Blob


1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include <thread.h>
5 #include <plumb.h>
6 #include <9pclient.h>
7 #include "dat.h"
9 void*
10 emalloc(uint n)
11 {
12 void *p;
14 p = malloc(n);
15 if(p == nil)
16 error("can't malloc: %r");
17 memset(p, 0, n);
18 setmalloctag(p, getcallerpc(&n));
19 return p;
20 }
22 void*
23 erealloc(void *p, uint n)
24 {
25 p = realloc(p, n);
26 if(p == nil)
27 error("can't realloc: %r");
28 setmalloctag(p, getcallerpc(&n));
29 return p;
30 }
32 char*
33 estrdup(char *s)
34 {
35 char *t;
37 t = emalloc(strlen(s)+1);
38 strcpy(t, s);
39 return t;
40 }
42 char*
43 estrstrdup(char *s, char *t)
44 {
45 char *u;
47 u = emalloc(strlen(s)+strlen(t)+1);
48 strcpy(u, s);
49 strcat(u, t);
50 return u;
51 }
53 char*
54 eappend(char *s, char *sep, char *t)
55 {
56 char *u;
58 if(t == nil)
59 u = estrstrdup(s, sep);
60 else{
61 u = emalloc(strlen(s)+strlen(sep)+strlen(t)+1);
62 strcpy(u, s);
63 strcat(u, sep);
64 strcat(u, t);
65 }
66 free(s);
67 return u;
68 }
70 char*
71 egrow(char *s, char *sep, char *t)
72 {
73 s = eappend(s, sep, t);
74 free(t);
75 return s;
76 }
78 void
79 error(char *fmt, ...)
80 {
81 Fmt f;
82 char buf[64];
83 va_list arg;
85 fmtfdinit(&f, 2, buf, sizeof buf);
86 fmtprint(&f, "Mail: ");
87 va_start(arg, fmt);
88 fmtvprint(&f, fmt, arg);
89 va_end(arg);
90 fmtprint(&f, "\n");
91 fmtfdflush(&f);
92 threadexitsall(fmt);
93 }
95 #if 0 /* jpc */
96 void
97 ctlprint(int fd, char *fmt, ...)
98 {
99 int n;
100 va_list arg;
102 va_start(arg, fmt);
103 n = vfprint(fd, fmt, arg);
104 va_end(arg);
105 fsync(fd);
106 if(n <= 0)
107 error("control file write error: %r");
109 #endif
111 void
112 ctlprint(CFid* fd, char *fmt, ...)
114 int n;
115 va_list arg;
116 char tmp[250];
118 va_start(arg, fmt);
119 n = vsnprint(tmp, 250, fmt, arg);
120 va_end(arg);
121 n = fswrite(fd, tmp, strlen(tmp));
122 if(n <= 0)
123 error("control file write error: %r");
126 int fsprint(CFid *fid, char* fmt, ...) {
127 // example call this replaces: Bprint(b, ">%s%s\n", lines[i][0]=='>'? "" : " ", lines[i]);
128 char *tmp;
129 va_list arg;
130 int n, tlen;
132 tmp = emalloc( tlen=(strlen(fmt)+250) ); // leave room for interpolated text
133 va_start(arg, fmt);
134 n = vsnprint(tmp, tlen, fmt, arg);
135 va_end(arg);
136 if(n == tlen)
137 error("fsprint formatting error");
138 n = fswrite(fid, tmp, strlen(tmp));
139 if(n <= 0)
140 error("fsprint write error: %r");
141 free(tmp);
143 return n;
146 #if 0 /* jpc */
147 /*
148 here's a read construct (from winselection) that may be useful in fsprint - think about it.
149 */
150 int m, n;
151 char *buf;
152 char tmp[256];
153 CFid* fid;
155 fid = winopenfid1(w, "rdsel", OREAD);
156 if(fid == nil)
157 error("can't open rdsel: %r");
158 n = 0;
159 buf = nil;
161 for(;;){
162 m = fsread(fid, tmp, sizeof tmp);
163 if(m <= 0)
164 break;
165 buf = erealloc(buf, n+m+1);
166 memmove(buf+n, tmp, m);
167 n += m;
168 buf[n] = '\0';
170 #endif