pub trait Decode<Format = ()>: Sized {
// Required method
fn decode<R: BufRead>(r: &mut Reader<R>) -> Result<Self, DecodeError>;
}Expand description
Types which can be decoded from storekey format with owned ownership.
Please refer to the documentation of the Encode trait for an explanation of how the data is
encoded.
§Implementing decode
Implementing decode is mostly very straight forward.
use std::io::BufRead;
struct MyStruct{
field_a: u32,
field_b: String,
}
impl Decode for MyStruct{
fn decode<R: BufRead>(r: &mut Reader<R>) -> Result<Self, DecodeError>{
let field_a = Decode::<()>::decode(r)?;
let field_b = Decode::<()>::decode(r)?;
Ok(MyStruct{
field_a,
field_b
})
}
}
enum MyEnum{
VariantA(u32),
VariantB(String),
}
impl Decode for MyEnum{
fn decode<R: BufRead>(r: &mut Reader<R>) -> Result<Self, DecodeError>{
match r.read_u8()? {
// One good pattern is to avoid using 0 or 1 as a discriminant as these might need
// to be escaped
2 => Ok(MyEnum::VariantA(Decode::<()>::decode(r)?)),
3 => Ok(MyEnum::VariantB(Decode::<()>::decode(r)?)),
_ => Err(DecodeError::InvalidFormat)
}
}
}For runtime size typed it is often best to read values in a while loop using the
Reader::read_terminal method.
use std::io::BufRead;
struct MyVec(Vec<u8>);
impl Decode for MyVec{
fn decode<R: BufRead>(r: &mut Reader<R>) -> Result<Self, DecodeError>{
let mut res = Vec::new();
while r.read_terminal()? {
res.push(Decode::<()>::decode(r)?);
}
Ok(MyVec(res))
}
}Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.