Serializer.hx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. /*
  2. * Copyright (C)2005-2018 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 #end
  141. #end
  142. buf.add("y");
  143. s = StringTools.urlEncode(s);
  144. buf.add(s.length);
  145. buf.add(":");
  146. buf.add(s);
  147. }
  148. function serializeRef(v:Dynamic) {
  149. #if js
  150. var vt = js.Syntax.typeof(v);
  151. #end
  152. for( i in 0...cache.length ) {
  153. #if js
  154. var ci = cache[i];
  155. if( js.Syntax.typeof(ci) == vt && ci == v ) {
  156. #else
  157. if( cache[i] == v ) {
  158. #end
  159. buf.add("r");
  160. buf.add(i);
  161. return true;
  162. }
  163. }
  164. cache.push(v);
  165. return false;
  166. }
  167. #if flash
  168. // only the instance variables
  169. function serializeClassFields(v:Dynamic, c:Dynamic) {
  170. var xml : flash.xml.XML = untyped __global__["flash.utils.describeType"](c);
  171. var vars = xml.factory[0].child("variable");
  172. for( i in 0...vars.length() ) {
  173. var f = vars[i].attribute("name").toString();
  174. if( !v.hasOwnProperty(f) )
  175. continue;
  176. serializeString(f);
  177. serialize(Reflect.field(v,f));
  178. }
  179. buf.add("g");
  180. }
  181. #end
  182. function serializeFields(v:{}) {
  183. for( f in Reflect.fields(v) ) {
  184. serializeString(f);
  185. serialize(Reflect.field(v,f));
  186. }
  187. buf.add("g");
  188. }
  189. /**
  190. Serializes `v`.
  191. All haxe-defined values and objects with the exception of functions can
  192. be serialized. Serialization of external/native objects is not
  193. guaranteed to work.
  194. The values of `this.useCache` and `this.useEnumIndex` may affect
  195. serialization output.
  196. **/
  197. public function serialize( v : Dynamic ) {
  198. switch( Type.typeof(v) ) {
  199. case TNull:
  200. buf.add("n");
  201. case TInt:
  202. var v : Int = v;
  203. if( v == 0 ) {
  204. buf.add("z");
  205. return;
  206. }
  207. buf.add("i");
  208. buf.add(v);
  209. case TFloat:
  210. var v : Float = v;
  211. if( Math.isNaN(v) )
  212. buf.add("k");
  213. else if( !Math.isFinite(v) )
  214. buf.add(if( v < 0 ) "m" else "p");
  215. else {
  216. buf.add("d");
  217. buf.add(v);
  218. }
  219. case TBool:
  220. buf.add(if( v ) "t" else "f");
  221. case TClass(c):
  222. if( #if neko untyped c.__is_String #else c == String #end ) {
  223. serializeString(v);
  224. return;
  225. }
  226. if( useCache && serializeRef(v) )
  227. return;
  228. switch( #if (neko || cs || python) Type.getClassName(c) #else c #end ) {
  229. case #if (neko || cs || python) "Array" #else cast Array #end:
  230. var ucount = 0;
  231. buf.add("a");
  232. #if (flash || python || hl)
  233. var v : Array<Dynamic> = v;
  234. #end
  235. var l = #if (neko || flash || php || cs || java || python || hl || lua || eval) v.length #elseif cpp v.__length() #else __getField(v, "length") #end;
  236. for( i in 0...l ) {
  237. if( v[i] == null )
  238. ucount++;
  239. else {
  240. if( ucount > 0 ) {
  241. if( ucount == 1 )
  242. buf.add("n");
  243. else {
  244. buf.add("u");
  245. buf.add(ucount);
  246. }
  247. ucount = 0;
  248. }
  249. serialize(v[i]);
  250. }
  251. }
  252. if( ucount > 0 ) {
  253. if( ucount == 1 )
  254. buf.add("n");
  255. else {
  256. buf.add("u");
  257. buf.add(ucount);
  258. }
  259. }
  260. buf.add("h");
  261. case #if (neko || cs || python) "haxe.ds.List" #else cast List #end:
  262. buf.add("l");
  263. var v : List<Dynamic> = v;
  264. for( i in v )
  265. serialize(i);
  266. buf.add("h");
  267. case #if (neko || cs || python) "Date" #else cast Date #end:
  268. var d : Date = v;
  269. buf.add("v");
  270. buf.add(d.getTime());
  271. case #if (neko || cs || python) "haxe.ds.StringMap" #else cast haxe.ds.StringMap #end:
  272. buf.add("b");
  273. var v : haxe.ds.StringMap<Dynamic> = v;
  274. for( k in v.keys() ) {
  275. serializeString(k);
  276. serialize(v.get(k));
  277. }
  278. buf.add("h");
  279. case #if (neko || cs || python) "haxe.ds.IntMap" #else cast haxe.ds.IntMap #end:
  280. buf.add("q");
  281. var v : haxe.ds.IntMap<Dynamic> = v;
  282. for( k in v.keys() ) {
  283. buf.add(":");
  284. buf.add(k);
  285. serialize(v.get(k));
  286. }
  287. buf.add("h");
  288. case #if (neko || cs || python) "haxe.ds.ObjectMap" #else cast haxe.ds.ObjectMap #end:
  289. buf.add("M");
  290. var v : haxe.ds.ObjectMap<Dynamic,Dynamic> = v;
  291. for ( k in v.keys() ) {
  292. #if (js || neko)
  293. var id = Reflect.field(k, "__id__");
  294. Reflect.deleteField(k, "__id__");
  295. serialize(k);
  296. Reflect.setField(k, "__id__", id);
  297. #else
  298. serialize(k);
  299. #end
  300. serialize(v.get(k));
  301. }
  302. buf.add("h");
  303. case #if (neko || cs || python) "haxe.io.Bytes" #else cast haxe.io.Bytes #end:
  304. var v : haxe.io.Bytes = v;
  305. #if neko
  306. var chars = new String(base_encode(v.getData(),untyped BASE64.__s));
  307. buf.add("s");
  308. buf.add(chars.length);
  309. buf.add(":");
  310. buf.add(chars);
  311. #else
  312. buf.add("s");
  313. buf.add(Math.ceil((v.length * 8) / 6));
  314. buf.add(":");
  315. var i = 0;
  316. var max = v.length - 2;
  317. var b64 = BASE64_CODES;
  318. if( b64 == null ) {
  319. b64 = new haxe.ds.Vector(BASE64.length);
  320. for( i in 0...BASE64.length )
  321. b64[i] = BASE64.charCodeAt(i);
  322. BASE64_CODES = b64;
  323. }
  324. while( i < max ) {
  325. var b1 = v.get(i++);
  326. var b2 = v.get(i++);
  327. var b3 = v.get(i++);
  328. buf.addChar(b64[b1 >> 2]);
  329. buf.addChar(b64[((b1 << 4) | (b2 >> 4)) & 63]);
  330. buf.addChar(b64[((b2 << 2) | (b3 >> 6)) & 63]);
  331. buf.addChar(b64[b3 & 63]);
  332. }
  333. if( i == max ) {
  334. var b1 = v.get(i++);
  335. var b2 = v.get(i++);
  336. buf.addChar(b64[b1 >> 2]);
  337. buf.addChar(b64[((b1 << 4) | (b2 >> 4)) & 63]);
  338. buf.addChar(b64[(b2 << 2) & 63]);
  339. } else if( i == max + 1 ) {
  340. var b1 = v.get(i++);
  341. buf.addChar(b64[b1 >> 2]);
  342. buf.addChar(b64[(b1 << 4) & 63]);
  343. }
  344. #end
  345. default:
  346. if( useCache ) cache.pop();
  347. if( #if flash try v.hxSerialize != null catch( e : Dynamic ) false #elseif (cs || java || python) Reflect.hasField(v, "hxSerialize") #elseif php php.Global.method_exists(v, 'hxSerialize') #else v.hxSerialize != null #end ) {
  348. buf.add("C");
  349. serializeString(Type.getClassName(c));
  350. if( useCache ) cache.push(v);
  351. v.hxSerialize(this);
  352. buf.add("g");
  353. } else {
  354. buf.add("c");
  355. serializeString(Type.getClassName(c));
  356. if( useCache ) cache.push(v);
  357. #if flash
  358. serializeClassFields(v,c);
  359. #else
  360. serializeFields(v);
  361. #end
  362. }
  363. }
  364. case TObject:
  365. if (Std.is(v,Class)) {
  366. var className = Type.getClassName(v);
  367. #if (flash || cpp)
  368. // Currently, Enum and Class are the same for flash and cpp.
  369. // use resolveEnum to test if it is actually an enum
  370. if (Type.resolveEnum(className)!=null) buf.add("B") else
  371. #end
  372. buf.add("A");
  373. serializeString(className);
  374. } else if (Std.is(v,Enum)) {
  375. buf.add("B");
  376. serializeString(Type.getEnumName(v));
  377. } else {
  378. if( useCache && serializeRef(v) )
  379. return;
  380. buf.add("o");
  381. serializeFields(v);
  382. }
  383. case TEnum(e):
  384. if( useCache ) {
  385. if( serializeRef(v) )
  386. return;
  387. cache.pop();
  388. }
  389. buf.add(useEnumIndex?"j":"w");
  390. serializeString(Type.getEnumName(e));
  391. #if neko
  392. if( useEnumIndex ) {
  393. buf.add(":");
  394. buf.add(v.index);
  395. } else
  396. serializeString(new String(v.tag));
  397. buf.add(":");
  398. if( v.args == null )
  399. buf.add(0);
  400. else {
  401. var l : Int = untyped __dollar__asize(v.args);
  402. buf.add(l);
  403. for( i in 0...l )
  404. serialize(v.args[i]);
  405. }
  406. #elseif flash
  407. if( useEnumIndex ) {
  408. buf.add(":");
  409. var i : Int = v.index;
  410. buf.add(i);
  411. } else
  412. serializeString(v.tag);
  413. buf.add(":");
  414. var pl : Array<Dynamic> = v.params;
  415. if( pl == null )
  416. buf.add(0);
  417. else {
  418. buf.add(pl.length);
  419. for( p in pl )
  420. serialize(p);
  421. }
  422. #elseif cpp
  423. var enumBase:cpp.EnumBase = v;
  424. if( useEnumIndex ) {
  425. buf.add(":");
  426. buf.add(enumBase.getIndex());
  427. } else
  428. serializeString(enumBase.getTag());
  429. buf.add(":");
  430. var len = enumBase.getParamCount();
  431. buf.add(len);
  432. for( p in 0...len )
  433. serialize( enumBase.getParamI(p));
  434. #elseif php
  435. if( useEnumIndex ) {
  436. buf.add(":");
  437. buf.add(v.index);
  438. } else
  439. serializeString(v.tag);
  440. buf.add(":");
  441. var l : Int = php.Syntax.code("count({0})", v.params);
  442. if( l == 0 || v.params == null)
  443. buf.add(0);
  444. else {
  445. buf.add(l);
  446. for( i in 0...l ) {
  447. #if php
  448. serialize(v.params[i]);
  449. #end
  450. }
  451. }
  452. #elseif (java || cs || python || hl || eval)
  453. if( useEnumIndex ) {
  454. buf.add(":");
  455. buf.add(Type.enumIndex(v));
  456. } else
  457. serializeString(Type.enumConstructor(v));
  458. buf.add(":");
  459. var arr:Array<Dynamic> = Type.enumParameters(v);
  460. if (arr != null)
  461. {
  462. buf.add(arr.length);
  463. for (v in arr)
  464. serialize(v);
  465. } else {
  466. buf.add("0");
  467. }
  468. #elseif js_enums_as_objects
  469. if( useEnumIndex ) {
  470. buf.add(":");
  471. buf.add(v._hx_index);
  472. } else
  473. serializeString(Type.enumConstructor(v));
  474. buf.add(":");
  475. var params = Type.enumParameters(v);
  476. buf.add(params.length);
  477. for(p in params) serialize(p);
  478. #else
  479. if( useEnumIndex ) {
  480. buf.add(":");
  481. buf.add(v[1]);
  482. } else
  483. serializeString(v[0]);
  484. buf.add(":");
  485. var l = __getField(v, "length");
  486. buf.add(l - 2);
  487. for( i in 2...l )
  488. serialize(v[i]);
  489. #end
  490. if( useCache ) cache.push(v);
  491. case TFunction:
  492. throw "Cannot serialize function";
  493. default:
  494. #if neko
  495. if( untyped (__i32__kind != null && __dollar__iskind(v,__i32__kind)) ) {
  496. buf.add("i");
  497. buf.add(v);
  498. return;
  499. }
  500. #end
  501. throw "Cannot serialize "+Std.string(v);
  502. }
  503. }
  504. @:extern inline function __getField(o:Dynamic, f:String):Dynamic return o[cast f];
  505. public function serializeException( e : Dynamic ) {
  506. buf.add("x");
  507. #if flash
  508. if( untyped __is__(e,__global__["Error"]) ) {
  509. var e : flash.errors.Error = e;
  510. var s = e.getStackTrace();
  511. if( s == null )
  512. serialize(e.message);
  513. else
  514. serialize(s);
  515. return;
  516. }
  517. #end
  518. serialize(e);
  519. }
  520. /**
  521. Serializes `v` and returns the String representation.
  522. This is a convenience function for creating a new instance of
  523. Serializer, serialize `v` into it and obtain the result through a call
  524. to toString().
  525. **/
  526. public static function run( v : Dynamic ) {
  527. var s = new Serializer();
  528. s.serialize(v);
  529. return s.toString();
  530. }
  531. #if neko
  532. static var base_encode = neko.Lib.load("std","base_encode",2);
  533. #end
  534. }