1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
use crate::{Checkpoint, Command, Entry, Record, Result};
#[derive(Debug)]
pub struct Queue<'a, T: 'static> {
record: &'a mut Record<T>,
commands: Vec<QueueCommand<T>>,
}
impl<'a, T> Queue<'a, T> {
pub fn apply(&mut self, command: impl Command<T>) {
self.commands.push(QueueCommand::Apply(Box::new(command)));
}
pub fn undo(&mut self) {
self.commands.push(QueueCommand::Undo);
}
pub fn redo(&mut self) {
self.commands.push(QueueCommand::Redo);
}
pub fn commit(self) -> Result {
for command in self.commands {
match command {
QueueCommand::Apply(command) => self.record.apply(Entry::new(command))?,
QueueCommand::Undo => self.record.undo()?,
QueueCommand::Redo => self.record.redo()?,
}
}
Ok(())
}
pub fn cancel(self) {}
pub fn queue(&mut self) -> Queue<T> {
self.record.queue()
}
pub fn checkpoint(&mut self) -> Checkpoint<T> {
self.record.checkpoint()
}
pub fn target(&self) -> &T {
self.record.target()
}
}
impl<'a, T> From<&'a mut Record<T>> for Queue<'a, T> {
fn from(record: &'a mut Record<T>) -> Self {
Queue {
record,
commands: Vec::new(),
}
}
}
#[derive(Debug)]
enum QueueCommand<T> {
Apply(Box<dyn Command<T>>),
Undo,
Redo,
}
#[cfg(test)]
mod tests {
use crate::*;
#[derive(Debug)]
struct Add(char);
impl Command<String> for Add {
fn apply(&mut self, s: &mut String) -> Result {
s.push(self.0);
Ok(())
}
fn undo(&mut self, s: &mut String) -> Result {
self.0 = s.pop().ok_or("s is empty")?;
Ok(())
}
}
#[test]
fn commit() {
let mut record = Record::default();
let mut q1 = record.queue();
q1.redo();
q1.redo();
q1.redo();
let mut q2 = q1.queue();
q2.undo();
q2.undo();
q2.undo();
let mut q3 = q2.queue();
q3.apply(Add('a'));
q3.apply(Add('b'));
q3.apply(Add('c'));
assert_eq!(q3.target(), "");
q3.commit().unwrap();
assert_eq!(q2.target(), "abc");
q2.commit().unwrap();
assert_eq!(q1.target(), "");
q1.commit().unwrap();
assert_eq!(record.target(), "abc");
}
}