use std::io;
pub struct LinearBuf {
buf: Vec<u8>,
head: usize,
tail: usize,
limit: Option<usize>,
}
impl LinearBuf {
pub fn new(capacity: usize, limit: Option<usize>) -> io::Result<Self> {
let capacity = super::checked_capacity(capacity, limit)?;
Ok(Self {
buf: vec![0; capacity],
head: 0,
tail: 0,
limit,
})
}
#[allow(dead_code)]
pub fn capacity(&self) -> usize {
self.buf.len()
}
pub fn readable(&self) -> usize {
self.tail - self.head
}
pub fn writable(&self) -> usize {
self.buf.len() - self.readable()
}
pub fn data(&self) -> &[u8] {
&self.buf[self.head..self.tail]
}
pub fn data_mut(&mut self) -> &mut [u8] {
&mut self.buf[self.head..self.tail]
}
pub fn unused_mut(&mut self) -> &mut [u8] {
if self.head != 0 {
self.buf.copy_within(self.head..self.tail, 0);
self.tail -= self.head;
self.head = 0;
}
&mut self.buf[self.tail..]
}
pub fn produce(&mut self, n: usize) {
debug_assert!(n <= self.buf.len() - self.tail);
self.tail += n;
}
pub fn consume(&mut self, n: usize) {
debug_assert!(n <= self.readable());
self.head += n;
if self.head == self.tail {
self.reset();
}
}
pub fn reset(&mut self) {
self.head = 0;
self.tail = 0;
}
pub fn grow(&mut self) -> io::Result<()> {
let new_capacity = super::grown_capacity(self.buf.len(), self.limit)?;
self.buf.resize(new_capacity, 0);
Ok(())
}
}