#[derive(Debug, Clone)]
pub struct DrawnRows<K> {
rows: Vec<(usize, K)>,
}
impl<K> Default for DrawnRows<K> {
fn default() -> Self {
Self { rows: Vec::new() }
}
}
impl<K> DrawnRows<K> {
pub fn clear(&mut self) {
self.rows.clear();
}
pub fn record(&mut self, rows: impl IntoIterator<Item = (usize, K)>) {
self.rows.clear();
self.rows.extend(rows);
}
pub fn record_borrowed<'a, Q>(&mut self, rows: impl IntoIterator<Item = (usize, &'a Q)>)
where
Q: ?Sized + PartialEq + ToOwned<Owned = K> + 'a,
K: std::borrow::Borrow<Q>,
{
let mut i = 0;
for (at, key) in rows {
if let Some(slot) = self.rows.get_mut(i) {
slot.0 = at;
if slot.1.borrow() != key {
key.clone_into(&mut slot.1);
}
} else {
self.rows.push((at, key.to_owned()));
}
i += 1;
}
self.rows.truncate(i);
}
pub fn lines(&self) -> usize {
self.rows.len()
}
#[cfg(test)]
pub fn drawn_at(&self) -> impl Iterator<Item = usize> + '_ {
self.rows.iter().map(|&(at, _)| at)
}
pub fn now(&self, line: usize, len: usize, holds: impl Fn(usize, &K) -> bool) -> Option<usize> {
let (at, key) = self.rows.get(line)?;
follow(*at, key, len, holds)
}
}
pub fn follow<K>(
at: usize,
key: &K,
len: usize,
holds: impl Fn(usize, &K) -> bool,
) -> Option<usize> {
if at < len && holds(at, key) {
return Some(at);
}
(0..len).find(|&i| holds(i, key))
}
#[cfg(test)]
mod tests {
use super::*;
fn drawn(rows: &[(usize, &'static str)]) -> DrawnRows<&'static str> {
let mut d = DrawnRows::default();
d.record(rows.iter().copied());
d
}
#[test]
fn a_row_still_in_its_place_is_met_there() {
let list = ["a", "b", "c"];
let d = drawn(&[(1, "b"), (2, "c")]);
assert_eq!(d.now(0, list.len(), |i, k| list[i] == *k), Some(1));
}
#[test]
fn a_row_that_moved_is_followed() {
let list = ["x", "y", "a", "b", "c"];
let d = drawn(&[(1, "b"), (2, "c")]);
assert_eq!(d.now(0, list.len(), |i, k| list[i] == *k), Some(3));
}
#[test]
fn a_row_that_is_gone_or_a_line_past_the_rows_meets_nothing() {
let list = ["a", "c"];
let d = drawn(&[(1, "b"), (2, "c")]);
assert_eq!(d.now(0, list.len(), |i, k| list[i] == *k), None);
assert_eq!(d.now(2, list.len(), |i, k| list[i] == *k), None);
}
#[test]
fn record_borrowed_reuses_unchanged_slots_without_allocating() {
let mut d: DrawnRows<String> = DrawnRows::default();
d.record_borrowed([(0, "alpha"), (1, "beta")]);
let ((), made) = crate::alloc_count::allocations_in(|| {
d.record_borrowed([(0, "alpha"), (1, "beta")]);
});
assert_eq!(made, 0, "unchanged rows should reuse owned slots");
d.record_borrowed([(0, "gamma")]);
let list = ["gamma", "beta"];
assert_eq!(d.now(0, list.len(), |i, k| list[i] == *k), Some(0));
assert_eq!(d.now(1, list.len(), |i, k| list[i] == *k), None);
}
}