ref: fd3391f84165bf8d637bec678142f07044d52f1d
dir: /util.c/
#include <u.h> #include <libc.h> #include <bio.h> #include <thread.h> #include <regexp.h> #include <json.h> #include "masto9.h" void * emalloc(ulong n) { void *v; if((v = mallocz(n, 1)) == nil) sysfatal("malloc: %r"); setmalloctag(v, getcallerpc(&n)); return v; } void * erealloc(void *p, ulong n) { void *v; if((v = realloc(p, n)) == nil) sysfatal("realloc: %r"); setmalloctag(v, getcallerpc(&p)); return v; } char * estrdup(char *s) { if((s = strdup(s)) == nil) sysfatal("strdup: %r"); setmalloctag(s, getcallerpc(&s)); return s; } char * esmprint(char *fmt, ...) { char *s; va_list ap; va_start(ap, fmt); s = vsmprint(fmt, ap); va_end(ap); if(s == nil) sysfatal("smprint: %r"); setmalloctag(s, getcallerpc(&fmt)); return s; } char * fslurp(int fd, int *nbuf) { int n, sz, r; char *buf; n = 0; sz = 128; buf = emalloc(sz); while(1) { r = read(fd, buf + n, sz - n); if(r == 0) break; if(r == -1) goto error; n += r; if(n == sz) { sz += sz / 2; buf = erealloc(buf, sz); } } buf[n] = 0; if(nbuf) *nbuf = n; return buf; error: free(buf); return nil; } void removesubstring(char *str, char *sub) { int len = strlen(sub); while((str = strstr(str, sub))) { memmove(str, str + len, strlen(str + len) + 1); } } void removetag(char *str, char *tag) { char *start = strstr(str, tag); while(start) { char *end = strchr(start, '>'); if(end) { memmove(start, end + 1, strlen(end + 1) + 1); } else { *start = '\0'; break; } start = strstr(start, tag); } } JSON * getjsonkey(JSON *obj, char *key) { JSON *value; if((value = jsonbyname(obj, key)) == nil) sysfatal("getjsonkey: jsonbyname: key %s not found in %J", key, obj); return value; } FileAttachment * readfile(char *filename) { int fd, nread, size = 0, bufsize = 1024; FileAttachment *fa = emalloc(sizeof(FileAttachment)); char *buf = emalloc(bufsize); if((fd = open(filename, OREAD)) < 0) sysfatal("readfile: open %s: %r", filename); while((nread = read(fd, buf + size, bufsize - size)) > 0) { size += nread; if(size == bufsize) { bufsize *= 2; buf = realloc(buf, bufsize); if(!buf) sysfatal("readfile: realloc failed"); } } close(fd); if(nread < 0) sysfatal("readfile: read %s: %r", filename); buf[size] = '\0'; fa->buf = buf; fa->size = size; return fa; } char * basename(char *path) { char *base = strrchr(path, '/'); return base ? base + 1 : path; }