-
Notifications
You must be signed in to change notification settings - Fork 0
/
htmlescape.c
95 lines (65 loc) · 1.5 KB
/
htmlescape.c
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
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
// Return the number of times the string needle appears in the string s.
size_t
htmlescape_count(const char *s, const char *needle)
{
size_t n = 0;
size_t needlesz = 0;
if (!needle || strlen(needle) == 0)
return n;
if (!s || strlen(s) == 0)
return n;
if (strlen(needle) == 1)
/*
* I'm guessing this is faster than strstr below.
*/
for (; *s; n += ( *s == needle[0] ), s++ );
else {
needlesz = strlen(needle);
while ((s = strstr(s, needle))) {
s += needlesz;
n++;
}
}
return n;
}
int
htmlescape(const char *src, char **dst)
{
char *p = 0;
static char *fromto[] = {
"&", "&",
"<", "<",
">", ">",
"\\\"", """ };
size_t dstsz = 0;
size_t fromtosz = 0;
size_t i = 0;
int rval = 0;
if (!src || !dst || !strlen(src))
return rval;
fromtosz = sizeof(fromto) / sizeof(fromto[0]);
dstsz = strlen(src);
for (i = 0; i < fromtosz; i += 2) {
size_t sz0 = strlen(fromto[i]);
size_t sz1 = strlen(fromto[i + 1]);
dstsz += htmlescape_count(src, fromto[i]) * (sz1 - sz0);
}
if ( (*dst = calloc(dstsz + 1, 1)) == NULL)
rval = ENOMEM;
for (p = *dst; *src && !rval; src++) {
for (i = 0; i < fromtosz; i += 2)
if ( !strncmp(src, fromto[i], strlen(fromto[i] ) ) ) {
memcpy(p, fromto[i + 1], strlen(fromto[i + 1]));
p += strlen(p);
src += strlen(fromto[i]) - 1;
break;
}
if (i == fromtosz)
*p++ = *src;
}
return rval;
}