]> git.notmuchmail.org Git - notmuch/blob - json.c
396075002db017309f8768b0a1c75e0967aaeeba
[notmuch] / json.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2009 Scott Robinson
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see http://www.gnu.org/licenses/ .
17  *
18  * Authors: Scott Robinson <scott@quadhome.com>
19  *
20  */
21
22 #include "notmuch-client.h"
23
24 /*
25  * json_quote_str derived from cJSON's print_string_ptr,
26  * Copyright (c) 2009 Dave Gamble
27  */
28
29 char *
30 json_quote_str(const void *ctx, const char *str)
31 {
32     const char *ptr;
33     char *ptr2;
34     char *out;
35     int len = 0;
36
37     if (!str)
38         return NULL;
39
40     for (ptr = str; *ptr; len++, ptr++) {
41         if (*ptr < 32 || *ptr == '\"' || *ptr == '\\')
42             len++;
43     }
44
45     out = talloc_array (ctx, char, len + 3);
46
47     ptr = str;
48     ptr2 = out;
49
50     *ptr2++ = '\"';
51     while (*ptr) {
52             if (*ptr > 31 && *ptr != '\"' && *ptr != '\\') {
53                 *ptr2++ = *ptr++;
54             } else {
55                 *ptr2++ = '\\';
56                 switch (*ptr++) {
57                     case '\"':  *ptr2++ = '\"'; break;
58                     case '\\':  *ptr2++ = '\\'; break;
59                     case '\b':  *ptr2++ = 'b';  break;
60                     case '\f':  *ptr2++ = 'f';  break;
61                     case '\n':  *ptr2++ = 'n';  break;
62                     case '\r':  *ptr2++ = 'r';  break;
63                     case '\t':  *ptr2++ = 't';  break;
64                     default:     ptr2--;        break;
65                 }
66             }
67     }
68     *ptr2++ = '\"';
69     *ptr2++ = '\0';
70
71     return out;
72 }