streaming redux

Michel Fortin michel.fortin at michelf.com
Tue Dec 28 15:31:48 PST 2010


On 2010-12-28 17:19:01 -0500, Sean Kelly <sean at invisibleduck.org> said:

> Michel Fortin Wrote:
> 
>> On 2010-12-28 13:07:56 -0500, Sean Kelly <sean at invisibleduck.org> said:
>> 
>>> Michel Fortin Wrote:
>>>> 
>>>> So because of all this virtual dispatch and all this rigidity, I think
>>>> Formatter needs to be rethought a little. My preference obviously goes
>>>> to satically-typed formatters. But what I'd like to see is something
>>>> like this:
>>>> 
>>>> 	interface Serializable(F) {
>>>> 		void writeTo(F formatter);
>>>> 	}
>> 
>> The 'F' formatter can be anything, it can be a class, a delegate, a
>> struct (although for a struct you might want to pass it as 'ref')... so
>> it *can* hold a state. Or am I missing something?
> 
> And I guess writeTo could just call formatter.write(MyClass c).  You're 
> right, that works.

Well, not exactly. I'd expect formatter.write(Object) do be the one 
calling writeTo. Here's what a similar function in my own code does 
(with a few things renamed to match this discussion):

	void write(T)(in T value) if (is(T == class)) {
		write('O'); // identifying an object type
		writeMappedString(value.classinfo.name); // class name
		
		// cast to interface and call writeTo
		auto s = cast(Serializable!Formatter)value;
		assert(s);
		s.writeTo(this);
		
		write('Z'); // end of object
	}

A typical writeTo might look like this:

	void writeTo(Formatter formatter) {
		formatter.write(member1);
		formatter.write(member2);
	}

or like this:

	void writeTo(Formatter formatter) {
		formatter.writeKeyValue("member1", member1);
		formatter.writeKeyValue("member2", member2);
	}

or anything else that fits how a specific formatter type wants to 
receive its data. This writeTo function could be generated with a mixin 
that'd introspect the type. The only thing is that you need to define 
writeTo (or use the mixin) with any class and subclass you want to 
serialize.


-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/



More information about the Digitalmars-d mailing list