pub trait Readable: Sized {
    fn take_from(b: &mut Reader<'_>) -> Result<Self>;
}
Expand description

Trait for an object that can be extracted from a Reader.

Implement this trait in order to make an object that can (maybe) be decoded from a reader. Most code won’t need to call this directly, but will instead use it implicitly via the Reader::extract() method.

Example

use tor_bytes::{Readable,Reader,Result};
#[derive(Debug, Eq, PartialEq)]
struct Message {
  flags: u32,
  cmd: u8
}

impl Readable for Message {
    fn take_from(r: &mut Reader<'_>) -> Result<Self> {
        // A "Message" is encoded as flags, then command.
        let flags = r.take_u32()?;
        let cmd = r.take_u8()?;
        Ok(Message{ flags, cmd })
    }
}

let encoded = [0x00, 0x00, 0x00, 0x43, 0x07 ];
let mut reader = Reader::from_slice(&encoded);
let m: Message = reader.extract()?;
assert_eq!(m, Message { flags: 0x43, cmd: 0x07 });
reader.should_be_exhausted()?; // make sure there are no bytes left over

Required Methods

Try to extract an object of this type from a Reader.

Implementations should generally try to be efficient: this is not the right place to check signatures or perform expensive operations. If you have an object that must not be used until it is finally validated, consider making this function return a wrapped type that can be unwrapped later on once it gets checked.

Implementations on Foreign Types

Implementors