use super::cell::Cell;
use super::layout::{Frame, Row};
use super::writer::Writer;
const GAP: usize = 4;
const ERASE_COST: usize = 3;
pub(crate) fn draw(w: &mut Writer, old: &Frame, new: &Frame) {
for (y, row) in new.rows.iter().enumerate() {
match old.rows.get(y) {
Some(was) if was.hash == row.hash && was == row => {}
Some(was) => update_row(w, y, was, row),
None => update_row(w, y, &Row::blank(new.width), row),
}
}
}
fn update_row(w: &mut Writer, y: usize, old: &Row, new: &Row) {
let (new_end, old_end) = (new.content_end(), old.content_end());
let erase_from = tail_start(old, new, new_end, old_end);
let limit = erase_from.unwrap_or_else(|| new_end.max(old_end));
for (from, to) in spans(&old.cells, &new.cells, limit) {
let from = rewind(w, y, from, &old.cells, &new.cells);
w.move_to(from, y);
for cell in &new.cells[from..to] {
w.put(cell);
}
}
if let Some(x) = erase_from {
w.move_to(x, y);
w.erase_line_right();
}
}
fn rewind(w: &Writer, y: usize, from: usize, old: &[Cell], new: &[Cell]) -> usize {
match w.x {
Some(x) if w.y == y && x < from && from - x < ERASE_COST => {
let start = widen_left(old, new, x);
if start == x { x } else { from }
}
_ => from,
}
}
fn tail_start(old: &Row, new: &Row, new_end: usize, old_end: usize) -> Option<usize> {
if old_end <= new_end {
return None;
}
let first = (new_end..old_end).find(|&i| old.cells[i] != new.cells[i])?;
(old_end - first > ERASE_COST).then_some(new_end)
}
fn spans(old: &[Cell], new: &[Cell], limit: usize) -> Vec<(usize, usize)> {
let mut out: Vec<(usize, usize)> = Vec::new();
let mut i = 0;
while i < limit {
if old[i] == new[i] {
i += 1;
continue;
}
let to = run_end(old, new, i, limit);
join(&mut out, widen_left(old, new, i), to);
i = to;
}
out
}
fn run_end(old: &[Cell], new: &[Cell], i: usize, limit: usize) -> usize {
let mut to = i + 1;
while to < limit && old[to] != new[to] {
to += 1;
}
widen_right(old, new, to)
}
fn join(out: &mut Vec<(usize, usize)>, from: usize, to: usize) {
match out.last_mut() {
Some(last) if from <= last.1 + GAP => last.1 = last.1.max(to),
_ => out.push((from, to)),
}
}
fn widen_left(old: &[Cell], new: &[Cell], mut i: usize) -> usize {
while i > 0 && (old[i].is_continuation() || new[i].is_continuation()) {
i -= 1;
}
i
}
fn widen_right(old: &[Cell], new: &[Cell], mut to: usize) -> usize {
while to < new.len() && (old[to].is_continuation() || new[to].is_continuation()) {
to += 1;
}
to
}
#[cfg(test)]
mod tests;