json.vala 6.9 KB

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