json.vala 7.0 KB

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