Skip to content

Instantly share code, notes, and snippets.

@back2dos
Created May 3, 2020 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save back2dos/ba0dd0ee9a3bb986f746465e304645c6 to your computer and use it in GitHub Desktop.
Save back2dos/ba0dd0ee9a3bb986f746465e304645c6 to your computer and use it in GitHub Desktop.
Caching circular references in tink_json
// 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