buf_ref_reader/buffer/
vec.rs

1// https://github.com/rust-lang/rust/issues/54236
2use copy_in_place::*;
3
4/// `Vec`-backed buffer
5pub struct VecBuffer {
6	buf: Vec<u8>,
7	// where actual data resides within the `buf`
8	start: usize,
9	end: usize,
10}
11impl super::Buffer for VecBuffer {
12	type Error = ();
13	fn new(size: usize) -> Result<Self, ()> {
14		let mut buf = Vec::with_capacity(size);
15		unsafe { buf.set_len(size); }
16		Ok(VecBuffer {
17			buf,
18			start: 0, end: 0,
19		})
20	}
21	// make room for new data one way or the other
22	fn enlarge(&mut self) -> Result<(), ()> {
23		//if self.start == 0 && self.end == self.buf.len() {
24		if self.len() == self.buf.len() {
25			// this buffer is already full, double its size
26			self.buf.reserve(self.buf.len());
27			unsafe { self.buf.set_len(self.buf.len() * 2) };
28		} else {
29			// reallocate and fill existing buffer
30			if self.end - self.start != 0 {
31				//self.buf.copy_within(self.start..self.end, 0)
32				copy_in_place(&mut self.buf, self.start..self.end, 0);
33			}
34			self.end -= self.start;
35			self.start = 0;
36		}
37		Ok(())
38	}
39	fn len(&self) -> usize {
40		self.end - self.start
41	}
42	fn filled(&self) -> &[u8] {
43		&self.buf[ self.start .. self.end ]
44	}
45	fn appendable(&mut self) -> &mut [u8] {
46		&mut self.buf[ self.end .. ]
47	}
48	fn grow(&mut self, amount: usize) {
49		self.end += amount;
50	}
51	/*
52	before:
53	|  xxxyyy |
54	   |    |end
55	   |start
56
57	after:
58	|  xxxyyy |
59	   | || |end
60	   | ||start
61	   |-|return value
62	*/
63	fn consume(&mut self, amount: usize) -> &[u8] {
64		let amount = std::cmp::min(amount, self.len());
65		let start = self.start;
66		self.start += amount;
67		&self.buf[ start .. (start+amount) ]
68	}
69}