Advertisement
Guest User

Simple Serialize

a guest
Feb 11th, 2014
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 2.23 KB | None | 0 0
  1. import  std.stdio,
  2.         std.conv;
  3.  
  4.  
  5. enum dirn {
  6.     UP,
  7.     DOWN
  8. }
  9.        
  10. struct Type {
  11.     int     a;
  12.     bool[]  b;
  13.     dirn    dir;
  14.     string  str;
  15.     int     c;
  16.     mixin(genConstructor!(typeof(this)));
  17. }
  18.  
  19. void main(){
  20.     //writeln(genConstructor!Type);    
  21.    
  22.     auto s_fromString   = Type("Type(5, [false, true], UP, \"hello\", -45)");
  23.     auto s_fromNormal   = Type(7, [true, true, false], dirn.DOWN, "-9world", 90);
  24.     auto s_restored     = Type(s_fromNormal.to!string());
  25.    
  26.     s_fromString.writeln;
  27.     s_fromNormal.writeln;
  28.     s_restored.writeln;
  29.    
  30. }
  31.  
  32. // Does not support backslash (and therefore escape sequences) in strings
  33. //   Because struct to!string substitutes codes with escape sequences
  34. //   (Eg char [10, 13]  =>  string "\n\r", which has length 4)
  35. string genConstructor(T)(){
  36.     string c0;  // imports
  37.     string c1;  // constructor from string
  38.     string c2;  // constructor from types: parameter list
  39.     string c3;  // constructor from types: assignment
  40.  
  41.     c0 = "import std.conv:      parse;\n"
  42.          "import std.algorithm: skipOver, countUntil;\n\n";
  43.    
  44.     c1 ~=  "this(string s){\n" ~
  45.                     "    s.skipOver(\"" ~ T.stringof ~ "(\");";
  46.     c2 ~= "this(";
  47.     foreach(i, memberType; typeof(T.tupleof)){
  48.         if(memberType.stringof == "string"){
  49.             c1 ~=  "\n    s = s[1..$];\n    " ~
  50.                    T.tupleof[i].stringof ~ " = s[0..s.countUntil(\"\\\"\")];";
  51.             if(i < typeof(T.tupleof).length - 1){
  52.                 c1 ~= "   s = s[s.countUntil(\"\\\"\")+3..$];";
  53.             }
  54.         } else {
  55.             c1 ~=  "\n    " ~ T.tupleof[i].stringof ~
  56.                             " = s.parse!(" ~ memberType.stringof ~
  57.                             ");";
  58.             if(i < typeof(T.tupleof).length - 1){
  59.                 c1 ~= "   s = s[2..$];";
  60.             }
  61.         }
  62.        
  63.         c2 ~= memberType.stringof ~ " " ~ T.tupleof[i].stringof;
  64.         c3 ~= "\n    this." ~ T.tupleof[i].stringof ~ " = " ~ T.tupleof[i].stringof ~ ";";
  65.        
  66.         if(i < typeof(T.tupleof).length - 1){
  67.             c2 ~= ", ";
  68.         }
  69.     }
  70.     c1 ~= "\n}\n\n";
  71.     c2 ~= "){";
  72.     c3 ~= "\n}";
  73.    
  74.     return c0 ~ c1 ~ c2 ~ c3;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement