buf_ref_reader/buffer/mod.rs
1/**
2This trait abstracts common operations with actual buffer from implementation details
3
4## Example usage
5
6```no_run
7use buf_ref_reader::Buffer;
8use memchr::memchr;
9use std::io::Read;
10
11# fn foo<SomeBuffer: Buffer, R: Read>(mut input: R) -> Result<(), SomeBuffer::Error> {
12// allocate 128 bytes of buffer or more
13let mut buf = SomeBuffer::new(128)?;
14
15// write data into free part of the buffer
16let read = input.read(buf.appendable()).unwrap();
17// append actually written bytes
18buf.grow(read);
19
20// read part of written data back
21// this slice is only valid until another call to one of `buf`'s methods
22let chunk = buf.consume(16);
23let _ = chunk.len();
24
25// we can also peek into filled part of the buffer
26// as with `consume()`, this slice also has limited shelf life
27let nl = memchr(b'\n', buf.filled());
28
29if buf.appendable().len() == 0 {
30 // reserve some space before appending even more data
31 buf.enlarge()?;
32}
33let read = input.read(buf.appendable()).unwrap();
34buf.grow(read);
35
36// borrow checker will prevent `chunk` from being used at this point,
37// and that makes sense as data might've been reallocated or destroyed
38// during further manipulations with the buffer (e.g. `enlarge()`)
39//let _ = chunk.len();
40
41# Ok(())
42# }
43```
44*/
45pub trait Buffer
46where Self: std::marker::Sized
47{
48 /// Error type emitted if failed to (re)allocate the buffer
49 type Error;
50 /// Allocate new buffer of at least size `cap`, or more.
51 fn new(cap: usize) -> Result<Self, Self::Error>;
52 /**
53 Part of the buffer next to the [`filled()`](#tymethod.filled) that can be used to append data.
54
55 Use [`grow()`](#tymethod.grow) to actually append data written to this slice.
56 */
57 fn appendable(&mut self) -> &mut [u8];
58 /// Attaches `amount` bytes of [`appendable()`](#tymethod.appendable)
59 /// to [`filled()`](#tymethod.filled) part of the buffer
60 fn grow(&mut self, amount: usize);
61 /**
62 Split [`filled()`](#tymethod.filled) part of the buffer,
63 returning up to `amount` bytes from the beginning while also marking them as discarded
64 right after lifetime of returned slice ends (i.e. before another call to any of `Buffer`'s methods that accepts `&mut self`).
65 */
66 fn consume(&mut self, amount: usize) -> &[u8];
67 /// Grow [`appendable()`](#tymethod.appendable) part of the buffer one way or the other
68 /// (by e.g. reallocating filled part of the buffer, or reallocating buffer itself)
69 fn enlarge(&mut self) -> Result<(), Self::Error>;
70 /// Return filled part of the buffer
71 fn filled(&self) -> &[u8];
72 /**
73 Size of [`filled()`](#tymethod.filled) part of the buffer
74
75 This is generally faster (and a bit more readable) than equivalent call to `.filled().len()`.
76 */
77 fn len(&self) -> usize;
78}
79
80mod vec;
81pub use vec::*;
82
83mod mmap;
84pub use mmap::*;