avro-rs
avro-rs copied to clipboard
Is it possible to Serialize/Deserialize rust enums?
Support for rust enum?
I appear to be able to serialize a struct with an enum, but can't deserialize. Is this feature supported?
Code below gives
Err(Error { message: "not an enum" })
Test code.
use avro_rs::{Codec, Reader, Schema, Writer, from_value};
use failure::Error;
use serde::{Serialize, Deserialize};
#[derive(Debug, Deserialize, Serialize)]
enum Suit {
Diamonds,
Spades,
Clubs,
Hearts
}
#[derive(Debug, Deserialize, Serialize)]
struct Test {
a: i64,
b: String,
c: Suit
}
fn main() -> Result<(), Error> {
let raw_schema = r#"
{
"type": "record",
"name": "Test",
"fields": [
{"name": "a", "type": "long", "default": 42},
{"name": "b", "type": "string"},
{
"name": "c",
"type": {
"type": "enum",
"name": "Suit",
"symbols": ["Diamonds", "Spades", "Clubs", "Hearts"]
},
"default": "Spades"
}
]
}
"#;
let schema = Schema::parse_str(raw_schema).unwrap();
let mut writer = Writer::with_codec(&schema, Vec::new(), Codec::Null);
let test = Test {
a: 1,
b: "Name".to_string(),
c: Suit::Spades
};
writer.append_ser(test)?;
writer.flush()?;
let input = writer.into_inner();
let reader = Reader::with_schema(&schema, &input[..]).unwrap();
for record in reader {
println!("{:?}", from_value::<Test>(&record?));
}
Ok(())
}
Here's an attempt to add that functionality: https://github.com/flavray/avro-rs/pull/76
You can preview it like that:
[dependencies]
serde = {version = "1.0.89", features = ["derive"]}
avro-rs = { git = "https://github.com/RGafiyatullin/avro-rs.git", tag = "rg-adt-serde-1553703171" }
This is not possible for an arbitrary Rust enum. Rust enums are more generic than C-style enums: each variant can contain arbitrary data.