1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include <String.h>
5 #include <ctype.h>
6 #include <thread.h>
7 #include "wiki.h"
8
9 void*
erealloc(void * v,ulong n)10 erealloc(void *v, ulong n)
11 {
12 v = realloc(v, n);
13 if(v == nil)
14 sysfatal("out of memory reallocating %lud", n);
15 setmalloctag(v, getcallerpc(&v));
16 return v;
17 }
18
19 void*
emalloc(ulong n)20 emalloc(ulong n)
21 {
22 void *v;
23
24 v = malloc(n);
25 if(v == nil)
26 sysfatal("out of memory allocating %lud", n);
27 memset(v, 0, n);
28 setmalloctag(v, getcallerpc(&n));
29 return v;
30 }
31
32 char*
estrdup(char * s)33 estrdup(char *s)
34 {
35 int l;
36 char *t;
37
38 if (s == nil)
39 return nil;
40 l = strlen(s)+1;
41 t = emalloc(l);
42 memmove(t, s, l);
43 setmalloctag(t, getcallerpc(&s));
44 return t;
45 }
46
47 char*
estrdupn(char * s,int n)48 estrdupn(char *s, int n)
49 {
50 int l;
51 char *t;
52
53 l = strlen(s);
54 if(l > n)
55 l = n;
56 t = emalloc(l+1);
57 memmove(t, s, l);
58 t[l] = '\0';
59 setmalloctag(t, getcallerpc(&s));
60 return t;
61 }
62
63 char*
strlower(char * s)64 strlower(char *s)
65 {
66 char *p;
67
68 for(p=s; *p; p++)
69 if('A' <= *p && *p <= 'Z')
70 *p += 'a'-'A';
71 return s;
72 }
73
74 String*
s_appendsub(String * s,char * p,int n,Sub * sub,int nsub)75 s_appendsub(String *s, char *p, int n, Sub *sub, int nsub)
76 {
77 int i, m;
78 char *q, *r, *ep;
79
80 ep = p+n;
81 while(p<ep){
82 q = ep;
83 m = -1;
84 for(i=0; i<nsub; i++){
85 if(sub[i].sub && (r = strstr(p, sub[i].match)) && r < q){
86 q = r;
87 m = i;
88 }
89 }
90 s = s_nappend(s, p, q-p);
91 p = q;
92 if(m >= 0){
93 s = s_append(s, sub[m].sub);
94 p += strlen(sub[m].match);
95 }
96 }
97 return s;
98 }
99
100 String*
s_appendlist(String * s,...)101 s_appendlist(String *s, ...)
102 {
103 char *x;
104 va_list arg;
105
106 va_start(arg, s);
107 while(x = va_arg(arg, char*))
108 s = s_append(s, x);
109 va_end(arg);
110 return s;
111 }
112
113 int
opentemp(char * template)114 opentemp(char *template)
115 {
116 int fd, i;
117 char *p;
118
119 p = estrdup(template);
120 fd = -1;
121 for(i=0; i<10; i++){
122 mktemp(p);
123 if(access(p, 0) < 0 && (fd=create(p, ORDWR|ORCLOSE, 0444)) >= 0)
124 break;
125 strcpy(p, template);
126 }
127 if(fd >= 0)
128 strcpy(template, p);
129 free(p);
130
131 return fd;
132 }
133
134