json.vala 7.1 KB

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