Created
May 3, 2020 07:12
-
-
Save back2dos/ba0dd0ee9a3bb986f746465e304645c6 to your computer and use it in GitHub Desktop.
Caching circular references in tink_json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// haxe -lib tink_json --run Main | |
package; | |
class Main { | |
static function main() { | |
var foo = new Circular('foo'); | |
var a = { c1: foo, c2: foo }; | |
var json = tink.Json.stringify(a); | |
trace(json); | |
a = tink.Json.parse(json); | |
trace(a.c1 == a.c2); | |
} | |
} | |
class CircularWriter { | |
final cache = new Map(); | |
var counter = 0; | |
public function new(writer:tink.json.Writer.BasicWriter) { | |
} | |
public function prepare(c:Circular) | |
return switch cache[c] { | |
case null: | |
cache[c] = counter++; | |
Payload({ value: c.value }); | |
case v: | |
Cached(v); | |
} | |
} | |
class CircularReader { | |
final cache = new Map(); | |
var counter = 0; | |
public function new(parser:tink.json.Parser.BasicParser) { | |
} | |
public function parse(c:Ref<{ value: String }>) | |
return switch c { | |
case Payload(v): | |
cache[counter++] = new Circular(v.value); | |
case Cached(id): | |
cache[id]; | |
} | |
} | |
@:jsonStringify(Main.CircularWriter) | |
@:jsonParse(Main.CircularReader) | |
class Circular { | |
public final self:Circular; | |
public final value:String; | |
public function new(value) { | |
this.self = this; | |
this.value = value; | |
} | |
} | |
enum Ref<T> { | |
Payload(payload:T); | |
Cached(id:Int); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment