pub trait Decode: Sized {
// Required method
fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError>;
}
Expand description
Trait that makes a type able to be decoded, akin to serde’s DeserializeOwned
trait.
This trait should be implemented for types which do not have references to data in the reader. For types that contain e.g. &str
and &[u8]
, implement BorrowDecode instead.
Whenever you implement Decode
for your type, the base trait BorrowDecode
is automatically implemented.
This trait will be automatically implemented if you enable the derive
feature and add #[derive(bincode::Decode)]
to your type. Note that if the type contains any lifetimes, BorrowDecode
will be implemented instead.
§Implementing this trait manually
If you want to implement this trait for your type, the easiest way is to add a #[derive(bincode::Decode)]
, build and check your target/generated/bincode/
folder. This should generate a <Struct name>_Decode.rs
file.
For this struct:
struct Entity {
pub x: f32,
pub y: f32,
}
It will look something like:
impl bincode::Decode for Entity {
fn decode<D: bincode::de::Decoder>(
decoder: &mut D,
) -> core::result::Result<Self, bincode::error::DecodeError> {
Ok(Self {
x: bincode::Decode::decode(decoder)?,
y: bincode::Decode::decode(decoder)?,
})
}
}
impl<'de> bincode::BorrowDecode<'de> for Entity {
fn borrow_decode<D: bincode::de::BorrowDecoder<'de>>(
decoder: &mut D,
) -> core::result::Result<Self, bincode::error::DecodeError> {
Ok(Self {
x: bincode::BorrowDecode::borrow_decode(decoder)?,
y: bincode::BorrowDecode::borrow_decode(decoder)?,
})
}
}
From here you can add/remove fields, or add custom logic.
To get specific integer types, you can use:
let x: u8 = bincode::Decode::decode(decoder)?;
let x = <u8 as bincode::Decode>::decode(decoder)?;