pub trait Bufferwhere
Self: Sized,{
type Error;
// Required methods
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;
}
Expand description
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();
Required Associated Types§
Required Methods§
Sourcefn new(cap: usize) -> Result<Self, Self::Error>
fn new(cap: usize) -> Result<Self, Self::Error>
Allocate new buffer of at least size cap
, or more.
Sourcefn appendable(&mut self) -> &mut [u8] ⓘ
fn appendable(&mut self) -> &mut [u8] ⓘ
Sourcefn grow(&mut self, amount: usize)
fn grow(&mut self, amount: usize)
Attaches amount
bytes of appendable()
to filled()
part of the buffer
Sourcefn consume(&mut self, amount: usize) -> &[u8] ⓘ
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
).
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.