1#include <base/system.h>
2
3#include <engine/shared/json.h>
4
5const struct _json_value *json_object_get(const json_value *pObject, const char *pIndex)
6{
7 unsigned int i;
8
9 if(pObject->type != json_object)
10 return &json_value_none;
11
12 for(i = 0; i < pObject->u.object.length; ++i)
13 if(!str_comp(a: pObject->u.object.values[i].name, b: pIndex))
14 return pObject->u.object.values[i].value;
15
16 return &json_value_none;
17}
18
19const struct _json_value *json_array_get(const json_value *pArray, int Index)
20{
21 if(pArray->type != json_array || Index >= (int)pArray->u.array.length)
22 return &json_value_none;
23
24 return pArray->u.array.values[Index];
25}
26
27int json_array_length(const json_value *pArray)
28{
29 return pArray->u.array.length;
30}
31
32const char *json_string_get(const json_value *pString)
33{
34 return pString->u.string.ptr;
35}
36
37int json_int_get(const json_value *pInteger)
38{
39 return pInteger->u.integer;
40}
41
42int json_boolean_get(const json_value *pBoolean)
43{
44 return pBoolean->u.boolean != 0;
45}
46
47static char EscapeJsonChar(char c)
48{
49 switch(c)
50 {
51 case '\"': return '\"';
52 case '\\': return '\\';
53 case '\b': return 'b';
54 case '\n': return 'n';
55 case '\r': return 'r';
56 case '\t': return 't';
57 // Don't escape '\f', who uses that. :)
58 default: return 0;
59 }
60}
61
62char *EscapeJson(char *pBuffer, int BufferSize, const char *pString)
63{
64 dbg_assert(BufferSize > 0, "can't null-terminate the string");
65 // Subtract the space for null termination early.
66 BufferSize--;
67
68 char *pResult = pBuffer;
69 while(BufferSize && *pString)
70 {
71 char c = *pString;
72 pString++;
73 char Escaped = EscapeJsonChar(c);
74 if(Escaped)
75 {
76 if(BufferSize < 2)
77 {
78 break;
79 }
80 *pBuffer++ = '\\';
81 *pBuffer++ = Escaped;
82 BufferSize -= 2;
83 }
84 // Assuming ASCII/UTF-8, "if control character".
85 else if((unsigned char)c < 0x20)
86 {
87 // \uXXXX
88 if(BufferSize < 6)
89 {
90 break;
91 }
92 str_format(buffer: pBuffer, buffer_size: BufferSize, format: "\\u%04x", c);
93 pBuffer += 6;
94 BufferSize -= 6;
95 }
96 else
97 {
98 *pBuffer++ = c;
99 BufferSize--;
100 }
101 }
102 *pBuffer = 0;
103 return pResult;
104}
105
106const char *JsonBool(bool Bool)
107{
108 if(Bool)
109 {
110 return "true";
111 }
112 else
113 {
114 return "false";
115 }
116}
117