1/*
2 * Copyright 2017, Data61
3 * Commonwealth Scientific and Industrial Research Organisation (CSIRO)
4 * ABN 41 687 119 230.
5 *
6 * This software may be distributed and modified according to the terms of
7 * the BSD 2-Clause license. Note that NO WARRANTY is provided.
8 * See "LICENSE_BSD2.txt" for details.
9 *
10 * @TAG(DATA61_BSD)
11 */
12
13#include <stddef.h>
14#include <stdio.h>
15#include <utils/attribute.h>
16#include <utils/xml.h>
17
18#define PRINT(s) (print == NULL ? printf("%s", (s)) : print(arg, "%s", (s)))
19
20int
21utils_put_xml_escape(const char *string,
22                     int (*print)(void *arg, const char *format, ...) FORMAT(printf, 2, 3),
23                     void *arg)
24{
25
26    int ret = 0;
27
28    while (*string != '\0') {
29
30        switch (*string) {
31
32            case '"':
33                ret += PRINT("&quot;");
34                break;
35
36            case '\'':
37                ret += PRINT("&apos;");
38                break;
39
40            case '<':
41                ret += PRINT("&lt;");
42                break;
43
44            case '>':
45                ret += PRINT("&gt;");
46                break;
47
48            case '&':
49                ret += PRINT("&amp;");
50                break;
51
52            default:
53                if (print == NULL) {
54                    putchar(*string);
55                    ret++;
56                } else {
57                    ret += print(arg, "%c", *string);
58                }
59        }
60
61        string++;
62    }
63
64    return ret;
65}
66