excel_cli/actions/
history.rs

1use super::ActionCommand;
2use std::rc::Rc;
3
4pub struct UndoHistory {
5    undo_stack: Vec<Rc<ActionCommand>>,
6    redo_stack: Vec<Rc<ActionCommand>>,
7}
8
9impl Default for UndoHistory {
10    fn default() -> Self {
11        Self::new()
12    }
13}
14
15impl UndoHistory {
16    pub fn new() -> Self {
17        Self {
18            undo_stack: Vec::with_capacity(100), // Pre-allocate capacity
19            redo_stack: Vec::with_capacity(20),
20        }
21    }
22
23    pub fn push(&mut self, action: ActionCommand) {
24        // Use Rc to avoid deep cloning the entire action
25        self.undo_stack.push(Rc::new(action));
26        self.redo_stack.clear();
27    }
28
29    pub fn undo(&mut self) -> Option<Rc<ActionCommand>> {
30        if let Some(action) = self.undo_stack.pop() {
31            self.redo_stack.push(Rc::clone(&action));
32            Some(action)
33        } else {
34            None
35        }
36    }
37
38    pub fn redo(&mut self) -> Option<Rc<ActionCommand>> {
39        if let Some(action) = self.redo_stack.pop() {
40            self.undo_stack.push(Rc::clone(&action));
41            Some(action)
42        } else {
43            None
44        }
45    }
46
47    pub fn all_undone(&self) -> bool {
48        self.undo_stack.is_empty()
49    }
50
51    pub fn clear(&mut self) {
52        self.undo_stack.clear();
53        self.redo_stack.clear();
54    }
55}