Module encdec::encode

source ·
Expand description

Encode traits and helper macros

Example

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

impl Encode for Something {
    type Error = Error;

    /// Fetch encoded length for an encodable object    
    fn encode_len(&self) -> Result<usize, Self::Error> {
        Ok(1 + 2 + 3)
    }

   /// Encode object to the provided buffer,
   /// returning the encoded length on success
   fn encode(&self, buff: &mut [u8]) -> Result<usize, Self::Error> {
       let mut index = 0;
       buff[index] = self.a;
       index += 1;

       buff[1] = self.b as u8;
       buff[2] = (self.b >> 8) as u8;
       index += 2;

       buff[3..][..3].copy_from_slice(&self.c);
       index += 3;
        
       Ok(index)
   }
}

Traits

Derive Macros

  • #[derive(Encode)] support.