Module encdec::decode

source ·
Expand description

Decode traits and helper macros

Example

#[derive(Debug, PartialEq)]
struct SomethingOwned {
    a: u8,
    b: u16,
    c: [u8; 3],
}

/// [`DecodeOwned`] implementation for self-contained types.
impl DecodeOwned for SomethingOwned {
    type Output = Self;
    type Error = Error;

   /// Decode object from provided buffer, returning object and decoded
   /// length on success
   fn decode_owned(buff: &[u8]) -> Result<(Self::Output, usize), Self::Error> {
        let mut index = 0;

        let a = buff[0];
        index += 1;

        let b = buff[1] as u16 | (buff[2] as u16) << 8;
        index += 2;

        let mut c = [0u8; 3];
        c.copy_from_slice(&buff[3..][..3]);
        index += 3;

        Ok((Self{a, b, c}, index))
   }
}
#[derive(Debug, PartialEq)]
struct SomethingBorrowed<'a> {
    a: u8,
    l: u16,
    c: &'a [u8],
}

/// Base [`Decode`] implementation, lifetime support for views
/// into borrowed buffers. If you don't need this, see [`DecodeOwned`].
impl <'a>Decode<'a> for SomethingBorrowed<'a> {
    type Output = SomethingBorrowed<'a>;
    type Error = Error;

   /// Decode object from provided buffer, returning object and decoded
   /// length on success
   fn decode(buff: &'a [u8]) -> Result<(Self::Output, usize), Self::Error> {
        let mut index = 0;

        let a = buff[0];
        index += 1;

        // using `l` as the length of `c`
        let l = buff[1] as u16 | (buff[2] as u16) << 8;
        index += 2;

        let c = &buff[index..][..l as usize];

        Ok((Self{a, l, c}, index))
   }
}

Structs

Helper type for parsing lists of decodable objects (with internal length delimiters)

Traits

Decode trait implemented for binary decodable objects
Extensions to Decode trait for decodable objects
Decode trait implemented for owned types
Decode helper trait for fields with length prefixes
Decode helper trait for for fields with external length tags (length must be specified via #[encdec(length=...)] macro)

Derive Macros

#[derive(Decode)] support.
#[derive(DecodeOwned)] support.