aboutsummaryrefslogtreecommitdiff
path: root/sanitize.c
blob: 50aee3beca3615ff0590f0a674d1c8a70dd593ea (plain) (blame)
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
#define _POSIX_C_SOURCE 200809L

#include "utils.h"
#include <dynstr.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>

char *sanitize(const char *s)
{
    struct dynstr d;

    dynstr_init(&d);

    while (*s)
    {
        char ss[sizeof "\"\""] = {0};

        switch (*s)
        {
            case '\'':
                strcpy(ss, "\'\'");
                break;

            case '\"':
                strcpy(ss, "\"\"");
                break;

            default:
                *ss = *s;
                break;
        }

        if (dynstr_append(&d, "%s", ss))
        {
            fprintf(stderr, "%s: dynstr_append failed\n", __func__);
            goto failure;
        }

        s++;
    }

    if (!d.str && dynstr_append(&d, "%c", '\0'))
    {
        fprintf(stderr, "%s: dynstr_append failed\n", __func__);
        goto failure;
    }

    return d.str;

failure:
    dynstr_free(&d);
    return NULL;
}