1 module inochi2d.fmt.serialize; 2 import inochi2d.core; 3 import std.json; 4 public import fghj; 5 public import inochi2d.math.serialization; 6 7 import std.array : appender, Appender; 8 import std.functional : forward; 9 import std.range.primitives : put; 10 11 /** 12 Interface for classes that can be serialized to JSON with custom code 13 */ 14 interface ISerializable { 15 /** 16 Custom serializer function 17 */ 18 void serialize(S)(ref S serializer); 19 } 20 21 /** 22 Interface for classes that can be deserialized to JSON with custom code 23 */ 24 interface IDeserializable(T) { 25 26 /** 27 Custom deserializer function 28 */ 29 static T deserialize(Fghj data); 30 } 31 32 /** 33 Tells serializer to ignore 34 */ 35 alias Ignore = serdeIgnore; 36 37 /** 38 Tells serializer that a key is optional 39 */ 40 alias Optional = serdeOptional; 41 42 /** 43 Sets the name of a key. 44 45 First key is JSON key name, second is human-readable name 46 */ 47 alias Name = serdeKeys; 48 49 /** 50 Loads JSON data from memory 51 */ 52 T inLoadJsonData(T)(string file) { 53 return inLoadJsonDataFromMemory(readText(file)); 54 } 55 56 57 /** 58 Loads JSON data from memory 59 */ 60 T inLoadJsonDataFromMemory(T)(string data) { 61 return deserialize!T(parseJson(cast(string)data)); 62 } 63 64 /** 65 Serialize item with compact Inochi2D JSON serializer 66 */ 67 string inToJson(T)(T item) { 68 auto app = appender!(char[]); 69 auto serializer = inCreateSerializer(app); 70 serializer.serializeValue(item); 71 serializer.flush(); 72 return cast(string)app.data; 73 } 74 75 /** 76 Serialize item with pretty Inochi2D JSON serializer 77 */ 78 string inToJsonPretty(T)(T item) { 79 auto app = appender!(char[]); 80 auto serializer = inCreatePrettySerializer(app); 81 serializer.serializeValue(item); 82 serializer.flush(); 83 return cast(string)app.data; 84 } 85 86 alias InochiSerializer = JsonSerializer!("", void delegate(const(char)[]) pure nothrow @safe); 87 88 /** 89 Creates a pretty-serializer 90 */ 91 InochiSerializer inCreateSerializer(Appender!(char[]) app) { 92 return InochiSerializer((const(char)[] chars) => put(app, chars)); 93 } 94 95 96 string getString(Fghj data) { 97 auto app = appender!(char[]); 98 data.toString((const(char)[] chars) => put(app, chars)); 99 return cast(string)app.data; 100 }