added functions for JSON handling
authorHolger Schemel <info@artsoft.org>
Mon, 21 Jun 2021 13:57:36 +0000 (15:57 +0200)
committerHolger Schemel <info@artsoft.org>
Mon, 21 Jun 2021 13:57:36 +0000 (15:57 +0200)
src/libgame/misc.c
src/libgame/misc.h

index 36e576bc59c15a8e2945cb7e24f199f6de372026..5f9c009afd39875560ed9b9f6ee846ceb0fabdd8 100644 (file)
@@ -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
 // ----------------------------------------------------------------------------
index a8eaa335972b2655f27408333b232c6cf79bd316..cb27fa4e9aadd78bbffd09421e34e04fd849ceb4 100644 (file)
@@ -227,6 +227,7 @@ void WriteUnusedBytesToFile(FILE *, unsigned int);
 
 char *getUTF8FromLatin1(char *);
 char *getLatin1FromUTF8(char *);
+char *getEscapedJSON(char *);
 
 char *getKeyNameFromKey(Key);
 char *getX11KeyNameFromKey(Key);