[][src]Trait buf_ref_reader::Buffer

pub trait Buffer where
    Self: Sized
{ type Error; fn new(cap: usize) -> Result<Self, Self::Error>;
fn appendable(&mut self) -> &mut [u8];
fn grow(&mut self, amount: usize);
fn consume(&mut self, amount: usize) -> &[u8];
fn enlarge(&mut self) -> Result<(), Self::Error>;
fn filled(&self) -> &[u8];
fn len(&self) -> usize; }

This trait abstracts common operations with actual buffer from implementation details

Example usage

use buf_ref_reader::Buffer;
use memchr::memchr;
use std::io::Read;

// allocate 128 bytes of buffer or more
let mut buf = SomeBuffer::new(128)?;

// write data into free part of the buffer
let read = input.read(buf.appendable()).unwrap();
// append actually written bytes
buf.grow(read);

// read part of written data back
// this slice is only valid until another call to one of `buf`'s methods
let chunk = buf.consume(16);
let _ = chunk.len();

// we can also peek into filled part of the buffer
// as with `consume()`, this slice also has limited shelf life
let nl = memchr(b'\n', buf.filled());

if buf.appendable().len() == 0 {
    // reserve some space before appending even more data
    buf.enlarge()?;
}
let read = input.read(buf.appendable()).unwrap();
buf.grow(read);

// borrow checker will prevent `chunk` from being used at this point,
// and that makes sense as data might've been reallocated or destroyed
// during further manipulations with the buffer (e.g. `enlarge()`)
//let _ = chunk.len();

Associated Types

type Error

Error type emitted if failed to (re)allocate the buffer

Loading content...

Required methods

fn new(cap: usize) -> Result<Self, Self::Error>

Allocate new buffer of at least size cap, or more.

fn appendable(&mut self) -> &mut [u8]

Part of the buffer next to the filled() that can be used to append data.

Use grow() to actually append data written to this slice.

fn grow(&mut self, amount: usize)

Attaches amount bytes of appendable() to filled() part of the buffer

fn consume(&mut self, amount: usize) -> &[u8]

Split filled() part of the buffer, returning up to amount bytes from the beginning while also marking them as discarded right after lifetime of returned slice ends (i.e. before another call to any of Buffer's methods that accepts &mut self).

fn enlarge(&mut self) -> Result<(), Self::Error>

Grow appendable() part of the buffer one way or the other (by e.g. reallocating filled part of the buffer, or reallocating buffer itself)

fn filled(&self) -> &[u8]

Return filled part of the buffer

fn len(&self) -> usize

Size of filled() part of the buffer

This is generally faster (and a bit more readable) than equivalent call to .filled().len().

Loading content...

Implementors

impl Buffer for MmapBuffer[src]

type Error = AllocError

impl Buffer for VecBuffer[src]

type Error = ()

Loading content...