//! Simple undo/redo stack for editor text. const DEFAULT_LIMIT: usize = 100; pub struct TextUndo { undo: Vec, redo: Vec, limit: usize, } impl Default for TextUndo { fn default() -> Self { Self { undo: Vec::new(), redo: Vec::new(), limit: DEFAULT_LIMIT, } } } impl TextUndo { pub fn record(&mut self, before: String) { if self.undo.last() == Some(&before) { return; } self.undo.push(before); if self.undo.len() > self.limit { self.undo.remove(0); } self.redo.clear(); } pub fn undo(&mut self, current: &str) -> Option { let prev = self.undo.pop()?; self.redo.push(current.to_string()); Some(prev) } pub fn redo(&mut self, current: &str) -> Option { let next = self.redo.pop()?; self.undo.push(current.to_string()); Some(next) } } #[cfg(test)] mod tests { use super::*; #[test] fn undo_redo_roundtrip() { let mut stack = TextUndo::default(); stack.record("a".into()); let u = stack.undo("b").unwrap(); assert_eq!(u, "a"); let r = stack.redo("a").unwrap(); assert_eq!(r, "b"); } }