json.vala 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. /*
  2. * Copyright (c) 2012-2017 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. using GLib;
  11. namespace Crown
  12. {
  13. public class Hashtable : HashMap<string, Value?> { }
  14. /// <summary>
  15. /// Provides functions for encoding and decoding files in the JSON format.
  16. /// </summary>
  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, "r");
  45. if (fs == null)
  46. return new Hashtable();
  47. // Get file size
  48. fs.seek(0, FileSeek.END);
  49. long size = fs.tell();
  50. fs.rewind();
  51. uint8[] bytes = new uint8[size];
  52. fs.read(bytes);
  53. return decode(bytes) as Hashtable;
  54. }
  55. /// <summary>
  56. /// Convenience function for saving a file.
  57. /// </summary>
  58. public static void save(Hashtable h, string path)
  59. {
  60. string s = encode(h);
  61. FileStream fs = FileStream.open(path, "w");
  62. assert(fs != null);
  63. uint8[] bytes = s.data;
  64. fs.write(bytes);
  65. }
  66. static void write_new_line(StringBuilder builder, int indentation)
  67. {
  68. builder.append_c('\n');
  69. for (int i = 0; i < indentation; ++i)
  70. builder.append_c('\t');
  71. }
  72. static void write(Value? o, StringBuilder builder, int indentation)
  73. {
  74. if (o == null)
  75. builder.append("null");
  76. else if (o.holds(typeof(bool)) && (bool)o == false)
  77. builder.append("false");
  78. else if (o.holds(typeof(bool)))
  79. builder.append("true");
  80. else if (o.holds(typeof(int)))
  81. builder.append(((int)o).to_string());
  82. else if (o.holds(typeof(float)))
  83. builder.append(((float)o).to_string());
  84. else if (o.holds(typeof(double)))
  85. builder.append(((double)o).to_string());
  86. else if (o.holds(typeof(string)))
  87. write_string((string)o, builder);
  88. else if (o.holds(typeof(ArrayList)))
  89. write_array((ArrayList)o, builder, indentation);
  90. else if (o.holds(typeof(Hashtable)))
  91. write_object((Hashtable)o, builder, indentation);
  92. else
  93. assert(false);
  94. }
  95. static void write_string(string s, StringBuilder builder)
  96. {
  97. builder.append_c('"');
  98. for (int i = 0; i < s.length; ++i)
  99. {
  100. uint8 c = s[i];
  101. if (c == '"' || c == '\\')
  102. {
  103. builder.append_c('\\');
  104. builder.append_c((char)c);
  105. }
  106. else if (c == '\n')
  107. {
  108. builder.append_c('\\');
  109. builder.append_c('n');
  110. }
  111. else
  112. builder.append_c((char)c);
  113. }
  114. builder.append_c('"');
  115. }
  116. static void write_array(ArrayList<Value?> a, StringBuilder builder, int indentation)
  117. {
  118. bool write_comma = false;
  119. builder.append("[ ");
  120. foreach (Value? item in a)
  121. {
  122. if (write_comma)
  123. builder.append(", ");
  124. write(item, builder, indentation + 1);
  125. write_comma = true;
  126. }
  127. builder.append("]");
  128. }
  129. static void write_object(Hashtable t, StringBuilder builder, int indentation)
  130. {
  131. builder.append_c('{');
  132. bool write_comma = false;
  133. foreach (var de in t.entries)
  134. {
  135. if (write_comma)
  136. builder.append(", ");
  137. write_new_line(builder, indentation);
  138. write(de.key, builder, indentation);
  139. builder.append(" : ");
  140. write(de.value, builder, indentation);
  141. write_comma = true;
  142. }
  143. write_new_line(builder, indentation);
  144. builder.append_c('}');
  145. }
  146. static void skip_whitespace(uint8[] json, ref int index)
  147. {
  148. while (index < json.length)
  149. {
  150. uint8 c = json[index];
  151. if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',')
  152. ++index;
  153. else
  154. break;
  155. }
  156. }
  157. static void consume(uint8[] json, ref int index, string consume)
  158. {
  159. skip_whitespace(json, ref index);
  160. for (int i = 0; i < consume.length; ++i)
  161. {
  162. if (json[index] != consume[i])
  163. assert(false);
  164. ++index;
  165. }
  166. }
  167. static Value? parse(uint8[] json, ref int index)
  168. {
  169. uint8 c = next(json, ref index);
  170. if (c == '{')
  171. return parse_object(json, ref index);
  172. else if (c == '[')
  173. return parse_array(json, ref index);
  174. else if (c == '"')
  175. return parse_string(json, ref index);
  176. else if (c == '-' || c >= '0' && c <= '9')
  177. return parse_number(json, ref index);
  178. else if (c == 't')
  179. {
  180. consume(json, ref index, "true");
  181. return true;
  182. }
  183. else if (c == 'f')
  184. {
  185. consume(json, ref index, "false");
  186. return false;
  187. }
  188. else if (c == 'n')
  189. {
  190. consume(json, ref index, "null");
  191. return null;
  192. }
  193. else
  194. {
  195. assert(false);
  196. return null;
  197. }
  198. }
  199. static uint8 next(uint8[] json, ref int index)
  200. {
  201. skip_whitespace(json, ref index);
  202. return json[index];
  203. }
  204. static Hashtable parse_object(uint8[] json, ref int index)
  205. {
  206. Hashtable ht = new Hashtable();
  207. consume(json, ref index, "{");
  208. skip_whitespace(json, ref index);
  209. while (next(json, ref index) != '}')
  210. {
  211. string key = parse_string(json, ref index);
  212. consume(json, ref index, ":");
  213. if (key.has_suffix("_binary"))
  214. ht[key] = (Value?)parse_binary(json, ref index);
  215. else
  216. ht[key] = parse(json, ref index);
  217. }
  218. consume(json, ref index, "}");
  219. return ht;
  220. }
  221. static ArrayList<Value?> parse_array(uint8[] json, ref int index)
  222. {
  223. ArrayList<Value?> a = new ArrayList<Value?>();
  224. consume(json, ref index, "[");
  225. while (next(json, ref index) != ']')
  226. {
  227. Value? value = parse(json, ref index);
  228. a.add(value);
  229. }
  230. consume(json, ref index, "]");
  231. return a;
  232. }
  233. static uint8[] parse_binary(uint8[] json, ref int index)
  234. {
  235. ArrayList<uint8> s = new ArrayList<uint8>();
  236. consume(json, ref index, "\"");
  237. while (true)
  238. {
  239. uint8 c = json[index];
  240. ++index;
  241. if (c == '"')
  242. break;
  243. else if (c != '\\')
  244. s.add(c);
  245. else
  246. {
  247. uint8 q = json[index];
  248. ++index;
  249. if (q == '"' || q == '\\' || q == '/')
  250. s.add(q);
  251. else if (q == 'b') s.add('\b');
  252. else if (q == 'f') s.add('\f');
  253. else if (q == 'n') s.add('\n');
  254. else if (q == 'r') s.add('\r');
  255. else if (q == 't') s.add('\t');
  256. else if (q == 'u')
  257. {
  258. assert(false);
  259. }
  260. else
  261. {
  262. assert(false);
  263. }
  264. }
  265. }
  266. s.add('\0');
  267. return s.to_array();
  268. }
  269. static string parse_string(uint8[] json, ref int index)
  270. {
  271. return (string)parse_binary(json, ref index);
  272. }
  273. static double parse_number(uint8[] json, ref int index)
  274. {
  275. int end = index;
  276. while ("0123456789+-.eE".index_of_char((char)json[end]) != -1)
  277. ++end;
  278. uint8[] num = json[index:end];
  279. num += '\0';
  280. index = end;
  281. return double.parse((string)num);
  282. }
  283. }
  284. }