ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/common/ezxml.c
Revision: 2.8
Committed: Thu Apr 2 16:40:32 2015 UTC (9 years, 1 month ago) by greg
Content type: text/plain
Branch: MAIN
CVS Tags: rad5R0
Changes since 2.7: +9 -1 lines
Log Message:
Support for color BSDF rendering using Klems representation

File Contents

# User Rev Content
1 greg 2.1 #ifndef lint
2 greg 2.8 static const char RCSid[] = "$Id: ezxml.c,v 2.7 2015/02/14 00:34:43 greg Exp $";
3 greg 2.1 #endif
4     /* ezxml.c
5     *
6     * Copyright 2004-2006 Aaron Voisine <[email protected]>
7     *
8     * Permission is hereby granted, free of charge, to any person obtaining
9     * a copy of this software and associated documentation files (the
10     * "Software"), to deal in the Software without restriction, including
11     * without limitation the rights to use, copy, modify, merge, publish,
12     * distribute, sublicense, and/or sell copies of the Software, and to
13     * permit persons to whom the Software is furnished to do so, subject to
14     * the following conditions:
15     *
16     * The above copyright notice and this permission notice shall be included
17     * in all copies or substantial portions of the Software.
18     *
19     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20     * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21     * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22     * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
23     * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24     * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25     * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26     */
27    
28     #include <stdlib.h>
29     #include <stdio.h>
30     #include <stdarg.h>
31     #include <string.h>
32     #include <ctype.h>
33     #include <sys/types.h>
34     #ifndef EZXML_NOMMAP
35     #include <unistd.h>
36     #include <sys/mman.h>
37 greg 2.2 #endif /* EZXML_NOMMAP */
38 greg 2.1 #include <sys/stat.h>
39     #include "ezxml.h"
40    
41 greg 2.3 #ifdef _WIN32
42     #include <io.h>
43     #define read _read
44     #define open _open
45     #define close _close
46     #endif
47    
48 greg 2.2 #define EZXML_WS "\t\r\n " /* whitespace */
49     #define EZXML_ERRL 128 /* maximum error string length */
50 greg 2.1
51     typedef struct ezxml_root *ezxml_root_t;
52 greg 2.2 struct ezxml_root { /* additional data for the root tag */
53     struct ezxml xml; /* is a super-struct built on top of ezxml struct */
54     ezxml_t cur; /* current xml tree insertion point */
55     char *m; /* original xml string */
56     size_t len; /* length of allocated memory for mmap, -1 for malloc */
57     char *u; /* UTF-8 conversion of string if original was UTF-16 */
58     char *s; /* start of work area */
59     char *e; /* end of work area */
60     char **ent; /* general entities (ampersand sequences) */
61     char ***attr; /* default attributes */
62     char ***pi; /* processing instructions */
63     short standalone; /* non-zero if <?xml standalone="yes"?> */
64     char err[EZXML_ERRL]; /* error string */
65 greg 2.1 };
66    
67 greg 2.2 char *EZXML_NIL[] = { NULL }; /* empty, null terminated array of strings */
68 greg 2.1
69 greg 2.2 /* returns the first child tag with the given name or NULL if not found */
70 greg 2.1 ezxml_t ezxml_child(ezxml_t xml, const char *name)
71     {
72     xml = (xml) ? xml->child : NULL;
73     while (xml && strcmp(name, xml->name)) xml = xml->sibling;
74     return xml;
75     }
76    
77 greg 2.8 /* returns the given tag's character content or empty string if none */
78     char *ezxml_txt(ezxml_t xml)
79     {
80     if (xml == NULL)
81     return "";
82     return xml->txt;
83     }
84    
85 greg 2.2 /* returns the Nth tag with the same name in the same subsection or NULL if not */
86     /* found */
87 greg 2.1 ezxml_t ezxml_idx(ezxml_t xml, int idx)
88     {
89     for (; xml && idx; idx--) xml = xml->next;
90     return xml;
91     }
92    
93 greg 2.2 /* returns the value of the requested tag attribute or NULL if not found */
94 greg 2.1 const char *ezxml_attr(ezxml_t xml, const char *attr)
95     {
96     int i = 0, j = 1;
97     ezxml_root_t root = (ezxml_root_t)xml;
98    
99     if (! xml || ! xml->attr) return NULL;
100     while (xml->attr[i] && strcmp(attr, xml->attr[i])) i += 2;
101 greg 2.2 if (xml->attr[i]) return xml->attr[i + 1]; /* found attribute */
102 greg 2.1
103 greg 2.2 while (root->xml.parent) root = (ezxml_root_t)root->xml.parent; /* root tag */
104 greg 2.1 for (i = 0; root->attr[i] && strcmp(xml->name, root->attr[i][0]); i++);
105 greg 2.2 if (! root->attr[i]) return NULL; /* no matching default attributes */
106 greg 2.1 while (root->attr[i][j] && strcmp(attr, root->attr[i][j])) j += 3;
107 greg 2.2 return (root->attr[i][j]) ? root->attr[i][j + 1] : NULL; /* found default */
108 greg 2.1 }
109    
110 greg 2.2 /* same as ezxml_get but takes an already initialized va_list */
111 greg 2.1 ezxml_t ezxml_vget(ezxml_t xml, va_list ap)
112     {
113     char *name = va_arg(ap, char *);
114     int idx = -1;
115    
116     if (name && *name) {
117     idx = va_arg(ap, int);
118     xml = ezxml_child(xml, name);
119     }
120     return (idx < 0) ? xml : ezxml_vget(ezxml_idx(xml, idx), ap);
121     }
122    
123 greg 2.2 /* Traverses the xml tree to retrieve a specific subtag. Takes a variable */
124     /* length list of tag names and indexes. The argument list must be terminated */
125     /* by either an index of -1 or an empty string tag name. Example: */
126     /* title = ezxml_get(library, "shelf", 0, "book", 2, "title", -1); */
127     /* This retrieves the title of the 3rd book on the 1st shelf of library. */
128     /* Returns NULL if not found. */
129 greg 2.1 ezxml_t ezxml_get(ezxml_t xml, ...)
130     {
131     va_list ap;
132     ezxml_t r;
133    
134     va_start(ap, xml);
135     r = ezxml_vget(xml, ap);
136     va_end(ap);
137     return r;
138     }
139    
140 greg 2.2 /* returns a null terminated array of processing instructions for the given */
141     /* target */
142 greg 2.1 const char **ezxml_pi(ezxml_t xml, const char *target)
143     {
144     ezxml_root_t root = (ezxml_root_t)xml;
145     int i = 0;
146    
147     if (! root) return (const char **)EZXML_NIL;
148 greg 2.2 while (root->xml.parent) root = (ezxml_root_t)root->xml.parent; /* root tag */
149     while (root->pi[i] && strcmp(target, root->pi[i][0])) i++; /* find target */
150 greg 2.1 return (const char **)((root->pi[i]) ? root->pi[i] + 1 : EZXML_NIL);
151     }
152    
153 greg 2.2 /* set an error string and return root */
154 greg 2.1 ezxml_t ezxml_err(ezxml_root_t root, char *s, const char *err, ...)
155     {
156     va_list ap;
157     int line = 1;
158     char *t, fmt[EZXML_ERRL];
159    
160     for (t = root->s; t < s; t++) if (*t == '\n') line++;
161 greg 2.4 sprintf(fmt, "[error near line %d]: %s", line, err);
162 greg 2.1
163     va_start(ap, err);
164     vsnprintf(root->err, EZXML_ERRL, fmt, ap);
165     va_end(ap);
166    
167     return &root->xml;
168     }
169    
170 greg 2.2 /* Recursively decodes entity and character references and normalizes new lines */
171     /* ent is a null terminated array of alternating entity names and values. set t */
172     /* to '&' for general entity decoding, '%' for parameter entity decoding, 'c' */
173     /* for cdata sections, ' ' for attribute normalization, or '*' for non-cdata */
174     /* attribute normalization. Returns s, or if the decoded string is longer than */
175     /* s, returns a malloced string that must be freed. */
176 greg 2.1 char *ezxml_decode(char *s, char **ent, char t)
177     {
178     char *e, *r = s, *m = s;
179     long b, c, d, l;
180    
181 greg 2.5 for (; *s; s++) /* normalize line endings */
182     if (*s == '\r') {
183     char *s2 = s+1;
184     do {
185     while (*s2 == '\r')
186     ++s2;
187     *s++ = *s2;
188     } while (*s2++);
189     break;
190     }
191 greg 2.1
192     for (s = r; ; ) {
193     while (*s && *s != '&' && (*s != '%' || t != '%') && !isspace(*s)) s++;
194    
195     if (! *s) break;
196 greg 2.2 else if (t != 'c' && ! strncmp(s, "&#", 2)) { /* character reference */
197     if (s[2] == 'x') c = strtol(s + 3, &e, 16); /* base 16 */
198     else c = strtol(s + 2, &e, 10); /* base 10 */
199     if (! c || *e != ';') { s++; continue; } /* not a character ref */
200    
201     if (c < 0x80) *(s++) = c; /* US-ASCII subset */
202     else { /* multi-byte UTF-8 sequence */
203     for (b = 0, d = c; d; d /= 2) b++; /* number of bits in c */
204     b = (b - 2) / 5; /* number of bytes in payload */
205     *(s++) = (0xFF << (7 - b)) | (c >> (6 * b)); /* head */
206     while (b) *(s++) = 0x80 | ((c >> (6 * --b)) & 0x3F); /* payload */
207 greg 2.1 }
208    
209     memmove(s, strchr(s, ';') + 1, strlen(strchr(s, ';')));
210     }
211     else if ((*s == '&' && (t == '&' || t == ' ' || t == '*')) ||
212 greg 2.2 (*s == '%' && t == '%')) { /* entity reference */
213 greg 2.1 for (b = 0; ent[b] && strncmp(s + 1, ent[b], strlen(ent[b]));
214 greg 2.2 b += 2); /* find entity in entity list */
215 greg 2.1
216 greg 2.2 if (ent[b++]) { /* found a match */
217 greg 2.1 if ((c = strlen(ent[b])) - 1 > (e = strchr(s, ';')) - s) {
218 greg 2.2 l = (d = (s - r)) + c + strlen(e); /* new length */
219 greg 2.1 r = (r == m) ? strcpy(malloc(l), r) : realloc(r, l);
220 greg 2.2 e = strchr((s = r + d), ';'); /* fix up pointers */
221 greg 2.1 }
222    
223 greg 2.2 memmove(s + c, e + 1, strlen(e)); /* shift rest of string */
224     strncpy(s, ent[b], c); /* copy in replacement text */
225 greg 2.1 }
226 greg 2.2 else s++; /* not a known entity */
227 greg 2.1 }
228     else if ((t == ' ' || t == '*') && isspace(*s)) *(s++) = ' ';
229 greg 2.2 else s++; /* no decoding needed */
230 greg 2.1 }
231    
232 greg 2.2 if (t == '*') { /* normalize spaces for non-cdata attributes */
233 greg 2.1 for (s = r; *s; s++) {
234     if ((l = strspn(s, " "))) memmove(s, s + l, strlen(s + l) + 1);
235     while (*s && *s != ' ') s++;
236     }
237 greg 2.2 if (--s >= r && *s == ' ') *s = '\0'; /* trim any trailing space */
238 greg 2.1 }
239     return r;
240     }
241    
242 greg 2.2 /* called when parser finds start of new tag */
243 greg 2.1 void ezxml_open_tag(ezxml_root_t root, char *name, char **attr)
244     {
245     ezxml_t xml = root->cur;
246    
247     if (xml->name) xml = ezxml_add_child(xml, name, strlen(xml->txt));
248 greg 2.2 else xml->name = name; /* first open tag */
249 greg 2.1
250     xml->attr = attr;
251 greg 2.2 root->cur = xml; /* update tag insertion point */
252 greg 2.1 }
253    
254 greg 2.2 /* called when parser finds character content between open and closing tag */
255 greg 2.1 void ezxml_char_content(ezxml_root_t root, char *s, size_t len, char t)
256     {
257     ezxml_t xml = root->cur;
258     char *m = s;
259     size_t l;
260    
261 greg 2.2 if (! xml || ! xml->name || ! len) return; /* sanity check */
262 greg 2.1
263 greg 2.2 s[len] = '\0'; /* null terminate text (calling functions anticipate this) */
264 greg 2.1 len = strlen(s = ezxml_decode(s, root->ent, t)) + 1;
265    
266 greg 2.2 if (! *(xml->txt)) xml->txt = s; /* initial character content */
267     else { /* allocate our own memory and make a copy */
268     xml->txt = (xml->flags & EZXML_TXTM) /* allocate some space */
269 greg 2.1 ? realloc(xml->txt, (l = strlen(xml->txt)) + len)
270     : strcpy(malloc((l = strlen(xml->txt)) + len), xml->txt);
271 greg 2.2 strcpy(xml->txt + l, s); /* add new char content */
272     if (s != m) free(s); /* free s if it was malloced by ezxml_decode() */
273 greg 2.1 }
274    
275     if (xml->txt != m) ezxml_set_flag(xml, EZXML_TXTM);
276     }
277    
278 greg 2.2 /* called when parser finds closing tag */
279 greg 2.1 ezxml_t ezxml_close_tag(ezxml_root_t root, char *name, char *s)
280     {
281     if (! root->cur || ! root->cur->name || strcmp(name, root->cur->name))
282     return ezxml_err(root, s, "unexpected closing tag </%s>", name);
283    
284     root->cur = root->cur->parent;
285     return NULL;
286     }
287    
288 greg 2.2 /* checks for circular entity references, returns non-zero if no circular */
289     /* references are found, zero otherwise */
290 greg 2.1 int ezxml_ent_ok(char *name, char *s, char **ent)
291     {
292     int i;
293    
294     for (; ; s++) {
295 greg 2.2 while (*s && *s != '&') s++; /* find next entity reference */
296 greg 2.1 if (! *s) return 1;
297 greg 2.2 if (! strncmp(s + 1, name, strlen(name))) return 0; /* circular ref. */
298 greg 2.1 for (i = 0; ent[i] && strncmp(ent[i], s + 1, strlen(ent[i])); i += 2);
299     if (ent[i] && ! ezxml_ent_ok(name, ent[i + 1], ent)) return 0;
300     }
301     }
302    
303 greg 2.2 /* called when the parser finds a processing instruction */
304 greg 2.1 void ezxml_proc_inst(ezxml_root_t root, char *s, size_t len)
305     {
306     int i = 0, j = 1;
307     char *target = s;
308    
309 greg 2.2 s[len] = '\0'; /* null terminate instruction */
310 greg 2.1 if (*(s += strcspn(s, EZXML_WS))) {
311 greg 2.2 *s = '\0'; /* null terminate target */
312     s += strspn(s + 1, EZXML_WS) + 1; /* skip whitespace after target */
313 greg 2.1 }
314    
315 greg 2.2 if (! strcmp(target, "xml")) { /* <?xml ... ?> */
316 greg 2.1 if ((s = strstr(s, "standalone")) && ! strncmp(s + strspn(s + 10,
317     EZXML_WS "='\"") + 10, "yes", 3)) root->standalone = 1;
318     return;
319     }
320    
321 greg 2.2 if (! root->pi[0]) *(root->pi = malloc(sizeof(char **))) = NULL; /*first pi */
322 greg 2.1
323 greg 2.2 while (root->pi[i] && strcmp(target, root->pi[i][0])) i++; /* find target */
324     if (! root->pi[i]) { /* new target */
325 greg 2.1 root->pi = realloc(root->pi, sizeof(char **) * (i + 2));
326     root->pi[i] = malloc(sizeof(char *) * 3);
327     root->pi[i][0] = target;
328 greg 2.2 root->pi[i][1] = (char *)(root->pi[i + 1] = NULL); /* terminate pi list */
329     root->pi[i][2] = strdup(""); /* empty document position list */
330 greg 2.1 }
331    
332 greg 2.2 while (root->pi[i][j]) j++; /* find end of instruction list for this target */
333 greg 2.1 root->pi[i] = realloc(root->pi[i], sizeof(char *) * (j + 3));
334     root->pi[i][j + 2] = realloc(root->pi[i][j + 1], j + 1);
335     strcpy(root->pi[i][j + 2] + j - 1, (root->xml.name) ? ">" : "<");
336 greg 2.2 root->pi[i][j + 1] = NULL; /* null terminate pi list for this target */
337     root->pi[i][j] = s; /* set instruction */
338 greg 2.1 }
339    
340 greg 2.2 /* called when the parser finds an internal doctype subset */
341 greg 2.1 short ezxml_internal_dtd(ezxml_root_t root, char *s, size_t len)
342     {
343     char q, *c, *t, *n = NULL, *v, **ent, **pe;
344     int i, j;
345    
346     pe = memcpy(malloc(sizeof(EZXML_NIL)), EZXML_NIL, sizeof(EZXML_NIL));
347    
348     for (s[len] = '\0'; s; ) {
349 greg 2.2 while (*s && *s != '<' && *s != '%') s++; /* find next declaration */
350 greg 2.1
351     if (! *s) break;
352 greg 2.2 else if (! strncmp(s, "<!ENTITY", 8)) { /* parse entity definitions */
353     c = s += strspn(s + 8, EZXML_WS) + 8; /* skip white space separator */
354     n = s + strspn(s, EZXML_WS "%"); /* find name */
355     *(s = n + strcspn(n, EZXML_WS)) = ';'; /* append ; to name */
356 greg 2.1
357 greg 2.2 v = s + strspn(s + 1, EZXML_WS) + 1; /* find value */
358     if ((q = *(v++)) != '"' && q != '\'') { /* skip externals */
359 greg 2.1 s = strchr(s, '>');
360     continue;
361     }
362    
363     for (i = 0, ent = (*c == '%') ? pe : root->ent; ent[i]; i++);
364 greg 2.2 ent = realloc(ent, (i + 3) * sizeof(char *)); /* space for next ent */
365 greg 2.1 if (*c == '%') pe = ent;
366     else root->ent = ent;
367    
368 greg 2.2 *(++s) = '\0'; /* null terminate name */
369     if ((s = strchr(v, q))) *(s++) = '\0'; /* null terminate value */
370     ent[i + 1] = ezxml_decode(v, pe, '%'); /* set value */
371     ent[i + 2] = NULL; /* null terminate entity list */
372     if (! ezxml_ent_ok(n, ent[i + 1], ent)) { /* circular reference */
373 greg 2.1 if (ent[i + 1] != v) free(ent[i + 1]);
374     ezxml_err(root, v, "circular entity declaration &%s", n);
375     break;
376     }
377 greg 2.2 else ent[i] = n; /* set entity name */
378 greg 2.1 }
379 greg 2.2 else if (! strncmp(s, "<!ATTLIST", 9)) { /* parse default attributes */
380     t = s + strspn(s + 9, EZXML_WS) + 9; /* skip whitespace separator */
381 greg 2.1 if (! *t) { ezxml_err(root, t, "unclosed <!ATTLIST"); break; }
382     if (*(s = t + strcspn(t, EZXML_WS ">")) == '>') continue;
383 greg 2.2 else *s = '\0'; /* null terminate tag name */
384 greg 2.1 for (i = 0; root->attr[i] && strcmp(n, root->attr[i][0]); i++);
385 greg 2.6 ++s;
386     while (*(n = s + strspn(s, EZXML_WS)) && *n != '>') {
387 greg 2.2 if (*(s = n + strcspn(n, EZXML_WS))) *s = '\0'; /* attr name */
388 greg 2.1 else { ezxml_err(root, t, "malformed <!ATTLIST"); break; }
389    
390 greg 2.2 s += strspn(s + 1, EZXML_WS) + 1; /* find next token */
391     c = (strncmp(s, "CDATA", 5)) ? "*" : " "; /* is it cdata? */
392 greg 2.1 if (! strncmp(s, "NOTATION", 8))
393     s += strspn(s + 8, EZXML_WS) + 8;
394     s = (*s == '(') ? strchr(s, ')') : s + strcspn(s, EZXML_WS);
395     if (! s) { ezxml_err(root, t, "malformed <!ATTLIST"); break; }
396    
397 greg 2.2 s += strspn(s, EZXML_WS ")"); /* skip white space separator */
398 greg 2.1 if (! strncmp(s, "#FIXED", 6))
399     s += strspn(s + 6, EZXML_WS) + 6;
400 greg 2.2 if (*s == '#') { /* no default value */
401 greg 2.1 s += strcspn(s, EZXML_WS ">") - 1;
402 greg 2.2 if (*c == ' ') continue; /* cdata is default, nothing to do */
403 greg 2.1 v = NULL;
404     }
405 greg 2.2 else if ((*s == '"' || *s == '\'') && /* default value */
406 greg 2.1 (s = strchr(v = s + 1, *s))) *s = '\0';
407     else { ezxml_err(root, t, "malformed <!ATTLIST"); break; }
408    
409 greg 2.2 if (! root->attr[i]) { /* new tag name */
410 greg 2.1 root->attr = (! i) ? malloc(2 * sizeof(char **))
411     : realloc(root->attr,
412     (i + 2) * sizeof(char **));
413     root->attr[i] = malloc(2 * sizeof(char *));
414 greg 2.2 root->attr[i][0] = t; /* set tag name */
415 greg 2.1 root->attr[i][1] = (char *)(root->attr[i + 1] = NULL);
416     }
417    
418 greg 2.2 for (j = 1; root->attr[i][j]; j += 3); /* find end of list */
419 greg 2.1 root->attr[i] = realloc(root->attr[i],
420     (j + 4) * sizeof(char *));
421    
422 greg 2.2 root->attr[i][j + 3] = NULL; /* null terminate list */
423     root->attr[i][j + 2] = c; /* is it cdata? */
424 greg 2.1 root->attr[i][j + 1] = (v) ? ezxml_decode(v, root->ent, *c)
425     : NULL;
426 greg 2.2 root->attr[i][j] = n; /* attribute name */
427 greg 2.6 ++s;
428 greg 2.1 }
429     }
430 greg 2.2 else if (! strncmp(s, "<!--", 4)) s = strstr(s + 4, "-->"); /* comments */
431     else if (! strncmp(s, "<?", 2)) { /* processing instructions */
432 greg 2.1 if ((s = strstr(c = s + 2, "?>")))
433     ezxml_proc_inst(root, c, s++ - c);
434     }
435 greg 2.2 else if (*s == '<') s = strchr(s, '>'); /* skip other declarations */
436 greg 2.1 else if (*(s++) == '%' && ! root->standalone) break;
437     }
438    
439     free(pe);
440     return ! *root->err;
441     }
442    
443 greg 2.2 /* Converts a UTF-16 string to UTF-8. Returns a new string that must be freed */
444     /* or NULL if no conversion was needed. */
445 greg 2.1 char *ezxml_str2utf8(char **s, size_t *len)
446     {
447     char *u;
448     size_t l = 0, sl, max = *len;
449     long c, d;
450     int b, be = (**s == '\xFE') ? 1 : (**s == '\xFF') ? 0 : -1;
451    
452 greg 2.2 if (be == -1) return NULL; /* not UTF-16 */
453 greg 2.1
454     u = malloc(max);
455     for (sl = 2; sl < *len - 1; sl += 2) {
456 greg 2.2 c = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF) /*UTF-16BE */
457     : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF); /*UTF-16LE */
458     if (c >= 0xD800 && c <= 0xDFFF && (sl += 2) < *len - 1) { /* high-half */
459 greg 2.1 d = (be) ? (((*s)[sl] & 0xFF) << 8) | ((*s)[sl + 1] & 0xFF)
460     : (((*s)[sl + 1] & 0xFF) << 8) | ((*s)[sl] & 0xFF);
461     c = (((c & 0x3FF) << 10) | (d & 0x3FF)) + 0x10000;
462     }
463    
464     while (l + 6 > max) u = realloc(u, max += EZXML_BUFSIZE);
465 greg 2.2 if (c < 0x80) u[l++] = c; /* US-ASCII subset */
466     else { /* multi-byte UTF-8 sequence */
467     for (b = 0, d = c; d; d /= 2) b++; /* bits in c */
468     b = (b - 2) / 5; /* bytes in payload */
469     u[l++] = (0xFF << (7 - b)) | (c >> (6 * b)); /* head */
470     while (b) u[l++] = 0x80 | ((c >> (6 * --b)) & 0x3F); /* payload */
471 greg 2.1 }
472     }
473     return *s = realloc(u, *len = l);
474     }
475    
476 greg 2.2 /* frees a tag attribute list */
477 greg 2.1 void ezxml_free_attr(char **attr) {
478     int i = 0;
479     char *m;
480    
481 greg 2.2 if (! attr || attr == EZXML_NIL) return; /* nothing to free */
482     while (attr[i]) i += 2; /* find end of attribute list */
483     m = attr[i + 1]; /* list of which names and values are malloced */
484 greg 2.1 for (i = 0; m[i]; i++) {
485     if (m[i] & EZXML_NAMEM) free(attr[i * 2]);
486     if (m[i] & EZXML_TXTM) free(attr[(i * 2) + 1]);
487     }
488     free(m);
489     free(attr);
490     }
491    
492 greg 2.2 /* parse the given xml string and return an ezxml structure */
493 greg 2.1 ezxml_t ezxml_parse_str(char *s, size_t len)
494     {
495     ezxml_root_t root = (ezxml_root_t)ezxml_new(NULL);
496 greg 2.2 char q, e, *d, **attr, **a = NULL; /* initialize a to avoid compile warning */
497 greg 2.1 int l, i, j;
498    
499     root->m = s;
500     if (! len) return ezxml_err(root, NULL, "root tag missing");
501 greg 2.2 root->u = ezxml_str2utf8(&s, &len); /* convert utf-16 to utf-8 */
502     root->e = (root->s = s) + len; /* record start and end of work area */
503 greg 2.1
504 greg 2.2 e = s[len - 1]; /* save end char */
505     s[len - 1] = '\0'; /* turn end char into null terminator */
506 greg 2.1
507 greg 2.2 while (*s && *s != '<') s++; /* find first tag */
508 greg 2.1 if (! *s) return ezxml_err(root, s, "root tag missing");
509    
510     for (; ; ) {
511     attr = (char **)EZXML_NIL;
512     d = ++s;
513    
514 greg 2.2 if (isalpha(*s) || *s == '_' || *s == ':' || *s < '\0') { /* new tag */
515 greg 2.1 if (! root->cur)
516     return ezxml_err(root, d, "markup outside of root element");
517    
518     s += strcspn(s, EZXML_WS "/>");
519 greg 2.2 while (isspace(*s)) *(s++) = '\0'; /* null terminate tag name */
520 greg 2.1
521 greg 2.2 if (*s && *s != '/' && *s != '>') /* find tag in default attr list */
522 greg 2.1 for (i = 0; (a = root->attr[i]) && strcmp(a[0], d); i++);
523    
524 greg 2.2 for (l = 0; *s && *s != '/' && *s != '>'; l += 2) { /* new attrib */
525 greg 2.1 attr = (l) ? realloc(attr, (l + 4) * sizeof(char *))
526 greg 2.2 : malloc(4 * sizeof(char *)); /* allocate space */
527 greg 2.1 attr[l + 3] = (l) ? realloc(attr[l + 1], (l / 2) + 2)
528 greg 2.2 : malloc(2); /* mem for list of maloced vals */
529     strcpy(attr[l + 3] + (l / 2), " "); /* value is not malloced */
530     attr[l + 2] = NULL; /* null terminate list */
531     attr[l + 1] = ""; /* temporary attribute value */
532     attr[l] = s; /* set attribute name */
533 greg 2.1
534     s += strcspn(s, EZXML_WS "=/>");
535     if (*s == '=' || isspace(*s)) {
536 greg 2.2 *(s++) = '\0'; /* null terminate tag attribute name */
537 greg 2.1 q = *(s += strspn(s, EZXML_WS "="));
538 greg 2.2 if (q == '"' || q == '\'') { /* attribute value */
539 greg 2.1 attr[l + 1] = ++s;
540     while (*s && *s != q) s++;
541 greg 2.2 if (*s) *(s++) = '\0'; /* null terminate attribute val */
542 greg 2.1 else {
543     ezxml_free_attr(attr);
544     return ezxml_err(root, d, "missing %c", q);
545     }
546    
547     for (j = 1; a && a[j] && strcmp(a[j], attr[l]); j +=3);
548     attr[l + 1] = ezxml_decode(attr[l + 1], root->ent, (a
549     && a[j]) ? *a[j + 2] : ' ');
550     if (attr[l + 1] < d || attr[l + 1] > s)
551 greg 2.2 attr[l + 3][l / 2] = EZXML_TXTM; /* value malloced */
552 greg 2.1 }
553     }
554     while (isspace(*s)) s++;
555     }
556    
557 greg 2.2 if (*s == '/') { /* self closing tag */
558 greg 2.1 *(s++) = '\0';
559     if ((*s && *s != '>') || (! *s && e != '>')) {
560     if (l) ezxml_free_attr(attr);
561     return ezxml_err(root, d, "missing >");
562     }
563     ezxml_open_tag(root, d, attr);
564     ezxml_close_tag(root, d, s);
565     }
566 greg 2.2 else if ((q = *s) == '>' || (! *s && e == '>')) { /* open tag */
567     *s = '\0'; /* temporarily null terminate tag name */
568 greg 2.1 ezxml_open_tag(root, d, attr);
569     *s = q;
570     }
571     else {
572     if (l) ezxml_free_attr(attr);
573     return ezxml_err(root, d, "missing >");
574     }
575     }
576 greg 2.2 else if (*s == '/') { /* close tag */
577 greg 2.1 s += strcspn(d = s + 1, EZXML_WS ">") + 1;
578     if (! (q = *s) && e != '>') return ezxml_err(root, d, "missing >");
579 greg 2.2 *s = '\0'; /* temporarily null terminate tag name */
580 greg 2.1 if (ezxml_close_tag(root, d, s)) return &root->xml;
581     if (isspace(*s = q)) s += strspn(s, EZXML_WS);
582     }
583 greg 2.2 else if (! strncmp(s, "!--", 3)) { /* xml comment */
584 greg 2.1 if (! (s = strstr(s + 3, "--")) || (*(s += 2) != '>' && *s) ||
585     (! *s && e != '>')) return ezxml_err(root, d, "unclosed <!--");
586     }
587 greg 2.2 else if (! strncmp(s, "![CDATA[", 8)) { /* cdata */
588 greg 2.1 if ((s = strstr(s, "]]>")))
589     ezxml_char_content(root, d + 8, (s += 2) - d - 10, 'c');
590     else return ezxml_err(root, d, "unclosed <![CDATA[");
591     }
592 greg 2.2 else if (! strncmp(s, "!DOCTYPE", 8)) { /* dtd */
593 greg 2.1 for (l = 0; *s && ((! l && *s != '>') || (l && (*s != ']' ||
594     *(s + strspn(s + 1, EZXML_WS) + 1) != '>')));
595     l = (*s == '[') ? 1 : l) s += strcspn(s + 1, "[]>") + 1;
596     if (! *s && e != '>')
597     return ezxml_err(root, d, "unclosed <!DOCTYPE");
598     d = (l) ? strchr(d, '[') + 1 : d;
599     if (l && ! ezxml_internal_dtd(root, d, s++ - d)) return &root->xml;
600     }
601 greg 2.2 else if (*s == '?') { /* <?...?> processing instructions */
602 greg 2.1 do { s = strchr(s, '?'); } while (s && *(++s) && *s != '>');
603     if (! s || (! *s && e != '>'))
604     return ezxml_err(root, d, "unclosed <?");
605     else ezxml_proc_inst(root, d + 1, s - d - 2);
606     }
607     else return ezxml_err(root, d, "unexpected <");
608    
609     if (! s || ! *s) break;
610     *s = '\0';
611     d = ++s;
612 greg 2.2 if (*s && *s != '<') { /* tag character content */
613 greg 2.1 while (*s && *s != '<') s++;
614     if (*s) ezxml_char_content(root, d, s - d, '&');
615     else break;
616     }
617     else if (! *s) break;
618     }
619    
620     if (! root->cur) return &root->xml;
621     else if (! root->cur->name) return ezxml_err(root, d, "root tag missing");
622     else return ezxml_err(root, d, "unclosed tag <%s>", root->cur->name);
623     }
624    
625 greg 2.2 /* Wrapper for ezxml_parse_str() that accepts a file stream. Reads the entire */
626     /* stream into memory and then parses it. For xml files, use ezxml_parse_file() */
627     /* or ezxml_parse_fd() */
628 greg 2.1 ezxml_t ezxml_parse_fp(FILE *fp)
629     {
630     ezxml_root_t root;
631     size_t l, len = 0;
632     char *s;
633    
634     if (! (s = malloc(EZXML_BUFSIZE))) return NULL;
635     do {
636     len += (l = fread((s + len), 1, EZXML_BUFSIZE, fp));
637     if (l == EZXML_BUFSIZE) s = realloc(s, len + EZXML_BUFSIZE);
638     } while (s && l == EZXML_BUFSIZE);
639    
640     if (! s) return NULL;
641     root = (ezxml_root_t)ezxml_parse_str(s, len);
642 greg 2.2 root->len = -1; /* so we know to free s in ezxml_free() */
643 greg 2.1 return &root->xml;
644     }
645    
646 greg 2.2 /* A wrapper for ezxml_parse_str() that accepts a file descriptor. First */
647     /* attempts to mem map the file. Failing that, reads the file into memory. */
648     /* Returns NULL on failure. */
649 greg 2.1 ezxml_t ezxml_parse_fd(int fd)
650     {
651     ezxml_root_t root;
652     struct stat st;
653     size_t l;
654     void *m;
655    
656     if (fd < 0) return NULL;
657     fstat(fd, &st);
658    
659     #ifndef EZXML_NOMMAP
660     l = (st.st_size + sysconf(_SC_PAGESIZE) - 1) & ~(sysconf(_SC_PAGESIZE) -1);
661     if ((m = mmap(NULL, l, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0))
662     != MAP_FAILED) {
663 greg 2.2 madvise(m, l, MADV_SEQUENTIAL); /* optimize for sequential access */
664 greg 2.1 root = (ezxml_root_t)ezxml_parse_str(m, st.st_size);
665 greg 2.2 madvise(m, root->len = l, MADV_NORMAL); /* put it back to normal */
666 greg 2.1 }
667 greg 2.2 else { /* mmap failed, read file into memory */
668     #endif /* EZXML_NOMMAP */
669 greg 2.1 l = read(fd, m = malloc(st.st_size), st.st_size);
670     root = (ezxml_root_t)ezxml_parse_str(m, l);
671 greg 2.2 root->len = -1; /* so we know to free s in ezxml_free() */
672 greg 2.1 #ifndef EZXML_NOMMAP
673     }
674 greg 2.2 #endif /* EZXML_NOMMAP */
675 greg 2.1 return &root->xml;
676     }
677    
678 greg 2.2 /* a wrapper for ezxml_parse_fd that accepts a file name */
679 greg 2.1 ezxml_t ezxml_parse_file(const char *file)
680     {
681     int fd = open(file, O_RDONLY, 0);
682     ezxml_t xml = ezxml_parse_fd(fd);
683    
684     if (fd >= 0) close(fd);
685     return xml;
686     }
687    
688 greg 2.2 /* Encodes ampersand sequences appending the results to *dst, reallocating *dst */
689     /* if length excedes max. a is non-zero for attribute encoding. Returns *dst */
690 greg 2.1 char *ezxml_ampencode(const char *s, size_t len, char **dst, size_t *dlen,
691     size_t *max, short a)
692     {
693     const char *e;
694    
695     for (e = s + len; s != e; s++) {
696     while (*dlen + 10 > *max) *dst = realloc(*dst, *max += EZXML_BUFSIZE);
697    
698     switch (*s) {
699     case '\0': return *dst;
700     case '&': *dlen += sprintf(*dst + *dlen, "&amp;"); break;
701     case '<': *dlen += sprintf(*dst + *dlen, "&lt;"); break;
702     case '>': *dlen += sprintf(*dst + *dlen, "&gt;"); break;
703     case '"': *dlen += sprintf(*dst + *dlen, (a) ? "&quot;" : "\""); break;
704     case '\n': *dlen += sprintf(*dst + *dlen, (a) ? "&#xA;" : "\n"); break;
705     case '\t': *dlen += sprintf(*dst + *dlen, (a) ? "&#x9;" : "\t"); break;
706     case '\r': *dlen += sprintf(*dst + *dlen, "&#xD;"); break;
707     default: (*dst)[(*dlen)++] = *s;
708     }
709     }
710     return *dst;
711     }
712    
713 greg 2.2 /* Recursively converts each tag to xml appending it to *s. Reallocates *s if */
714     /* its length excedes max. start is the location of the previous tag in the */
715     /* parent tag's character content. Returns *s. */
716 greg 2.1 char *ezxml_toxml_r(ezxml_t xml, char **s, size_t *len, size_t *max,
717     size_t start, char ***attr)
718     {
719     int i, j;
720     char *txt = (xml->parent) ? xml->parent->txt : "";
721     size_t off = 0;
722    
723 greg 2.2 /* parent character content up to this tag */
724 greg 2.1 *s = ezxml_ampencode(txt + start, xml->off - start, s, len, max, 0);
725    
726 greg 2.2 while (*len + strlen(xml->name) + 4 > *max) /* reallocate s */
727 greg 2.1 *s = realloc(*s, *max += EZXML_BUFSIZE);
728    
729 greg 2.2 *len += sprintf(*s + *len, "<%s", xml->name); /* open tag */
730     for (i = 0; xml->attr[i]; i += 2) { /* tag attributes */
731 greg 2.1 if (ezxml_attr(xml, xml->attr[i]) != xml->attr[i + 1]) continue;
732 greg 2.2 while (*len + strlen(xml->attr[i]) + 7 > *max) /* reallocate s */
733 greg 2.1 *s = realloc(*s, *max += EZXML_BUFSIZE);
734    
735     *len += sprintf(*s + *len, " %s=\"", xml->attr[i]);
736     ezxml_ampencode(xml->attr[i + 1], -1, s, len, max, 1);
737     *len += sprintf(*s + *len, "\"");
738     }
739    
740     for (i = 0; attr[i] && strcmp(attr[i][0], xml->name); i++);
741 greg 2.2 for (j = 1; attr[i] && attr[i][j]; j += 3) { /* default attributes */
742 greg 2.1 if (! attr[i][j + 1] || ezxml_attr(xml, attr[i][j]) != attr[i][j + 1])
743 greg 2.2 continue; /* skip duplicates and non-values */
744     while (*len + strlen(attr[i][j]) + 7 > *max) /* reallocate s */
745 greg 2.1 *s = realloc(*s, *max += EZXML_BUFSIZE);
746    
747     *len += sprintf(*s + *len, " %s=\"", attr[i][j]);
748     ezxml_ampencode(attr[i][j + 1], -1, s, len, max, 1);
749     *len += sprintf(*s + *len, "\"");
750     }
751     *len += sprintf(*s + *len, ">");
752    
753 greg 2.2 *s = (xml->child) ? ezxml_toxml_r(xml->child, s, len, max, 0, attr) /*child */
754     : ezxml_ampencode(xml->txt, -1, s, len, max, 0); /*data */
755 greg 2.1
756 greg 2.2 while (*len + strlen(xml->name) + 4 > *max) /* reallocate s */
757 greg 2.1 *s = realloc(*s, *max += EZXML_BUFSIZE);
758    
759 greg 2.2 *len += sprintf(*s + *len, "</%s>", xml->name); /* close tag */
760 greg 2.1
761 greg 2.2 while (txt[off] && off < xml->off) off++; /* make sure off is within bounds */
762 greg 2.1 return (xml->ordered) ? ezxml_toxml_r(xml->ordered, s, len, max, off, attr)
763     : ezxml_ampencode(txt + off, -1, s, len, max, 0);
764     }
765    
766 greg 2.2 /* Converts an ezxml structure back to xml. Returns a string of xml data that */
767     /* must be freed. */
768 greg 2.1 char *ezxml_toxml(ezxml_t xml)
769     {
770     ezxml_t p = (xml) ? xml->parent : NULL, o = (xml) ? xml->ordered : NULL;
771     ezxml_root_t root = (ezxml_root_t)xml;
772     size_t len = 0, max = EZXML_BUFSIZE;
773     char *s = strcpy(malloc(max), ""), *t, *n;
774     int i, j, k;
775    
776     if (! xml || ! xml->name) return realloc(s, len + 1);
777 greg 2.2 while (root->xml.parent) root = (ezxml_root_t)root->xml.parent; /* root tag */
778 greg 2.1
779 greg 2.2 for (i = 0; ! p && root->pi[i]; i++) { /* pre-root processing instructions */
780 greg 2.1 for (k = 2; root->pi[i][k - 1]; k++);
781     for (j = 1; (n = root->pi[i][j]); j++) {
782 greg 2.2 if (root->pi[i][k][j - 1] == '>') continue; /* not pre-root */
783 greg 2.1 while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
784     s = realloc(s, max += EZXML_BUFSIZE);
785     len += sprintf(s + len, "<?%s%s%s?>\n", t, *n ? " " : "", n);
786     }
787     }
788    
789     xml->parent = xml->ordered = NULL;
790     s = ezxml_toxml_r(xml, &s, &len, &max, 0, root->attr);
791     xml->parent = p;
792     xml->ordered = o;
793    
794 greg 2.2 for (i = 0; ! p && root->pi[i]; i++) { /* post-root processing instructions */
795 greg 2.1 for (k = 2; root->pi[i][k - 1]; k++);
796     for (j = 1; (n = root->pi[i][j]); j++) {
797 greg 2.2 if (root->pi[i][k][j - 1] == '<') continue; /* not post-root */
798 greg 2.1 while (len + strlen(t = root->pi[i][0]) + strlen(n) + 7 > max)
799     s = realloc(s, max += EZXML_BUFSIZE);
800     len += sprintf(s + len, "\n<?%s%s%s?>", t, *n ? " " : "", n);
801     }
802     }
803     return realloc(s, len + 1);
804     }
805    
806 greg 2.2 /* free the memory allocated for the ezxml structure */
807 greg 2.1 void ezxml_free(ezxml_t xml)
808     {
809     ezxml_root_t root = (ezxml_root_t)xml;
810     int i, j;
811     char **a, *s;
812    
813     if (! xml) return;
814     ezxml_free(xml->child);
815     ezxml_free(xml->ordered);
816    
817 greg 2.2 if (! xml->parent) { /* free root tag allocations */
818     for (i = 10; root->ent[i]; i += 2) /* 0 - 9 are default entites (<>&"') */
819 greg 2.1 if ((s = root->ent[i + 1]) < root->s || s > root->e) free(s);
820 greg 2.2 free(root->ent); /* free list of general entities */
821 greg 2.1
822     for (i = 0; (a = root->attr[i]); i++) {
823 greg 2.2 for (j = 1; a[j++]; j += 2) /* free malloced attribute values */
824 greg 2.1 if (a[j] && (a[j] < root->s || a[j] > root->e)) free(a[j]);
825     free(a);
826     }
827 greg 2.2 if (root->attr[0]) free(root->attr); /* free default attribute list */
828 greg 2.1
829     for (i = 0; root->pi[i]; i++) {
830     for (j = 1; root->pi[i][j]; j++);
831     free(root->pi[i][j + 1]);
832     free(root->pi[i]);
833     }
834 greg 2.2 if (root->pi[0]) free(root->pi); /* free processing instructions */
835 greg 2.1
836 greg 2.2 if (root->len == -1) free(root->m); /* malloced xml data */
837 greg 2.1 #ifndef EZXML_NOMMAP
838 greg 2.2 else if (root->len) munmap(root->m, root->len); /* mem mapped xml data */
839     #endif /* EZXML_NOMMAP */
840     if (root->u) free(root->u); /* utf8 conversion */
841 greg 2.1 }
842    
843 greg 2.2 ezxml_free_attr(xml->attr); /* tag attributes */
844     if ((xml->flags & EZXML_TXTM)) free(xml->txt); /* character content */
845     if ((xml->flags & EZXML_NAMEM)) free(xml->name); /* tag name */
846 greg 2.1 free(xml);
847     }
848    
849 greg 2.2 /* return parser error message or empty string if none */
850 greg 2.1 const char *ezxml_error(ezxml_t xml)
851     {
852 greg 2.2 while (xml && xml->parent) xml = xml->parent; /* find root tag */
853 greg 2.1 return (xml) ? ((ezxml_root_t)xml)->err : "";
854     }
855    
856 greg 2.2 /* returns a new empty ezxml structure with the given root tag name */
857 greg 2.1 ezxml_t ezxml_new(const char *name)
858     {
859     static char *ent[] = { "lt;", "&#60;", "gt;", "&#62;", "quot;", "&#34;",
860     "apos;", "&#39;", "amp;", "&#38;", NULL };
861     ezxml_root_t root = (ezxml_root_t)memset(malloc(sizeof(struct ezxml_root)),
862     '\0', sizeof(struct ezxml_root));
863     root->xml.name = (char *)name;
864     root->cur = &root->xml;
865     strcpy(root->err, root->xml.txt = "");
866     root->ent = memcpy(malloc(sizeof(ent)), ent, sizeof(ent));
867     root->attr = root->pi = (char ***)(root->xml.attr = EZXML_NIL);
868     return &root->xml;
869     }
870    
871 greg 2.2 /* inserts an existing tag into an ezxml structure */
872 greg 2.1 ezxml_t ezxml_insert(ezxml_t xml, ezxml_t dest, size_t off)
873     {
874     ezxml_t cur, prev, head;
875    
876     xml->next = xml->sibling = xml->ordered = NULL;
877     xml->off = off;
878     xml->parent = dest;
879    
880 greg 2.2 if ((head = dest->child)) { /* already have sub tags */
881     if (head->off <= off) { /* not first subtag */
882 greg 2.1 for (cur = head; cur->ordered && cur->ordered->off <= off;
883     cur = cur->ordered);
884     xml->ordered = cur->ordered;
885     cur->ordered = xml;
886     }
887 greg 2.2 else { /* first subtag */
888 greg 2.1 xml->ordered = head;
889     dest->child = xml;
890     }
891    
892     for (cur = head, prev = NULL; cur && strcmp(cur->name, xml->name);
893 greg 2.2 prev = cur, cur = cur->sibling); /* find tag type */
894     if (cur && cur->off <= off) { /* not first of type */
895 greg 2.1 while (cur->next && cur->next->off <= off) cur = cur->next;
896     xml->next = cur->next;
897     cur->next = xml;
898     }
899 greg 2.2 else { /* first tag of this type */
900     if (prev && cur) prev->sibling = cur->sibling; /* remove old first */
901     xml->next = cur; /* old first tag is now next */
902 greg 2.1 for (cur = head, prev = NULL; cur && cur->off <= off;
903 greg 2.2 prev = cur, cur = cur->sibling); /* new sibling insert point */
904 greg 2.1 xml->sibling = cur;
905     if (prev) prev->sibling = xml;
906     }
907     }
908 greg 2.2 else dest->child = xml; /* only sub tag */
909 greg 2.1
910     return xml;
911     }
912    
913 greg 2.2 /* Adds a child tag. off is the offset of the child tag relative to the start */
914     /* of the parent tag's character content. Returns the child tag. */
915 greg 2.1 ezxml_t ezxml_add_child(ezxml_t xml, const char *name, size_t off)
916     {
917     ezxml_t child;
918    
919     if (! xml) return NULL;
920     child = (ezxml_t)memset(malloc(sizeof(struct ezxml)), '\0',
921     sizeof(struct ezxml));
922     child->name = (char *)name;
923     child->attr = EZXML_NIL;
924     child->txt = "";
925    
926     return ezxml_insert(child, xml, off);
927     }
928    
929 greg 2.2 /* sets the character content for the given tag and returns the tag */
930 greg 2.1 ezxml_t ezxml_set_txt(ezxml_t xml, const char *txt)
931     {
932     if (! xml) return NULL;
933 greg 2.7 if (txt == xml->txt) return xml;
934 greg 2.2 if (xml->flags & EZXML_TXTM) free(xml->txt); /* existing txt was malloced */
935 greg 2.1 xml->flags &= ~EZXML_TXTM;
936     xml->txt = (char *)txt;
937     return xml;
938     }
939    
940 greg 2.7 /* add text to the current character content, allocating memory as needed (GW) */
941     ezxml_t ezxml_add_txt(ezxml_t xml, const char *txt)
942     {
943     int len;
944     if (! xml) return NULL;
945     if (!*txt) return xml;
946     len = strlen(xml->txt) + strlen(txt) + 1;
947     if (xml->flags & EZXML_TXTM) {
948     xml->txt = (char *)realloc(xml->txt, len);
949     } else {
950     xml->txt = strcpy((char *)malloc(len), xml->txt);
951     xml->flags |= EZXML_TXTM;
952     }
953     strcat(xml->txt, txt);
954     return xml;
955     }
956    
957 greg 2.2 /* Sets the given tag attribute or adds a new attribute if not found. A value */
958     /* of NULL will remove the specified attribute. Returns the tag given. */
959 greg 2.1 ezxml_t ezxml_set_attr(ezxml_t xml, const char *name, const char *value)
960     {
961     int l = 0, c;
962    
963     if (! xml) return NULL;
964     while (xml->attr[l] && strcmp(xml->attr[l], name)) l += 2;
965 greg 2.2 if (! xml->attr[l]) { /* not found, add as new attribute */
966     if (! value) return xml; /* nothing to do */
967     if (xml->attr == EZXML_NIL) { /* first attribute */
968 greg 2.1 xml->attr = malloc(4 * sizeof(char *));
969 greg 2.2 xml->attr[1] = strdup(""); /* empty list of malloced names/vals */
970 greg 2.1 }
971     else xml->attr = realloc(xml->attr, (l + 4) * sizeof(char *));
972    
973 greg 2.2 xml->attr[l] = (char *)name; /* set attribute name */
974     xml->attr[l + 2] = NULL; /* null terminate attribute list */
975 greg 2.1 xml->attr[l + 3] = realloc(xml->attr[l + 1],
976     (c = strlen(xml->attr[l + 1])) + 2);
977 greg 2.2 strcpy(xml->attr[l + 3] + c, " "); /* set name/value as not malloced */
978 greg 2.1 if (xml->flags & EZXML_DUP) xml->attr[l + 3][c] = EZXML_NAMEM;
979     }
980 greg 2.2 else if (xml->flags & EZXML_DUP) free((char *)name); /* name was strduped */
981 greg 2.1
982 greg 2.2 for (c = l; xml->attr[c]; c += 2); /* find end of attribute list */
983     if (xml->attr[c + 1][l / 2] & EZXML_TXTM) free(xml->attr[l + 1]); /*old val */
984 greg 2.1 if (xml->flags & EZXML_DUP) xml->attr[c + 1][l / 2] |= EZXML_TXTM;
985     else xml->attr[c + 1][l / 2] &= ~EZXML_TXTM;
986    
987 greg 2.2 if (value) xml->attr[l + 1] = (char *)value; /* set attribute value */
988     else { /* remove attribute */
989 greg 2.1 if (xml->attr[c + 1][l / 2] & EZXML_NAMEM) free(xml->attr[l]);
990     memmove(xml->attr + l, xml->attr + l + 2, (c - l + 2) * sizeof(char*));
991     xml->attr = realloc(xml->attr, (c + 2) * sizeof(char *));
992     memmove(xml->attr[c + 1] + (l / 2), xml->attr[c + 1] + (l / 2) + 1,
993 greg 2.2 (c / 2) - (l / 2)); /* fix list of which name/vals are malloced */
994 greg 2.1 }
995 greg 2.2 xml->flags &= ~EZXML_DUP; /* clear strdup() flag */
996 greg 2.1 return xml;
997     }
998    
999 greg 2.2 /* sets a flag for the given tag and returns the tag */
1000 greg 2.1 ezxml_t ezxml_set_flag(ezxml_t xml, short flag)
1001     {
1002     if (xml) xml->flags |= flag;
1003     return xml;
1004     }
1005    
1006 greg 2.2 /* removes a tag along with its subtags without freeing its memory */
1007 greg 2.1 ezxml_t ezxml_cut(ezxml_t xml)
1008     {
1009     ezxml_t cur;
1010    
1011 greg 2.2 if (! xml) return NULL; /* nothing to do */
1012     if (xml->next) xml->next->sibling = xml->sibling; /* patch sibling list */
1013 greg 2.1
1014 greg 2.2 if (xml->parent) { /* not root tag */
1015     cur = xml->parent->child; /* find head of subtag list */
1016     if (cur == xml) xml->parent->child = xml->ordered; /* first subtag */
1017     else { /* not first subtag */
1018 greg 2.1 while (cur->ordered != xml) cur = cur->ordered;
1019 greg 2.2 cur->ordered = cur->ordered->ordered; /* patch ordered list */
1020 greg 2.1
1021 greg 2.2 cur = xml->parent->child; /* go back to head of subtag list */
1022     if (strcmp(cur->name, xml->name)) { /* not in first sibling list */
1023 greg 2.1 while (strcmp(cur->sibling->name, xml->name))
1024     cur = cur->sibling;
1025 greg 2.2 if (cur->sibling == xml) { /* first of a sibling list */
1026 greg 2.1 cur->sibling = (xml->next) ? xml->next
1027     : cur->sibling->sibling;
1028     }
1029 greg 2.2 else cur = cur->sibling; /* not first of a sibling list */
1030 greg 2.1 }
1031    
1032     while (cur->next && cur->next != xml) cur = cur->next;
1033 greg 2.2 if (cur->next) cur->next = cur->next->next; /* patch next list */
1034 greg 2.1 }
1035     }
1036     xml->ordered = xml->sibling = xml->next = NULL;
1037     return xml;
1038     }
1039    
1040 greg 2.2 #ifdef EZXML_TEST /* test harness */
1041 greg 2.1 int main(int argc, char **argv)
1042     {
1043     ezxml_t xml;
1044     char *s;
1045     int i;
1046    
1047     if (argc != 2) return fprintf(stderr, "usage: %s xmlfile\n", argv[0]);
1048    
1049     xml = ezxml_parse_file(argv[1]);
1050     printf("%s\n", (s = ezxml_toxml(xml)));
1051     free(s);
1052     i = fprintf(stderr, "%s", ezxml_error(xml));
1053     ezxml_free(xml);
1054     return (i) ? 1 : 0;
1055     }
1056 greg 2.2 #endif /* EZXML_TEST */