[][src]Trait byteio::ReadBytes

pub trait ReadBytes<'a>: AsRef<[u8]> {
    fn read_exact(&mut self, n: usize) -> &'a [u8];

    fn try_read_exact(&mut self, n: usize) -> Result<&'a [u8]> { ... }

Read a slice of bytes from a buffer.

Readers can be thought of as cursors that only allow you to seek forward from the current position. They can be implemented with one method; read_exact. This forcibly attempts to split the underlying buffer in order to extract a sub-slice with a given length, and advance the buffer forward such that the next call to read_exact will return subsequent bytes in the buffer.

The lifetime of the slices extracted are tied to the underlying buffer. This allows you to compose structures borrowing from the underlying buffer.

ReadBytes uses AsRef<[u8]> as a supertrait. This means that a generic reader can obtain its current length or peek at the underlying bytes without advancing the cursor through read operations. Note that by using as_ref on a reader you discard the lifetime information of the underlying buffer for the returned reference.


Reading from a slice:

use byteio::ReadBytes;

fn main() {
    let mut buf = &[1, 2, 3, 4, 5][..];

    let sub_slice = buf.read_exact(2);
    assert_eq!(sub_slice, &[1, 2][..]);

    let sub_slice = buf.read_exact(3);
    assert_eq!(sub_slice, &[3, 4, 5][..]);


Building a structure using borrowed data:

use core::str;

use byteio::ReadBytes;

/// A packet whose payload is encoded as `[n, b0, b1, ..., bn-1]`.
struct Packet<'a> {
    payload: &'a [u8],

impl<'a> Packet<'a> {
    pub fn new<R: ReadBytes<'a>>(mut r: R) -> byteio::Result<Self> {
        let len: usize = r.try_read_exact(1)?[0].into();
        let payload = r.try_read_exact(len)?;

        Ok(Self { payload })

fn main() -> byteio::Result<()> {
    let buf = b"\x05hello";
    let packet = Packet::new(&buf[..])?;
    assert_eq!(str::from_utf8(packet.payload).unwrap(), "hello");


Required methods

fn read_exact(&mut self, n: usize) -> &'a [u8]

Forcibly attempts to read exactly n bytes from the buffer.


Panics if there are not enough bytes in self.

Loading content...

Provided methods

fn try_read_exact(&mut self, n: usize) -> Result<&'a [u8]>

Attempts to read exactly n bytes from the buffer.

If there are not enough bytes in self this function will return Error::EndOfStream.

Loading content...

Implementations on Foreign Types

impl<'a> ReadBytes<'a> for &'a [u8][src]

impl<'a> ReadBytes<'a> for &'a mut [u8][src]

impl<'a, '_, R: ReadBytes<'a>> ReadBytes<'a> for &'_ mut R[src]

Loading content...


impl<'a, R: ReadBytes<'a>> ReadBytes<'a> for Reader<'a, R>[src]

Loading content...