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