Przeglądaj źródła

added serialization support for ObjectMap

Simon Krajewski 12 lat temu
rodzic
commit
3a8e389521
3 zmienionych plików z 53 dodań i 1 usunięć
  1. 16 0
      std/haxe/Serializer.hx
  2. 10 0
      std/haxe/Unserializer.hx
  3. 27 1
      tests/unit/TestSerialize.hx

+ 16 - 0
std/haxe/Serializer.hx

@@ -142,6 +142,7 @@ class Serializer {
 		x : exception
 		y : urlencoded string
 		z : zero
+		M : haxe.ds.ObjectMap
 		C : custom
 	*/
 
@@ -308,6 +309,21 @@ class Serializer {
 					serialize(v.get(k));
 				}
 				buf.add("h");
+			case #if (neko || cs) "haxe.ds.ObjectMap" #else cast haxe.ds.ObjectMap #end:
+				buf.add("M");
+				var v : haxe.ds.ObjectMap<Dynamic,Dynamic> = v;
+				for ( k in v.keys() ) {
+					#if (js || flash8)
+					var id = Reflect.field(k, "__id__");
+					Reflect.deleteField(k, "__id__");
+					serialize(k);
+					Reflect.setField(k, "__id__", id);
+					#else
+					serialize(k);
+					#end
+					serialize(v.get(k));
+				}
+				buf.add("h");
 			case #if (neko || cs) "haxe.io.Bytes" #else cast haxe.io.Bytes #end:
 				var v : haxe.io.Bytes = v;
 				#if neko

+ 10 - 0
std/haxe/Unserializer.hx

@@ -347,6 +347,16 @@ class Unserializer {
 			if( c != "h".code )
 				throw "Invalid IntMap format";
 			return h;
+		case "M".code:
+			var h = new haxe.ds.ObjectMap();
+			cache.push(h);
+			var buf = buf;
+			while( get(pos) != "h".code ) {
+				var s = unserialize();
+				h.set(s,unserialize());
+			}
+			pos++;
+			return h;
 		case "v".code:
 			var d = Date.fromString(buf.substr(pos,19));
 			cache.push(d);

+ 27 - 1
tests/unit/TestSerialize.hx

@@ -53,7 +53,7 @@ class TestSerialize extends Test {
 		haxe.Serializer.USE_ENUM_INDEX = true;
 		doTestEnums();
 
-		// hash
+		// StringMap
 		var h = new haxe.ds.StringMap();
 		h.set("keya",2);
 		h.set("kéyb",-465);
@@ -73,6 +73,32 @@ class TestSerialize extends Test {
 		eq( h2.get(-101), -465 );
 		eq( Lambda.count(h2), 2 );
 
+		// ObjectMap
+		var h = new haxe.ds.ObjectMap();
+		var a = new unit.MyAbstract.ClassWithoutHashCode(9);
+		var b = new unit.MyAbstract.ClassWithoutHashCode(8);
+		h.set(a, b);
+		h.set(b, a);
+		var h2 = id(h);
+		t(Std.is(h2, haxe.ds.ObjectMap));
+		// these are NOT the same objects
+		f(h2.exists(a));
+		f(h2.exists(b));
+		// all these should still work
+		t(h.exists(a));
+		t(h.exists(b));
+		eq(h.get(a), b);
+		eq(h.get(b), a);
+		var nothing = true;
+		for (k in h2.keys()) {
+			nothing = false;
+			t(k.i == 8 || k.i == 9);
+			t(h2.exists(k));
+			var v = h2.get(k);
+			t(v.i == 8 || v.i == 9);
+		}
+		f(nothing);
+		
 		// bytes
 		doTestBytes(haxe.io.Bytes.alloc(0));
 		doTestBytes(haxe.io.Bytes.ofString("A"));