json.vala 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. /*
  2. * Copyright (c) 2012-2024 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: GPL-3.0-or-later
  4. */
  5. /*
  6. * Original C# code:
  7. * Public Domain Niklas Frykholm
  8. */
  9. namespace Crown
  10. {
  11. /// <summary>
  12. /// Provides functions for encoding and decoding files in the JSON format.
  13. /// </summary>
  14. [Compact]
  15. public class JSON
  16. {
  17. /// <summary>
  18. /// Encodes the hashtable t in the JSON format. The hash table can
  19. /// contain, numbers, bools, strings, ArrayLists and Hashtables.
  20. /// </summary>
  21. public static string encode(Value? t)
  22. {
  23. StringBuilder sb = new StringBuilder();
  24. write(t, sb, 0);
  25. sb.append_c('\n');
  26. return sb.str;
  27. }
  28. /// <summary>
  29. /// Decodes a JSON bytestream into a hash table with numbers, bools, strings,
  30. /// ArrayLists and Hashtables.
  31. /// </summary>
  32. public static Value? decode(uint8[] sjson)
  33. {
  34. int index = 0;
  35. return parse(sjson, ref index);
  36. }
  37. /// <summary>
  38. /// Convenience function for loading a file.
  39. /// </summary>
  40. public static Hashtable load(string path)
  41. {
  42. FileStream fs = FileStream.open(path, "rb");
  43. if (fs == null)
  44. return new Hashtable();
  45. // Get file size
  46. fs.seek(0, FileSeek.END);
  47. size_t size = fs.tell();
  48. fs.rewind();
  49. if (size == 0)
  50. return new Hashtable();
  51. // Read whole file
  52. uint8[] bytes = new uint8[size];
  53. size_t bytes_read = fs.read(bytes);
  54. if (bytes_read != size)
  55. return new Hashtable();
  56. return decode(bytes) as Hashtable;
  57. }
  58. /// <summary>
  59. /// Convenience function for saving a file.
  60. /// </summary>
  61. public static void save(Hashtable h, string path)
  62. {
  63. FileStream fs = FileStream.open(path, "wb");
  64. if (fs == null)
  65. return;
  66. fs.write(encode(h).data);
  67. }
  68. static void write_new_line(StringBuilder builder, int indentation)
  69. {
  70. if (builder.len > 0)
  71. builder.append_c('\n');
  72. for (int i = 0; i < indentation; ++i)
  73. builder.append_c('\t');
  74. }
  75. static void write(Value? o, StringBuilder builder, int indentation)
  76. {
  77. if (o == null)
  78. builder.append("null");
  79. else if (o.holds(typeof(bool)) && (bool)o == false)
  80. builder.append("false");
  81. else if (o.holds(typeof(bool)))
  82. builder.append("true");
  83. else if (o.holds(typeof(int)))
  84. builder.append_printf("%d", (int)o);
  85. else if (o.holds(typeof(float)))
  86. builder.append_printf("%.9g", (float)o);
  87. else if (o.holds(typeof(double)))
  88. builder.append_printf("%.17g", (double)o);
  89. else if (o.holds(typeof(string)))
  90. write_string((string)o, builder);
  91. else if (o.holds(typeof(Gee.ArrayList)))
  92. write_array((Gee.ArrayList)o, builder, indentation);
  93. else if (o.holds(typeof(Hashtable)))
  94. write_object((Hashtable)o, builder, indentation);
  95. else
  96. assert(false);
  97. }
  98. static void write_string(string s, StringBuilder builder)
  99. {
  100. builder.append_c('"');
  101. for (int i = 0; i < s.length; ++i) {
  102. uint8 c = s[i];
  103. if (c == '"' || c == '\\') {
  104. builder.append_c('\\');
  105. builder.append_c((char)c);
  106. } else if (c == '\n') {
  107. builder.append_c('\\');
  108. builder.append_c('n');
  109. } else {
  110. builder.append_c((char)c);
  111. }
  112. }
  113. builder.append_c('"');
  114. }
  115. static void write_array(Gee.ArrayList<Value?> a, StringBuilder builder, int indentation)
  116. {
  117. bool write_comma = false;
  118. builder.append("[ ");
  119. foreach (Value? item in a) {
  120. if (write_comma)
  121. builder.append(", ");
  122. write(item, builder, indentation + 1);
  123. write_comma = true;
  124. }
  125. builder.append("]");
  126. }
  127. static void write_object(Hashtable t, StringBuilder builder, int indentation)
  128. {
  129. builder.append_c('{');
  130. bool write_comma = false;
  131. foreach (var de in t.entries) {
  132. if (write_comma)
  133. builder.append(", ");
  134. write_new_line(builder, indentation);
  135. write(de.key, builder, indentation);
  136. builder.append(" : ");
  137. write(de.value, builder, indentation);
  138. write_comma = true;
  139. }
  140. write_new_line(builder, indentation);
  141. builder.append_c('}');
  142. }
  143. static void skip_whitespace(uint8[] json, ref int index)
  144. {
  145. while (index < json.length) {
  146. uint8 c = json[index];
  147. if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',')
  148. ++index;
  149. else
  150. break;
  151. }
  152. }
  153. static void consume(uint8[] json, ref int index, string consume)
  154. {
  155. skip_whitespace(json, ref index);
  156. for (int i = 0; i < consume.length; ++i) {
  157. if (json[index] != consume[i])
  158. assert(false);
  159. ++index;
  160. }
  161. }
  162. static Value? parse(uint8[] json, ref int index)
  163. {
  164. uint8 c = next(json, ref index);
  165. if (c == '{') {
  166. return parse_object(json, ref index);
  167. } else if (c == '[') {
  168. return parse_array(json, ref index);
  169. } else if (c == '"') {
  170. return parse_string(json, ref index);
  171. } else if (c == '-' || c >= '0' && c <= '9') {
  172. return parse_number(json, ref index);
  173. } else if (c == 't') {
  174. consume(json, ref index, "true");
  175. return true;
  176. } else if (c == 'f') {
  177. consume(json, ref index, "false");
  178. return false;
  179. } else if (c == 'n') {
  180. consume(json, ref index, "null");
  181. return null;
  182. } else {
  183. assert(false);
  184. return null;
  185. }
  186. }
  187. static uint8 next(uint8[] json, ref int index)
  188. {
  189. skip_whitespace(json, ref index);
  190. return json[index];
  191. }
  192. static Hashtable parse_object(uint8[] json, ref int index)
  193. {
  194. Hashtable ht = new Hashtable();
  195. consume(json, ref index, "{");
  196. skip_whitespace(json, ref index);
  197. while (next(json, ref index) != '}') {
  198. string key = parse_string(json, ref index);
  199. consume(json, ref index, ":");
  200. if (key.has_suffix("_binary"))
  201. ht[key] = (Value?)parse_binary(json, ref index);
  202. else
  203. ht[key] = parse(json, ref index);
  204. }
  205. consume(json, ref index, "}");
  206. return ht;
  207. }
  208. static Gee.ArrayList<Value?> parse_array(uint8[] json, ref int index)
  209. {
  210. Gee.ArrayList<Value?> a = new Gee.ArrayList<Value?>();
  211. consume(json, ref index, "[");
  212. while (next(json, ref index) != ']') {
  213. Value? value = parse(json, ref index);
  214. a.add(value);
  215. }
  216. consume(json, ref index, "]");
  217. return a;
  218. }
  219. static uint8[] parse_binary(uint8[] json, ref int index)
  220. {
  221. Gee.ArrayList<uint8> s = new Gee.ArrayList<uint8>();
  222. consume(json, ref index, "\"");
  223. while (true) {
  224. uint8 c = json[index];
  225. ++index;
  226. if (c == '"') {
  227. break;
  228. } else if (c != '\\') {
  229. s.add(c);
  230. } else {
  231. uint8 q = json[index];
  232. ++index;
  233. if (q == '"' || q == '\\' || q == '/')
  234. s.add(q);
  235. else if (q == 'b')
  236. s.add('\b');
  237. else if (q == 'f')
  238. s.add('\f');
  239. else if (q == 'n')
  240. s.add('\n');
  241. else if (q == 'r')
  242. s.add('\r');
  243. else if (q == 't')
  244. s.add('\t');
  245. else if (q == 'u')
  246. assert(false);
  247. else
  248. assert(false);
  249. }
  250. }
  251. s.add('\0');
  252. return s.to_array();
  253. }
  254. static string parse_string(uint8[] json, ref int index)
  255. {
  256. return (string)parse_binary(json, ref index);
  257. }
  258. static double parse_number(uint8[] json, ref int index)
  259. {
  260. int end = index;
  261. while ("0123456789+-.eE".index_of_char((char)json[end]) != -1)
  262. ++end;
  263. uint8[] num = json[index : end];
  264. num += '\0';
  265. index = end;
  266. return double.parse((string)num);
  267. }
  268. }
  269. } /* namespace Crown */