use std::ops::Deref;
#[derive(Debug, Default)]
pub(crate) struct Tail {
held: Vec<u8>,
at: usize,
}
impl Tail {
pub(crate) fn of(held: Vec<u8>, at: usize) -> Option<Self> {
(at <= held.len()).then_some(Self { held, at })
}
}
impl From<Vec<u8>> for Tail {
fn from(held: Vec<u8>) -> Self {
Self { held, at: 0 }
}
}
impl Deref for Tail {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.held[self.at..]
}
}
impl Clone for Tail {
fn clone(&self) -> Self {
Self::from(self.to_vec())
}
}
#[cfg(test)]
mod tests {
use super::Tail;
#[test]
fn a_tail_is_the_bytes_past_its_start_and_a_clone_holds_only_those() {
let tail = Tail::of(vec![1, 2, 3, 4, 5], 2).expect("inside the buffer");
assert_eq!(&*tail, &[3, 4, 5]);
let copy = tail.clone();
assert_eq!(&*copy, &[3, 4, 5]);
assert_eq!(copy.held.len(), 3);
assert!(Tail::of(vec![1, 2], 3).is_none());
assert!(Tail::of(vec![1, 2], 2).is_some_and(|tail| tail.is_empty()));
}
}