Class GenericWriter
[DatumWriter] for GenericDatum objects.
Constructors
Name | Description |
this
(schema, encoder)
|
Constructs a writer for a given schema using the given encoder.
|
Methods
Name | Description |
write
(datum, e)
|
Uses a given encoder to convert a [GenericDatum] into its serialized format.
|
write
(datum)
|
Writes a value into the encoder.
|
Example
import std.format;
import std.algorithm;
import std.array : appender;
import avro.parser : Parser;
import avro.codec.binaryencoder;
auto parser = new Parser();
Schema schema = parser.parseText(q"EOS
{"namespace": "example.avro",
"type": "record",
"name": "User",
"fields": [
{"name": "name", "type": "string"},
{"name": "favorite_number", "type": ["int", "null"]},
{"name": "favorite_color", "type": ["string", "null"]}
]
}
EOS");
GenericDatum datum = new GenericDatum(schema);
assert(datum.getType == Type.RECORD);
datum["name"].setValue("bob");
assert(datum["name"].getValue!string == "bob");
datum["favorite_number"].setUnionIndex(0);
assert(datum["favorite_number"].getUnionIndex() == 0);
datum["favorite_number"].setValue(8);
assert(datum["favorite_number"].getValue!int == 8);
datum["favorite_color"].setUnionIndex(0);
assert(datum["favorite_color"].getUnionIndex() == 0);
datum["favorite_color"].setValue("blue");
assert(datum["favorite_color"].getValue!string == "blue");
ubyte[] data;
auto encoder = binaryEncoder(appender(&data));
GenericWriter writer = new GenericWriter(schema, encoder);
writer.write(datum);
assert(data == [
// Field: name
// len=3 b o b
0x06, 0x62, 0x6F, 0x62,
// Field: favorite_number
// idx=0 8
0x00, 0x10,
// Field: favorite_color
// idx=0 len=4 b l u e
0x00, 0x08, 0x62, 0x6C, 0x75, 0x65
], data.map!(a => format!("0x%02X")(a)).joiner(" ").to!string);
Example
import std.format;
import std.algorithm;
import std.json : parseJSON;
import std.array : appender;
import avro.parser : Parser;
import avro.codec.jsonencoder : jsonEncoder;
auto parser = new Parser();
Schema schema = parser.parseText(q"EOS
{"namespace": "example.avro",
"type": "record",
"name": "User",
"fields": [
{"name": "name", "type": "string"},
{"name": "favorite_number", "type": ["int", "null"]},
{"name": "favorite_color", "type": ["string", "null"]}
]
}
EOS");
GenericDatum datum = new GenericDatum(schema);
datum["name"].setValue("bob");
datum["favorite_number"].setUnionIndex(0);
datum["favorite_number"].setValue(8);
datum["favorite_color"].setUnionIndex(1);
//datum["favorite_color"].setValue("blue");
string data;
auto encoder = jsonEncoder(appender(&data));
GenericWriter writer = new GenericWriter(schema, encoder);
writer.write(datum);
assert(parseJSON(data) == parseJSON(
`{"name": "bob", "favorite_number": {"int": 8}, "favorite_color": { "null": null } }`));