aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/htmlfmt/util.c
blob: b22b0ab56e756c443b79e198990194672d40b32d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <u.h>
#include <libc.h>
#include <bio.h>
#include <draw.h>
#include <html.h>
#include "dat.h"

void*
emalloc(ulong n)
{
	void *p;

	p = malloc(n);
	if(p == nil)
		error("can't malloc: %r");
	memset(p, 0, n);
	return p;
}

void*
erealloc(void *p, ulong n)
{
	p = realloc(p, n);
	if(p == nil)
		error("can't malloc: %r");
	return p;
}

char*
estrdup(char *s)
{
	char *t;

	t = emalloc(strlen(s)+1);
	strcpy(t, s);
	return t;
}

char*
estrstrdup(char *s, char *t)
{
	long ns, nt;
	char *u;

	ns = strlen(s);
	nt = strlen(t);
	/* use malloc to avoid memset */
	u = malloc(ns+nt+1);
	if(u == nil)
		error("can't malloc: %r");
	memmove(u, s, ns);
	memmove(u+ns, t, nt);
	u[ns+nt] = '\0';
	return u;
}

char*
eappend(char *s, char *sep, char *t)
{
	long ns, nsep, nt;
	char *u;

	if(t == nil)
		u = estrstrdup(s, sep);
	else{
		ns = strlen(s);
		nsep = strlen(sep);
		nt = strlen(t);
		/* use malloc to avoid memset */
		u = malloc(ns+nsep+nt+1);
		if(u == nil)
			error("can't malloc: %r");
		memmove(u, s, ns);
		memmove(u+ns, sep, nsep);
		memmove(u+ns+nsep, t, nt);
		u[ns+nsep+nt] = '\0';
	}
	free(s);
	return u;
}

char*
egrow(char *s, char *sep, char *t)
{
	s = eappend(s, sep, t);
	free(t);
	return s;
}

void
error(char *fmt, ...)
{
	va_list arg;
	char buf[256];
	Fmt f;

	fmtfdinit(&f, 2, buf, sizeof buf);
	fmtprint(&f, "Mail: ");
	va_start(arg, fmt);
	fmtvprint(&f, fmt, arg);
	va_end(arg);
	fmtprint(&f, "\n");
	fmtfdflush(&f);
	exits(fmt);
}

void
growbytes(Bytes *b, char *s, long ns)
{
	if(b->nalloc < b->n + ns + 1){
		b->nalloc = b->n + ns + 8000;
		/* use realloc to avoid memset */
		b->b = realloc(b->b, b->nalloc);
		if(b->b == nil)
			error("growbytes: can't realloc: %r");
	}
	memmove(b->b+b->n, s, ns);
	b->n += ns;
	b->b[b->n] = '\0';
}