Monday, May 25, 2009

Serialization for D part 3 of N: with Code!

I have published reasonably working version posted here. It's very much alpha and I haven't documented it much at all.

What works is user defined types (structs and classes) where every member is to be serialized. The one fun case that works is driveled classes (that wasn't as hard as I though it would be) as long as the base class is also serializable.

A quick tutorial



First, invocation:

void main()
{
// something to work with
SS ss = SS(42, 2.717, new DS(1));

// A data sink
Si c = new Si();

//------- Run the serializer
marshal(c,ss);

// show the data
writef("%s\n", c.get));

// make a Source from that data
So s = new So(c.get)

//------- deserialize stuff.
SS sd = SS.DemarshalMe();

// show the results
writef("%s\n"%s\n", sd);
}


To serialize something, you need a data sink to dump it into and to deserialize something you need a source to pull from. In this example, I use an basic sink that just stores into a buffer and a source that pulls from one.

Next, The data types.

/// A struct to serialize
struct SS
{
mixin Serializable!();

int foo;
float bar;
CS cs;

char[] toString() { return format("<%s,%s,%s>", this.tupleof); }
}

/// a base class to serialize
class CS
{
mixin Serializable!();

int i = 5; float j = 3.1415926;

this(){}
this(int) { i++; j++; }

char[] toString() { return format("<%s,%s>", this.tupleof); }
}

/// a derived class to serialize
class DS : CS
{
mixin Serializable!();

real f = 2.717;

this(){}
this(int) { f++; super(0); }

char[] toString()
{ return format("<%s,%s>", super.toString()[1..$-1], this.tupleof); }
}

No comments:

Post a Comment