util.c (1765B)
1 #include <u.h> 2 #include <libc.h> 3 #include <bio.h> 4 #include <draw.h> 5 #include <html.h> 6 #include "dat.h" 7 8 void* 9 emalloc(ulong n) 10 { 11 void *p; 12 13 p = malloc(n); 14 if(p == nil) 15 error("can't malloc: %r"); 16 memset(p, 0, n); 17 return p; 18 } 19 20 void* 21 erealloc(void *p, ulong n) 22 { 23 p = realloc(p, n); 24 if(p == nil) 25 error("can't malloc: %r"); 26 return p; 27 } 28 29 char* 30 estrdup(char *s) 31 { 32 char *t; 33 34 t = emalloc(strlen(s)+1); 35 strcpy(t, s); 36 return t; 37 } 38 39 char* 40 estrstrdup(char *s, char *t) 41 { 42 long ns, nt; 43 char *u; 44 45 ns = strlen(s); 46 nt = strlen(t); 47 /* use malloc to avoid memset */ 48 u = malloc(ns+nt+1); 49 if(u == nil) 50 error("can't malloc: %r"); 51 memmove(u, s, ns); 52 memmove(u+ns, t, nt); 53 u[ns+nt] = '\0'; 54 return u; 55 } 56 57 char* 58 eappend(char *s, char *sep, char *t) 59 { 60 long ns, nsep, nt; 61 char *u; 62 63 if(t == nil) 64 u = estrstrdup(s, sep); 65 else{ 66 ns = strlen(s); 67 nsep = strlen(sep); 68 nt = strlen(t); 69 /* use malloc to avoid memset */ 70 u = malloc(ns+nsep+nt+1); 71 if(u == nil) 72 error("can't malloc: %r"); 73 memmove(u, s, ns); 74 memmove(u+ns, sep, nsep); 75 memmove(u+ns+nsep, t, nt); 76 u[ns+nsep+nt] = '\0'; 77 } 78 free(s); 79 return u; 80 } 81 82 char* 83 egrow(char *s, char *sep, char *t) 84 { 85 s = eappend(s, sep, t); 86 free(t); 87 return s; 88 } 89 90 void 91 error(char *fmt, ...) 92 { 93 va_list arg; 94 char buf[256]; 95 Fmt f; 96 97 fmtfdinit(&f, 2, buf, sizeof buf); 98 fmtprint(&f, "Mail: "); 99 va_start(arg, fmt); 100 fmtvprint(&f, fmt, arg); 101 va_end(arg); 102 fmtprint(&f, "\n"); 103 fmtfdflush(&f); 104 exits(fmt); 105 } 106 107 void 108 growbytes(Bytes *b, char *s, long ns) 109 { 110 if(b->nalloc < b->n + ns + 1){ 111 b->nalloc = b->n + ns + 8000; 112 /* use realloc to avoid memset */ 113 b->b = realloc(b->b, b->nalloc); 114 if(b->b == nil) 115 error("growbytes: can't realloc: %r"); 116 } 117 memmove(b->b+b->n, s, ns); 118 b->n += ns; 119 b->b[b->n] = '\0'; 120 }