Skip to main content

Decode

Trait Decode 

Source
pub trait Decode<'de>: Sized {
    // Required method
    fn decode(buf: &mut ReadBuf<'de>) -> Result<Self>;
}
Expand description

A value that can be read from a ReadBuf.

The lifetime parameter 'de ties the decoded value to the borrowed input, enabling zero-copy decoding of borrowed payloads (&'de [u8], &'de str).

§Example

use wire_codec::{Decode, ReadBuf, Result};

struct Tagged {
    tag: u8,
    value: u32,
}

impl<'de> Decode<'de> for Tagged {
    fn decode(buf: &mut ReadBuf<'de>) -> Result<Self> {
        let tag = buf.read_u8()?;
        let value = buf.read_u32_be()?;
        Ok(Self { tag, value })
    }
}

let mut buf = ReadBuf::new(&[0x01, 0xCA, 0xFE, 0xBA, 0xBE]);
let tagged = Tagged::decode(&mut buf).unwrap();
assert_eq!(tagged.tag, 0x01);
assert_eq!(tagged.value, 0xCAFEBABE);

Required Methods§

Source

fn decode(buf: &mut ReadBuf<'de>) -> Result<Self>

Read a value of Self from buf, advancing its read position.

§Errors

Returns an error if buf is exhausted before the value finishes, or if the encoded bytes violate the codec’s structural rules.

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.

Implementations on Foreign Types§

Source§

impl<'de> Decode<'de> for u8

Source§

fn decode(buf: &mut ReadBuf<'de>) -> Result<Self>

Implementors§