From: Holger Schemel Date: Mon, 21 Jun 2021 13:57:36 +0000 (+0200) Subject: added functions for JSON handling X-Git-Tag: 4.3.0.0~127 X-Git-Url: https://git.artsoft.org/?a=commitdiff_plain;h=c75628b175a7eedae537ff482cc2dd932e250178;p=rocksndiamonds.git added functions for JSON handling --- diff --git a/src/libgame/misc.c b/src/libgame/misc.c index 36e576bc..5f9c009a 100644 --- a/src/libgame/misc.c +++ b/src/libgame/misc.c @@ -1840,6 +1840,49 @@ char *getLatin1FromUTF8(char *utf8) } +// ---------------------------------------------------------------------------- +// functions for JSON handling +// ---------------------------------------------------------------------------- + +char *getEscapedJSON(char *s) +{ + int max_json_size = 2 * strlen(s) + 1; + char *json = checked_calloc(max_json_size); + unsigned char *src = (unsigned char *)s; + unsigned char *dst = (unsigned char *)json; + char *escaped[256] = + { + ['\b'] = "\\b", + ['\f'] = "\\f", + ['\n'] = "\\n", + ['\r'] = "\\r", + ['\t'] = "\\t", + ['\"'] = "\\\"", + ['\\'] = "\\\\", + }; + + while (*src) + { + if (escaped[*src] != NULL) + { + char *esc = escaped[*src++]; + + while (*esc) + *dst++ = *esc++; + } + else + { + *dst++ = *src++; + } + } + + // only use the smallest possible string buffer size + json = checked_realloc(json, strlen(json) + 1); + + return json; +} + + // ---------------------------------------------------------------------------- // functions to translate key identifiers between different format // ---------------------------------------------------------------------------- diff --git a/src/libgame/misc.h b/src/libgame/misc.h index a8eaa335..cb27fa4e 100644 --- a/src/libgame/misc.h +++ b/src/libgame/misc.h @@ -227,6 +227,7 @@ void WriteUnusedBytesToFile(FILE *, unsigned int); char *getUTF8FromLatin1(char *); char *getLatin1FromUTF8(char *); +char *getEscapedJSON(char *); char *getKeyNameFromKey(Key); char *getX11KeyNameFromKey(Key);