use std::collections::VecDeque;
#[derive(Debug, Clone)]
pub struct Snapshot {
pub lines: Vec<String>,
pub cursor: (usize, usize),
}
impl Snapshot {
pub fn new(lines: Vec<String>) -> Self {
Self {
lines,
cursor: (0, 0),
}
}
pub fn with_cursor(lines: Vec<String>, cursor: (usize, usize)) -> Self {
Self { lines, cursor }
}
}
#[derive(Debug, Clone)]
pub struct History {
stack: VecDeque<Snapshot>,
cursor: usize,
max_size: usize,
}
impl Default for History {
fn default() -> Self {
Self::new()
}
}
impl History {
pub fn new() -> Self {
Self {
stack: VecDeque::new(),
cursor: 0,
max_size: 100,
}
}
pub fn push(&mut self, snapshot: Snapshot) {
if self.cursor < self.stack.len() {
self.stack.truncate(self.cursor);
}
self.stack.push_back(snapshot);
self.cursor = self.stack.len();
if self.stack.len() > self.max_size {
self.stack.pop_front();
self.cursor = self.cursor.saturating_sub(1);
}
}
pub fn undo(&mut self) -> Option<&Snapshot> {
if self.cursor > 1 {
self.cursor -= 1;
self.stack.get(self.cursor - 1)
} else {
None
}
}
pub fn redo(&mut self) -> Option<&Snapshot> {
if self.cursor < self.stack.len() {
self.cursor += 1;
self.stack.get(self.cursor - 1)
} else {
None
}
}
}