const KEPT: usize = 32;
const DATAGRAMS: usize = 64;
pub(crate) const MIN_QUOTE: usize = 13;
pub(crate) struct SentDatagrams {
starts: Box<[[u8; KEPT]; DATAGRAMS]>,
lengths: [u8; DATAGRAMS],
next: usize,
}
impl Default for SentDatagrams {
fn default() -> Self {
Self {
starts: Box::new([[0; KEPT]; DATAGRAMS]),
lengths: [0; DATAGRAMS],
next: 0,
}
}
}
impl SentDatagrams {
pub(crate) fn record(&mut self, datagram: &[u8]) {
let kept = datagram.len().min(KEPT);
self.starts[self.next][..kept].copy_from_slice(&datagram[..kept]);
self.lengths[self.next] = kept as u8;
self.next = (self.next + 1) % DATAGRAMS;
}
pub(crate) fn begins_with(&self, quoted: &[u8]) -> Option<bool> {
if quoted.len() < MIN_QUOTE {
return None;
}
Some(self.starts.iter().zip(self.lengths).any(|(start, length)| {
let compared = quoted.len().min(usize::from(length));
compared >= MIN_QUOTE && start[..compared] == quoted[..compared]
}))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn a_quote_matches_only_the_beginning_of_a_datagram_sent() {
let mut sent = SentDatagrams::default();
let datagram: Vec<u8> = (0..100).collect();
sent.record(&datagram);
assert_eq!(sent.begins_with(&datagram[..12]), None, "too short to tell");
assert_eq!(sent.begins_with(&datagram[..13]), Some(true));
assert_eq!(sent.begins_with(&datagram), Some(true), "a longer quote");
assert_eq!(sent.begins_with(&datagram[1..40]), Some(false));
for other in 0..DATAGRAMS as u8 {
sent.record(&[other + 101; 40]);
}
assert_eq!(sent.begins_with(&datagram), Some(false), "pushed out");
}
}