use std::io;
use std::io::Read;
#[derive(Debug)]
pub struct ReadBuffer<const SIZE: usize> {
buffer: [u8; SIZE],
}
impl<const SIZE: usize> ReadBuffer<SIZE> {
pub fn new() -> Self {
Self {
buffer: [0u8; SIZE],
}
}
pub fn read_from(&mut self, source: &mut impl Read) -> Result<&[u8], io::Error> {
let length = source.read(&mut self.buffer)?;
Ok(&self.buffer[..length])
}
pub fn read_while(&mut self, source: &mut impl Read, mut predicate: impl FnMut(&[u8]) -> bool) -> Result<&[u8], io::Error> {
let mut remaining = &mut self.buffer[..];
loop {
let length = source.read(remaining)?;
if length == 0 {
break;
}
let chunk: &mut [u8];
(chunk, remaining) = remaining.split_at_mut(length);
if !predicate(chunk) || remaining.is_empty() {
break;
}
}
let read_bytes = SIZE - remaining.len();
Ok(&self.buffer[..read_bytes])
}
pub const fn capacity(&self) -> usize {
SIZE
}
}
impl<const SIZE: usize> Default for ReadBuffer<SIZE> {
fn default() -> Self {
Self::new()
}
}