rejectedsoftware/vibe.d — pull request #937 by lultimouomo (2014-12-20 15:11:56+00:00)
Title: Allow policy-based serialization

An explicit Policy parameter allows to customize serialization of types
without having to modify them, which is useful if the types are supplied
by a library or if different serializations are needed.

The PR is not ready yet, needing documentation and tests, but it's working, so I would like some feedback.

An usage example (that pushed me to write the code) is serializing objects synthesized by [dproto](https://github.com/msoucy/dproto), which can be done with such a policy:

```
template BufferPolicy(Buf) if (__traits(compiles, Buf.init == Buf.init.opGet))
{
auto toRepresentation(Buf b) {
return b.opGet;
}
Buf fromRepresentation(typeof(Buf.init.opGet) v){
Buf b;
b = v;
return b;
}
}
```
which transforms the serialized form from:
```
{"fieldname":{"opGet":"fieldvalue"}}
```
to
```
{"fieldname": "fieldvalue"}
```
(Actually, serializing dproto objects without a custom policy fails, due to https://issues.dlang.org/show_bug.cgi?id=12363 ; but it would look like the former if it worked)

I also would have liked to add a template parameter (defaulted to DefaultPolicy) to ```serialize``` and ```deserialize```, but I don't think it can be done without breaking some existing code.

It should be possible to compose policies with something like
```
template CompositePolicy(T)
{
static if (isPolicySerializable!(FirstPolicy, T))
{
alias toRepresentation = FirstPolicy!T.toRepresentation;
alias fromRepresentation = FirstPolicy!T.fromRepresentation;
} else {
alias toRepresentation = FallbackPolicy!T.toRepresentation;
alias fromRepresentation = FallbackPolicy!T.fromRepresentation;
}
}
```
but I still have to work on it, and I wonder if it would be possible to create a general policy composer.