pub trait Encode {
// Required method
fn encode(
&self,
encoded: &mut [u8],
offset: &mut usize,
) -> Result<(), EncodeError>;
}Expand description
A trait for types that can encode themselves into a byte slice.
All the behavior should be same as implementing an Encoder for Self.
§Examples
§Encoding simple struct
use byten::{Encode, EncodeError};
struct MyType {
value: u32,
}
impl Encode for MyType {
fn encode(&self, encoded: &mut [u8], offset: &mut usize) -> Result<(), EncodeError> {
if *offset + 4 > encoded.len() {
return Err(EncodeError::BufferTooSmall);
}
encoded[*offset..*offset + 4].copy_from_slice(&self.value.to_le_bytes());
*offset += 4;
Ok(())
}
}
let my_type = MyType { value: 0x12345678 };
let mut data = vec![0u8; 4];
let mut offset = 0;
my_type.encode(&mut data, &mut offset).unwrap();
assert_eq!(data, vec![0x78, 0x56, 0x34, 0x12]);
assert_eq!(offset, 4);