Serialization + semantics of toString

aarti_pl aarti at interia.pl
Thu Nov 12 15:13:39 PST 2009


Andrei Alexandrescu pisze:
 > But that being said, I'd so much want to start thinking of an actual
 > text serialization infrastructure. Why develop one later with the
 > mention "well use that stuff for debugging only, this is the real stuff."
 >
 > Andrei

You might want to see my serialization library for D.

I think that it is worth noting as it manages to achieve the goal:
same data - completely different output. Because this output might be 
defined by user in the way she wants, it seems that this can work 
exactly the way toString should work.

It is achieved by using Archive classes which makes proper formatting, 
and which are completely independent from data being printed. Initial 
design is based on C++ Boost. I just extended concept a bit and adopted 
it to D.

Basic interface for serialization is like this:

auto serializer = Serializer!(TextArchive);
//It might be also e.g.:
//auto serializer = Serializer!(JsonArchive);
auto input = new TransparentClass(-21, 2.11, "text1", 128, -127);
auto output = serializer.dump(input);
assert(serializer.load!(TransparentClass)(output) == input);

In case of transparent classes (every field is public) you don't need 
any method inside of serialized class/struct.

In case of opaque classes there is enough to:
1. add mixin inside:
mixin Serializable;
or
2. add template method:
void describeUdt(T)(T arch) {
     arch.describeStaticArray(array, array.stringof);
}

This is all what is necessary to print every possible class/struct in 
whatever format you want.

Because of limitations of D I couldn't achieve serialization of classes 
from base pointer. It was because of fact that template methods are not 
virtual.

Recently I didn't have time to work on it, but if you think it's worthy 
and eventually might be included in Phobos, I would be interested to 
work on it further. But I would definitely need some code/concepts review.

Unfortunately there is rather poor documentation. But you can find a lot 
of unit tests in examples directory.

It's Boost licensed so no worries :-)

BR
Marcin Kuszczak
(aarti_pl)



More information about the Digitalmars-d mailing list