Trait FromBytes

Source
pub trait FromBytes {
    // Required method
    fn from_bytes(bytes: &[u8]) -> Result<Box<Self>>;

    // Provided methods
    fn u8_to_u16(upper: u8, lower: u8) -> u16 { ... }
    fn u8_to_u32(bytes_slice: &[u8]) -> Result<u32> { ... }
}
Expand description

Used to convert raw bytes representation into a Rust struct

Example:

let mut buf: Vec<u8> = Vec::new();
// Read the response from a stream
stream.read_to_end(&mut buf).await.unwrap();
// Interpret the response into a struct S
let resp = S::from_bytes(&buf);

In the above code, resp is Option<Box<S>> type, so you will have to deal with the None value appropriately. This helps denote invalid situations, ie, parse failures

You will have to interpret each byte and convert it into each field of your struct yourself when implementing this trait.

Required Methods§

Source

fn from_bytes(bytes: &[u8]) -> Result<Box<Self>>

Try converting given bytes into the struct

Returns an Option<Box> of the struct which implements this trait to help denote parsing failures

Provided Methods§

Source

fn u8_to_u16(upper: u8, lower: u8) -> u16

Convert two u8’s into a u16

It is just a thin wrapper over u16::from_be_bytes()

Source

fn u8_to_u32(bytes_slice: &[u8]) -> Result<u32>

Convert four u8’s contained in a slice into a u32

It is just a thin wrapper over u32::from_be_bytes() but also deals with converting &[u8] (u8 slice) into [u8; 4] (a fixed size array of u8)

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.

Implementors§