Serializer.hx 14 KB

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