1 module libpb.serialization;
2 
3 import std.json;
4 import std.conv : to;
5 import std.traits : FieldTypeTuple, FieldNameTuple;
6 
7 public JSONValue serializeRecord(RecordType)(RecordType record)
8 {		
9 	// Final JSON to submit
10 	JSONValue builtJSON;
11 
12 	// Alias as to only expand later when used in compile-time
13 	alias structTypes = FieldTypeTuple!(RecordType);
14 	alias structNames = FieldNameTuple!(RecordType);
15 	alias structValues = record.tupleof;
16 
17 	static foreach(cnt; 0..structTypes.length)
18 	{
19 		debug(dbg)
20 		{
21 			pragma(msg, structTypes[cnt]);
22 			pragma(msg, structNames[cnt]);
23 			// pragma(msg, structValues[cnt]);
24 		}
25 
26 
27 		static if(__traits(isSame, mixin(structTypes[cnt]), int))
28 		{
29 			builtJSON[structNames[cnt]] = structValues[cnt];
30 		}
31 		else static if(__traits(isSame, mixin(structTypes[cnt]), uint))
32 		{
33 			builtJSON[structNames[cnt]] = structValues[cnt];
34 		}
35 		else static if(__traits(isSame, mixin(structTypes[cnt]), ulong))
36 		{
37 			builtJSON[structNames[cnt]] = structValues[cnt];
38 		}
39 		else static if(__traits(isSame, mixin(structTypes[cnt]), long))
40 		{
41 			builtJSON[structNames[cnt]] = structValues[cnt];
42 		}
43 		else static if(__traits(isSame, mixin(structTypes[cnt]), string))
44 		{
45 			builtJSON[structNames[cnt]] = structValues[cnt];
46 		}
47 		else static if(__traits(isSame, mixin(structTypes[cnt]), JSONValue))
48 		{
49 			builtJSON[structNames[cnt]] = structValues[cnt];
50 		}
51 		else static if(__traits(isSame, mixin(structTypes[cnt]), bool))
52 		{
53 			builtJSON[structNames[cnt]] = structValues[cnt];
54 		}
55 		else
56 		{
57 			debug(dbg)
58 			{
59 				pragma(msg, "Yaa");	
60 			}
61 			builtJSON[structNames[cnt]] = to!(string)(structValues[cnt]);
62 		}
63 	}
64 
65 
66 	return builtJSON;
67 }
68 
69 // Test serialization of a struct to JSON
70 private enum EnumType
71 {
72 	DOG,
73 	CAT
74 }
75 unittest
76 {
77 	import std.algorithm.searching : canFind;
78 	import std.string : cmp;
79 	import std.stdio : writeln;
80 	
81 	struct Person
82 	{
83 		public string firstname, lastname;
84 		public int age;
85 		public string[] list;
86 		public JSONValue extraJSON;
87 		public EnumType eType;
88 	}
89 
90 	Person p1;
91 	p1.firstname  = "Tristan";
92 	p1.lastname = "Kildaire";
93 	p1.age = 23;
94 	p1.list = ["1", "2", "3"];
95 	p1.extraJSON = parseJSON(`{"item":1, "items":[1,2,3]}`);
96 	p1.eType = EnumType.CAT;
97 
98 	JSONValue serialized = serializeRecord(p1);
99 
100 	string[] keys = serialized.object().keys();
101 	assert(canFind(keys, "firstname") && cmp(serialized["firstname"].str(), "Tristan") == 0);
102 	assert(canFind(keys, "lastname") && cmp(serialized["lastname"].str(), "Kildaire") == 0);
103 	assert(canFind(keys, "age") && serialized["age"].integer() == 23);
104 
105 	debug(dbg)
106 	{
107 		writeln(serialized.toPrettyString());
108 	}
109 }