Derive Macro encdec::Encode

source ·
#[derive(Encode)]
{
    // Attributes available to this derive:
    #[encdec]
}
Expand description

#[derive(Encode)] support.

generates an [Encode][encdec_base::encode::Encode] implementation equivalent to calling .encode() on each field in order.

for example:

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

// `#[derive(Decode)]` equivalent implementation
impl Encode for Something {
  type Error = Error;

  fn encode_len(&self) -> Result<usize, Self::Error> {
    Ok(1 + 2 + 3)
  }

  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)
  }
}