1 // Copyright (C) 2018-2019 HuntLabs. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 module hunt.gossip.Serializer; 16 17 import hunt.gossip.Buffer; 18 import std.json; 19 import hunt.logging; 20 import hunt.io.Common; 21 import hunt.gossip.JsonObject; 22 23 24 public class Serializer { 25 private static Serializer ourInstance ; 26 public static Serializer getInstance() { 27 if(ourInstance is null) 28 { 29 ourInstance = new Serializer(); 30 } 31 return ourInstance; 32 } 33 34 private this() { 35 } 36 37 public static Buffer encode(T)(Serializable obj) { 38 Buffer buffer = Buffer.buffer(); 39 try { 40 buffer.appendString(JsonObject.mapFrom(cast(T)obj).encode()); 41 } catch (Exception e) { 42 logError(e.msg); 43 } 44 return buffer; 45 } 46 47 public T decode(T)(Buffer buffer) { 48 T gdsm = null; 49 if (buffer !is null) { 50 try { 51 gdsm = buffer.toJsonObject().mapTo!(T)(); 52 } catch (Exception e) { 53 logError(e.msg); 54 } 55 } 56 return gdsm; 57 } 58 }