2
0

Serializer.hx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. /*
  2. * Copyright (C)2005-2019 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package haxe;
  23. import haxe.ds.List;
  24. /**
  25. The Serializer class can be used to encode values and objects into a `String`,
  26. from which the `Unserializer` class can recreate the original representation.
  27. This class can be used in two ways:
  28. - create a `new Serializer()` instance, call its `serialize()` method with
  29. any argument and finally retrieve the String representation from
  30. `toString()`
  31. - call `Serializer.run()` to obtain the serialized representation of a
  32. single argument
  33. Serialization is guaranteed to work for all haxe-defined classes, but may
  34. or may not work for instances of external/native classes.
  35. The specification of the serialization format can be found here:
  36. <https://haxe.org/manual/std-serialization-format.html>
  37. **/
  38. class Serializer {
  39. /**
  40. If the values you are serializing can contain circular references or
  41. objects repetitions, you should set `USE_CACHE` to true to prevent
  42. infinite loops.
  43. This may also reduce the size of serialization Strings at the expense of
  44. performance.
  45. This value can be changed for individual instances of `Serializer` by
  46. setting their `useCache` field.
  47. **/
  48. public static var USE_CACHE = false;
  49. /**
  50. Use constructor indexes for enums instead of names.
  51. This may reduce the size of serialization Strings, but makes them less
  52. suited for long-term storage: If constructors are removed or added from
  53. the enum, the indices may no longer match.
  54. This value can be changed for individual instances of `Serializer` by
  55. setting their `useEnumIndex` field.
  56. **/
  57. public static var USE_ENUM_INDEX = false;
  58. static var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%:";
  59. static var BASE64_CODES = null;
  60. var buf:StringBuf;
  61. var cache:Array<Dynamic>;
  62. var shash:haxe.ds.StringMap<Int>;
  63. var scount:Int;
  64. /**
  65. The individual cache setting for `this` Serializer instance.
  66. See `USE_CACHE` for a complete description.
  67. **/
  68. public var useCache:Bool;
  69. /**
  70. The individual enum index setting for `this` Serializer instance.
  71. See `USE_ENUM_INDEX` for a complete description.
  72. **/
  73. public var useEnumIndex:Bool;
  74. /**
  75. Creates a new Serializer instance.
  76. Subsequent calls to `this.serialize` will append values to the
  77. internal buffer of this String. Once complete, the contents can be
  78. retrieved through a call to `this.toString`.
  79. Each `Serializer` instance maintains its own cache if `this.useCache` is
  80. `true`.
  81. **/
  82. public function new() {
  83. buf = new StringBuf();
  84. cache = new Array();
  85. useCache = USE_CACHE;
  86. useEnumIndex = USE_ENUM_INDEX;
  87. shash = new haxe.ds.StringMap();
  88. scount = 0;
  89. }
  90. /**
  91. Return the String representation of `this` Serializer.
  92. The exact format specification can be found here:
  93. https://haxe.org/manual/serialization/format
  94. **/
  95. public function toString() {
  96. return buf.toString();
  97. }
  98. /* prefixes :
  99. a : array
  100. b : hash
  101. c : class
  102. d : Float
  103. e : reserved (float exp)
  104. f : false
  105. g : object end
  106. h : array/list/hash end
  107. i : Int
  108. j : enum (by index)
  109. k : NaN
  110. l : list
  111. m : -Inf
  112. n : null
  113. o : object
  114. p : +Inf
  115. q : haxe.ds.IntMap
  116. r : reference
  117. s : bytes (base64)
  118. t : true
  119. u : array nulls
  120. v : date
  121. w : enum
  122. x : exception
  123. y : urlencoded string
  124. z : zero
  125. A : Class<Dynamic>
  126. B : Enum<Dynamic>
  127. M : haxe.ds.ObjectMap
  128. C : custom
  129. */
  130. function serializeString(s:String) {
  131. var x = shash.get(s);
  132. if (x != null) {
  133. buf.add("R");
  134. buf.add(x);
  135. return;
  136. }
  137. shash.set(s, scount++);
  138. #if old_serialize
  139. // no more support for -D old_serialize due to 'j' reuse
  140. #if error
  141. #end
  142. #end
  143. buf.add("y");
  144. s = StringTools.urlEncode(s);
  145. buf.add(s.length);
  146. buf.add(":");
  147. buf.add(s);
  148. }
  149. function serializeRef(v:Dynamic) {
  150. #if js
  151. var vt = js.Syntax.typeof(v);
  152. #end
  153. for (i in 0...cache.length) {
  154. #if js
  155. var ci = cache[i];
  156. if (js.Syntax.typeof(ci) == vt && ci == v) {
  157. #else
  158. if (cache[i] == v) {
  159. #end
  160. buf.add("r");
  161. buf.add(i);
  162. return true;
  163. }
  164. }
  165. cache.push(v);
  166. return false;
  167. }
  168. #if flash
  169. // only the instance variables
  170. function serializeClassFields(v:Dynamic, c:Dynamic) {
  171. var xml:flash.xml.XML = untyped __global__["flash.utils.describeType"](c);
  172. var vars = xml.factory[0].child("variable");
  173. for (i in 0...vars.length()) {
  174. var f = vars[i].attribute("name").toString();
  175. if (!v.hasOwnProperty(f))
  176. continue;
  177. serializeString(f);
  178. serialize(Reflect.field(v, f));
  179. }
  180. buf.add("g");
  181. }
  182. #end
  183. function serializeFields(v:{}) {
  184. for (f in Reflect.fields(v)) {
  185. serializeString(f);
  186. serialize(Reflect.field(v, f));
  187. }
  188. buf.add("g");
  189. }
  190. /**
  191. Serializes `v`.
  192. All haxe-defined values and objects with the exception of functions can
  193. be serialized. Serialization of external/native objects is not
  194. guaranteed to work.
  195. The values of `this.useCache` and `this.useEnumIndex` may affect
  196. serialization output.
  197. **/
  198. public function serialize(v:Dynamic) {
  199. switch (Type.typeof(v)) {
  200. case TNull:
  201. buf.add("n");
  202. case TInt:
  203. var v:Int = v;
  204. if (v == 0) {
  205. buf.add("z");
  206. return;
  207. }
  208. buf.add("i");
  209. buf.add(v);
  210. case TFloat:
  211. var v:Float = v;
  212. if (Math.isNaN(v))
  213. buf.add("k");
  214. else if (!Math.isFinite(v))
  215. buf.add(if (v < 0) "m" else "p");
  216. else {
  217. buf.add("d");
  218. buf.add(v);
  219. }
  220. case TBool:
  221. buf.add(if (v) "t" else "f");
  222. case TClass(c):
  223. if (#if neko untyped c.__is_String #else c == String #end) {
  224. serializeString(v);
  225. return;
  226. }
  227. if (useCache && serializeRef(v))
  228. return;
  229. switch (#if (neko || cs || python) Type.getClassName(c) #else c #end) {
  230. case #if (neko || cs || python) "Array" #else cast Array #end:
  231. var ucount = 0;
  232. buf.add("a");
  233. #if (flash || python || hl)
  234. var v:Array<Dynamic> = v;
  235. #end
  236. var l = #if (neko || flash || php || cs || java || python || hl || lua || eval) v.length #elseif cpp v.__length() #else __getField(v,
  237. "length") #end;
  238. for (i in 0...l) {
  239. if (v[i] == null)
  240. ucount++;
  241. else {
  242. if (ucount > 0) {
  243. if (ucount == 1)
  244. buf.add("n");
  245. else {
  246. buf.add("u");
  247. buf.add(ucount);
  248. }
  249. ucount = 0;
  250. }
  251. serialize(v[i]);
  252. }
  253. }
  254. if (ucount > 0) {
  255. if (ucount == 1)
  256. buf.add("n");
  257. else {
  258. buf.add("u");
  259. buf.add(ucount);
  260. }
  261. }
  262. buf.add("h");
  263. case #if (neko || cs || python) "haxe.ds.List" #else cast List #end:
  264. buf.add("l");
  265. var v:List<Dynamic> = v;
  266. for (i in v)
  267. serialize(i);
  268. buf.add("h");
  269. case #if (neko || cs || python) "Date" #else cast Date #end:
  270. var d:Date = v;
  271. buf.add("v");
  272. buf.add(d.getTime());
  273. case #if (neko || cs || python) "haxe.ds.StringMap" #else cast haxe.ds.StringMap #end:
  274. buf.add("b");
  275. var v:haxe.ds.StringMap<Dynamic> = v;
  276. for (k in v.keys()) {
  277. serializeString(k);
  278. serialize(v.get(k));
  279. }
  280. buf.add("h");
  281. case #if (neko || cs || python) "haxe.ds.IntMap" #else cast haxe.ds.IntMap #end:
  282. buf.add("q");
  283. var v:haxe.ds.IntMap<Dynamic> = v;
  284. for (k in v.keys()) {
  285. buf.add(":");
  286. buf.add(k);
  287. serialize(v.get(k));
  288. }
  289. buf.add("h");
  290. case #if (neko || cs || python) "haxe.ds.ObjectMap" #else cast haxe.ds.ObjectMap #end:
  291. buf.add("M");
  292. var v:haxe.ds.ObjectMap<Dynamic, Dynamic> = v;
  293. for (k in v.keys()) {
  294. #if (js || neko)
  295. var id = Reflect.field(k, "__id__");
  296. Reflect.deleteField(k, "__id__");
  297. serialize(k);
  298. Reflect.setField(k, "__id__", id);
  299. #else
  300. serialize(k);
  301. #end
  302. serialize(v.get(k));
  303. }
  304. buf.add("h");
  305. case #if (neko || cs || python) "haxe.io.Bytes" #else cast haxe.io.Bytes #end:
  306. var v:haxe.io.Bytes = v;
  307. #if neko
  308. var chars = new String(base_encode(v.getData(), untyped BASE64.__s));
  309. buf.add("s");
  310. buf.add(chars.length);
  311. buf.add(":");
  312. buf.add(chars);
  313. #elseif php
  314. var chars = new String(php.Global.base64_encode(v.getData()));
  315. chars = php.Global.strtr(chars, '+/', '%:');
  316. buf.add("s");
  317. buf.add(chars.length);
  318. buf.add(":");
  319. buf.add(chars);
  320. #else
  321. buf.add("s");
  322. buf.add(Math.ceil((v.length * 8) / 6));
  323. buf.add(":");
  324. var i = 0;
  325. var max = v.length - 2;
  326. var b64 = BASE64_CODES;
  327. if (b64 == null) {
  328. b64 = new haxe.ds.Vector(BASE64.length);
  329. for (i in 0...BASE64.length)
  330. b64[i] = BASE64.charCodeAt(i);
  331. BASE64_CODES = b64;
  332. }
  333. while (i < max) {
  334. var b1 = v.get(i++);
  335. var b2 = v.get(i++);
  336. var b3 = v.get(i++);
  337. buf.addChar(b64[b1 >> 2]);
  338. buf.addChar(b64[((b1 << 4) | (b2 >> 4)) & 63]);
  339. buf.addChar(b64[((b2 << 2) | (b3 >> 6)) & 63]);
  340. buf.addChar(b64[b3 & 63]);
  341. }
  342. if (i == max) {
  343. var b1 = v.get(i++);
  344. var b2 = v.get(i++);
  345. buf.addChar(b64[b1 >> 2]);
  346. buf.addChar(b64[((b1 << 4) | (b2 >> 4)) & 63]);
  347. buf.addChar(b64[(b2 << 2) & 63]);
  348. } else if (i == max + 1) {
  349. var b1 = v.get(i++);
  350. buf.addChar(b64[b1 >> 2]);
  351. buf.addChar(b64[(b1 << 4) & 63]);
  352. }
  353. #end
  354. default:
  355. if (useCache) cache.pop();
  356. if (#if flash try
  357. v.hxSerialize != null
  358. catch (e:Dynamic)
  359. false #elseif (cs || java || python) Reflect.hasField(v,
  360. "hxSerialize") #elseif php php.Global.method_exists(v, 'hxSerialize') #else v.hxSerialize != null #end) {
  361. buf.add("C");
  362. serializeString(Type.getClassName(c));
  363. if (useCache)
  364. cache.push(v);
  365. v.hxSerialize(this);
  366. buf.add("g");
  367. } else {
  368. buf.add("c");
  369. serializeString(Type.getClassName(c));
  370. if (useCache)
  371. cache.push(v);
  372. #if flash
  373. serializeClassFields(v, c);
  374. #else
  375. serializeFields(v);
  376. #end
  377. }
  378. }
  379. case TObject:
  380. if (Std.isOfType(v, Class)) {
  381. var className = Type.getClassName(v);
  382. #if (flash || cpp)
  383. // Currently, Enum and Class are the same for flash and cpp.
  384. // use resolveEnum to test if it is actually an enum
  385. if (Type.resolveEnum(className) != null)
  386. buf.add("B")
  387. else
  388. #end
  389. buf.add("A");
  390. serializeString(className);
  391. } else if (Std.isOfType(v, Enum)) {
  392. buf.add("B");
  393. serializeString(Type.getEnumName(v));
  394. } else {
  395. if (useCache && serializeRef(v))
  396. return;
  397. buf.add("o");
  398. serializeFields(v);
  399. }
  400. case TEnum(e):
  401. if (useCache) {
  402. if (serializeRef(v))
  403. return;
  404. cache.pop();
  405. }
  406. buf.add(useEnumIndex ? "j" : "w");
  407. serializeString(Type.getEnumName(e));
  408. #if neko
  409. if (useEnumIndex) {
  410. buf.add(":");
  411. buf.add(v.index);
  412. } else
  413. serializeString(new String(v.tag));
  414. buf.add(":");
  415. if (v.args == null)
  416. buf.add(0);
  417. else {
  418. var l:Int = untyped __dollar__asize(v.args);
  419. buf.add(l);
  420. for (i in 0...l)
  421. serialize(v.args[i]);
  422. }
  423. #elseif flash
  424. if (useEnumIndex) {
  425. buf.add(":");
  426. var i:Int = v.index;
  427. buf.add(i);
  428. } else
  429. serializeString(v.tag);
  430. buf.add(":");
  431. var pl:Array<Dynamic> = v.params;
  432. if (pl == null)
  433. buf.add(0);
  434. else {
  435. buf.add(pl.length);
  436. for (p in pl)
  437. serialize(p);
  438. }
  439. #elseif cpp
  440. var enumBase:cpp.EnumBase = v;
  441. if (useEnumIndex) {
  442. buf.add(":");
  443. buf.add(enumBase.getIndex());
  444. } else
  445. serializeString(enumBase.getTag());
  446. buf.add(":");
  447. var len = enumBase.getParamCount();
  448. buf.add(len);
  449. for (p in 0...len)
  450. serialize(enumBase.getParamI(p));
  451. #elseif php
  452. if (useEnumIndex) {
  453. buf.add(":");
  454. buf.add(v.index);
  455. } else
  456. serializeString(v.tag);
  457. buf.add(":");
  458. var l:Int = php.Syntax.code("count({0})", v.params);
  459. if (l == 0 || v.params == null)
  460. buf.add(0);
  461. else {
  462. buf.add(l);
  463. for (i in 0...l) {
  464. #if php
  465. serialize(v.params[i]);
  466. #end
  467. }
  468. }
  469. #elseif (java || cs || python || hl || eval)
  470. if (useEnumIndex) {
  471. buf.add(":");
  472. buf.add(Type.enumIndex(v));
  473. } else
  474. serializeString(Type.enumConstructor(v));
  475. buf.add(":");
  476. var arr:Array<Dynamic> = Type.enumParameters(v);
  477. if (arr != null) {
  478. buf.add(arr.length);
  479. for (v in arr)
  480. serialize(v);
  481. } else {
  482. buf.add("0");
  483. }
  484. #elseif (js && !js_enums_as_arrays)
  485. if (useEnumIndex) {
  486. buf.add(":");
  487. buf.add(v._hx_index);
  488. } else
  489. serializeString(Type.enumConstructor(v));
  490. buf.add(":");
  491. var params = Type.enumParameters(v);
  492. buf.add(params.length);
  493. for (p in params)
  494. serialize(p);
  495. #else
  496. if (useEnumIndex) {
  497. buf.add(":");
  498. buf.add(v[1]);
  499. } else
  500. serializeString(v[0]);
  501. buf.add(":");
  502. var l = __getField(v, "length");
  503. buf.add(l - 2);
  504. for (i in 2...l)
  505. serialize(v[i]);
  506. #end
  507. if (useCache)
  508. cache.push(v);
  509. case TFunction:
  510. throw "Cannot serialize function";
  511. default:
  512. #if neko
  513. if (untyped (__i32__kind != null && __dollar__iskind(v, __i32__kind))) {
  514. buf.add("i");
  515. buf.add(v);
  516. return;
  517. }
  518. #end
  519. throw "Cannot serialize " + Std.string(v);
  520. }
  521. }
  522. extern inline function __getField(o:Dynamic, f:String):Dynamic
  523. return o[cast f];
  524. public function serializeException(e:Dynamic) {
  525. buf.add("x");
  526. #if flash
  527. if (untyped __is__(e, __global__["Error"])) {
  528. var e:flash.errors.Error = e;
  529. var s = e.getStackTrace();
  530. if (s == null)
  531. serialize(e.message);
  532. else
  533. serialize(s);
  534. return;
  535. }
  536. #end
  537. serialize(e);
  538. }
  539. /**
  540. Serializes `v` and returns the String representation.
  541. This is a convenience function for creating a new instance of
  542. Serializer, serialize `v` into it and obtain the result through a call
  543. to `toString()`.
  544. **/
  545. public static function run(v:Dynamic) {
  546. var s = new Serializer();
  547. s.serialize(v);
  548. return s.toString();
  549. }
  550. #if neko
  551. static var base_encode = neko.Lib.load("std", "base_encode", 2);
  552. #end
  553. }