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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
mod builder;
mod checkpoint;
mod display;
mod queue;
pub use builder::Builder;
pub use checkpoint::Checkpoint;
pub use display::Display;
pub use queue::Queue;
use crate::socket::{Nop, Slot, Socket};
use crate::{Action, Entry, History, Merged, Signal};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::num::NonZeroUsize;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug)]
pub struct Record<A, S = Nop> {
pub(crate) entries: VecDeque<Entry<A>>,
pub(crate) limit: NonZeroUsize,
pub(crate) current: usize,
pub(crate) saved: Option<usize>,
pub(crate) socket: Socket<S>,
}
impl<A> Record<A> {
pub fn new() -> Record<A> {
Record::builder().build()
}
}
impl<A, S> Record<A, S> {
pub fn builder() -> Builder<A, S> {
Builder::new()
}
pub fn reserve(&mut self, additional: usize) {
self.entries.reserve(additional);
}
pub fn capacity(&self) -> usize {
self.entries.capacity()
}
pub fn shrink_to_fit(&mut self) {
self.entries.shrink_to_fit();
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn limit(&self) -> usize {
self.limit.get()
}
pub fn connect(&mut self, slot: S) -> Option<S> {
self.socket.connect(Some(slot))
}
pub fn disconnect(&mut self) -> Option<S> {
self.socket.disconnect()
}
pub fn can_undo(&self) -> bool {
self.current > 0
}
pub fn can_redo(&self) -> bool {
self.current < self.len()
}
pub fn is_saved(&self) -> bool {
self.saved == Some(self.current)
}
pub fn current(&self) -> usize {
self.current
}
pub fn display(&self) -> Display<A, S> {
Display::from(self)
}
pub fn actions(&self) -> impl Iterator<Item = &A> {
self.entries.iter().map(|e| &e.action)
}
pub fn queue(&mut self) -> Queue<A, S> {
Queue::from(self)
}
pub fn checkpoint(&mut self) -> Checkpoint<A, S> {
Checkpoint::from(self)
}
}
impl<A: Action, S: Slot> Record<A, S> {
pub fn apply(&mut self, target: &mut A::Target, action: A) -> A::Output {
let (output, _, _) = self.__apply(target, action);
output
}
pub(crate) fn __apply(
&mut self,
target: &mut A::Target,
mut action: A,
) -> (A::Output, bool, VecDeque<Entry<A>>) {
let output = action.apply(target);
let current = self.current;
let could_undo = self.can_undo();
let could_redo = self.can_redo();
let was_saved = self.is_saved();
let tail = self.entries.split_off(current);
self.saved = self.saved.filter(|&saved| saved <= current);
let merged = match self.entries.back_mut() {
Some(last) if !was_saved => last.action.merge(action),
_ => Merged::No(action),
};
let merged_or_annulled = match merged {
Merged::Yes => true,
Merged::Annul => {
self.entries.pop_back();
self.current -= 1;
true
}
Merged::No(action) => {
if self.limit() == self.current {
self.entries.pop_front();
self.saved = self.saved.and_then(|saved| saved.checked_sub(1));
} else {
self.current += 1;
}
self.entries.push_back(Entry::from(action));
false
}
};
self.socket.emit_if(could_redo, Signal::Redo(false));
self.socket.emit_if(!could_undo, Signal::Undo(true));
self.socket.emit_if(was_saved, Signal::Saved(false));
(output, merged_or_annulled, tail)
}
pub fn undo(&mut self, target: &mut A::Target) -> Option<A::Output> {
self.can_undo().then(|| {
let was_saved = self.is_saved();
let old = self.current;
let output = self.entries[self.current - 1].undo(target);
self.current -= 1;
let is_saved = self.is_saved();
self.socket
.emit_if(old == self.entries.len(), Signal::Redo(true));
self.socket.emit_if(old == 1, Signal::Undo(false));
self.socket
.emit_if(was_saved != is_saved, Signal::Saved(is_saved));
output
})
}
pub fn redo(&mut self, target: &mut A::Target) -> Option<A::Output> {
self.can_redo().then(|| {
let was_saved = self.is_saved();
let old = self.current;
let output = self.entries[self.current].redo(target);
self.current += 1;
let is_saved = self.is_saved();
self.socket
.emit_if(old == self.len() - 1, Signal::Redo(false));
self.socket.emit_if(old == 0, Signal::Undo(true));
self.socket
.emit_if(was_saved != is_saved, Signal::Saved(is_saved));
output
})
}
pub fn set_saved(&mut self, saved: bool) {
let was_saved = self.is_saved();
if saved {
self.saved = Some(self.current);
self.socket.emit_if(!was_saved, Signal::Saved(true));
} else {
self.saved = None;
self.socket.emit_if(was_saved, Signal::Saved(false));
}
}
pub fn clear(&mut self) {
let could_undo = self.can_undo();
let could_redo = self.can_redo();
self.entries.clear();
self.saved = self.is_saved().then_some(0);
self.current = 0;
self.socket.emit_if(could_undo, Signal::Undo(false));
self.socket.emit_if(could_redo, Signal::Redo(false));
}
pub fn revert(&mut self, target: &mut A::Target) -> Vec<A::Output> {
self.saved
.map_or_else(Vec::new, |saved| self.go_to(target, saved))
}
pub fn go_to(&mut self, target: &mut A::Target, current: usize) -> Vec<A::Output> {
if current > self.len() {
return Vec::new();
}
let could_undo = self.can_undo();
let could_redo = self.can_redo();
let was_saved = self.is_saved();
let slot = self.socket.disconnect();
let undo_or_redo = if current > self.current {
Record::redo
} else {
Record::undo
};
let mut outputs = Vec::new();
while self.current != current {
let output = undo_or_redo(self, target).unwrap();
outputs.push(output);
}
let can_undo = self.can_undo();
let can_redo = self.can_redo();
let is_saved = self.is_saved();
self.socket.connect(slot);
self.socket
.emit_if(could_undo != can_undo, Signal::Undo(can_undo));
self.socket
.emit_if(could_redo != can_redo, Signal::Redo(can_redo));
self.socket
.emit_if(was_saved != is_saved, Signal::Saved(is_saved));
outputs
}
}
impl<A: ToString, S> Record<A, S> {
pub fn undo_string(&self) -> Option<String> {
self.current.checked_sub(1).and_then(|i| self.string_at(i))
}
pub fn redo_string(&self) -> Option<String> {
self.string_at(self.current)
}
fn string_at(&self, i: usize) -> Option<String> {
self.entries.get(i).map(|e| e.action.to_string())
}
}
impl<A> Default for Record<A> {
fn default() -> Record<A> {
Record::new()
}
}
impl<A, F> From<History<A, F>> for Record<A, F> {
fn from(history: History<A, F>) -> Record<A, F> {
history.record
}
}
#[cfg(test)]
mod tests {
use crate::*;
enum Edit {
Push(Push),
Pop(Pop),
}
impl Action for Edit {
type Target = String;
type Output = ();
fn apply(&mut self, s: &mut String) {
match self {
Edit::Push(add) => add.apply(s),
Edit::Pop(del) => del.apply(s),
}
}
fn undo(&mut self, s: &mut String) {
match self {
Edit::Push(add) => add.undo(s),
Edit::Pop(del) => del.undo(s),
}
}
fn merge(&mut self, edit: Self) -> Merged<Self>
where
Self: Sized,
{
match (self, edit) {
(Edit::Push(_), Edit::Pop(_)) => Merged::Annul,
(Edit::Pop(Pop(Some(a))), Edit::Push(Push(b))) if a == &b => Merged::Annul,
(_, edit) => Merged::No(edit),
}
}
}
#[derive(Debug, PartialEq)]
struct Push(char);
impl Action for Push {
type Target = String;
type Output = ();
fn apply(&mut self, s: &mut String) {
s.push(self.0);
}
fn undo(&mut self, s: &mut String) {
self.0 = s.pop().unwrap();
}
}
#[derive(Default)]
struct Pop(Option<char>);
impl Action for Pop {
type Target = String;
type Output = ();
fn apply(&mut self, s: &mut String) {
self.0 = s.pop();
}
fn undo(&mut self, s: &mut String) {
let ch = self.0.unwrap();
s.push(ch);
}
}
#[test]
fn go_to() {
let mut target = String::new();
let mut record = Record::new();
record.apply(&mut target, Push('a'));
record.apply(&mut target, Push('b'));
record.apply(&mut target, Push('c'));
record.apply(&mut target, Push('d'));
record.apply(&mut target, Push('e'));
record.go_to(&mut target, 0);
assert_eq!(record.current(), 0);
assert_eq!(target, "");
record.go_to(&mut target, 5);
assert_eq!(record.current(), 5);
assert_eq!(target, "abcde");
record.go_to(&mut target, 1);
assert_eq!(record.current(), 1);
assert_eq!(target, "a");
record.go_to(&mut target, 4);
assert_eq!(record.current(), 4);
assert_eq!(target, "abcd");
record.go_to(&mut target, 2);
assert_eq!(record.current(), 2);
assert_eq!(target, "ab");
record.go_to(&mut target, 3);
assert_eq!(record.current(), 3);
assert_eq!(target, "abc");
assert!(record.go_to(&mut target, 6).is_empty());
assert_eq!(record.current(), 3);
}
#[test]
fn annul() {
let mut target = String::new();
let mut record = Record::new();
record.apply(&mut target, Edit::Push(Push('a')));
record.apply(&mut target, Edit::Pop(Pop::default()));
record.apply(&mut target, Edit::Push(Push('b')));
assert_eq!(record.len(), 1);
}
#[test]
fn actions() {
let mut target = String::new();
let mut record = Record::new();
record.apply(&mut target, Push('a'));
record.apply(&mut target, Push('b'));
let collected = record.actions().collect::<Vec<_>>();
assert_eq!(&collected[..], &[&Push('a'), &Push('b')][..]);
}
}