Only one function may be specified for one data type. Default data types already have representer functions unless disabled in the Representer constructor.
Structs and classes must implement the opCmp() operator for D:YAML support. The signature of the operator that must be implemented is const int opCmp(ref const MyStruct s) for structs where MyStruct is the struct type, and int opCmp(Object o) for classes. Note that the class opCmp() should not alter the compared values - it is not const for compatibility reasons.
Representing a simple struct:
import std.string; import dyaml.all; struct MyStruct { int x, y, z; //Any D:YAML type must have a custom opCmp operator. //This is used for ordering in mappings. const int opCmp(ref const MyStruct s) { if(x != s.x){return x - s.x;} if(y != s.y){return y - s.y;} if(z != s.z){return z - s.z;} return 0; } } Node representMyStruct(ref Node node, Representer representer) { //The node is guaranteed to be MyStruct as we add representer for MyStruct. auto value = node.as!MyStruct; //Using custom scalar format, x:y:z. auto scalar = format("%s:%s:%s", value.x, value.y, value.z); //Representing as a scalar, with custom tag to specify this data type. return representer.representScalar("!mystruct.tag", scalar); } void main() { auto dumper = Dumper("file.yaml"); auto representer = new Representer; representer.addRepresenter!MyStruct(&representMyStruct); dumper.representer = representer; dumper.dump(Node(MyStruct(1,2,3))); }
Representing a class:
import std.string; import dyaml.all; class MyClass { int x, y, z; this(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } //Any D:YAML type must have a custom opCmp operator. //This is used for ordering in mappings. override int opCmp(Object o) { MyClass s = cast(MyClass)o; if(s is null){return -1;} if(x != s.x){return x - s.x;} if(y != s.y){return y - s.y;} if(z != s.z){return z - s.z;} return 0; } ///Useful for Node.as!string . override string toString() { return format("MyClass(%s, %s, %s)", x, y, z); } } //Same as representMyStruct. Node representMyClass(ref Node node, Representer representer) { //The node is guaranteed to be MyClass as we add representer for MyClass. auto value = node.as!MyClass; //Using custom scalar format, x:y:z. auto scalar = format("%s:%s:%s", value.x, value.y, value.z); //Representing as a scalar, with custom tag to specify this data type. return representer.representScalar("!myclass.tag", scalar); } void main() { auto dumper = Dumper("file.yaml"); auto representer = new Representer; representer.addRepresenter!MyClass(&representMyClass); dumper.representer = representer; dumper.dump(Node(new MyClass(1,2,3))); }
Add a function to represent nodes with a specific data type.
The representer function takes references to a Node storing the data type and to the Representer. It returns the represented node and may throw a RepresenterException. See the example for more information.