xref: /plan9/acme/wiki/src/util.c (revision 9a747e4fd48b9f4522c70c07e8f882a15030f964)
1 #include "awiki.h"
2 
3 void*
emalloc(uint n)4 emalloc(uint n)
5 {
6 	void *p;
7 
8 	p = malloc(n);
9 	if(p == nil)
10 		error("can't malloc: %r");
11 	memset(p, 0, n);
12 	return p;
13 }
14 
15 char*
estrdup(char * s)16 estrdup(char *s)
17 {
18 	char *t;
19 
20 	t = emalloc(strlen(s)+1);
21 	strcpy(t, s);
22 	return t;
23 }
24 
25 char*
estrstrdup(char * s,char * t)26 estrstrdup(char *s, char *t)
27 {
28 	char *u;
29 
30 	u = emalloc(strlen(s)+strlen(t)+1);
31 	strcpy(u, s);
32 	strcat(u, t);
33 	return u;
34 }
35 
36 char*
eappend(char * s,char * sep,char * t)37 eappend(char *s, char *sep, char *t)
38 {
39 	char *u;
40 
41 	if(t == nil)
42 		u = estrstrdup(s, sep);
43 	else{
44 		u = emalloc(strlen(s)+strlen(sep)+strlen(t)+1);
45 		strcpy(u, s);
46 		strcat(u, sep);
47 		strcat(u, t);
48 	}
49 	free(s);
50 	return u;
51 }
52 
53 char*
egrow(char * s,char * sep,char * t)54 egrow(char *s, char *sep, char *t)
55 {
56 	s = eappend(s, sep, t);
57 	free(t);
58 	return s;
59 }
60 
61 void
error(char * fmt,...)62 error(char *fmt, ...)
63 {
64 	int n;
65 	va_list arg;
66 	char buf[256];
67 
68 	fprint(2, "Wiki: ");
69 	va_start(arg, fmt);
70 	n = vseprint(buf, buf+sizeof buf, fmt, arg) - buf;
71 	va_end(arg);
72 	write(2, buf, n);
73 	write(2, "\n", 1);
74 	threadexitsall(fmt);
75 }
76 
77 void
ctlprint(int fd,char * fmt,...)78 ctlprint(int fd, char *fmt, ...)
79 {
80 	int n;
81 	va_list arg;
82 	char buf[256];
83 
84 	va_start(arg, fmt);
85 	n = vseprint(buf, buf+sizeof buf, fmt, arg) - buf;
86 	va_end(arg);
87 	if(write(fd, buf, n) != n)
88 		error("control file write(%s) error: %r", buf);
89 }
90