pub trait Decode<Context>: Sized {
// Required method
fn decode<D: Decoder<Context = Context>>(
decoder: &mut D,
) -> Result<Self, DecodeError>;
}Expand description
Trait that makes a type able to be decoded, akin to serde’s DeserializeOwned trait.
Some types may require specific contexts. For example, to decode arena-based collections, an arena allocator must be provided as a context. In these cases, the context type Context should be specified or bounded.
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 derive Decode for your type, the base trait BorrowDecode is automatically implemented.
This trait will be automatically implemented with unbounded Context 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<Context> bincode::Decode<Context> for Entity {
fn decode<D: bincode::de::Decoder<Context = Context>>(
decoder: &mut D,
) -> core::result::Result<Self, bincode::error::DecodeError> {
Ok(Self {
x: bincode::Decode::decode(decoder)?,
y: bincode::Decode::decode(decoder)?,
})
}
}
impl<'de, Context> bincode::BorrowDecode<'de, Context> for Entity {
fn borrow_decode<D: bincode::de::BorrowDecoder<'de, Context = Context>>(
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::<Context>::decode(decoder)?;
let x = <u8 as bincode::Decode::<Context>>::decode(decoder)?;You can use Context to require contexts for decoding a type:
use bincode::de::Decoder;
use bincode::error::DecodeError;
struct BytesInArena<'a>(bumpalo::collections::Vec<'a, u8>);
impl<'a> bincode::Decode<&'a bumpalo::Bump> for BytesInArena<'a> {
fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError> {
todo!()
}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.