basic_usage/basic_usage.rs
1// SPDX-FileCopyrightText: 2025 undoredo contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use std::collections::HashMap;
6use undoredo::aliases::{HashMapDelta, HashMapHalfDelta};
7use undoredo::{Recorder, UndoRedo};
8
9fn main() {
10 // The recorder records the ongoing changes to the recorded container.
11 //
12 // For some containers such as `HashMap` and `HashSet`, you need
13 // to explicitly pass a half-delta type to the `Recorder` (here
14 // `HashMapHalfDelta`). For most containers, however, you don't need to do
15 // that because their half-delta is already the default, `BTreeMap`.
16 let mut recorder: Recorder<HashMap<usize, char>, HashMapHalfDelta<usize, char>> =
17 Recorder::new(HashMap::new());
18
19 // The undo-redo struct that holds and maintains the undo-redo bistack.
20 let mut undoredo: UndoRedo<HashMapDelta<usize, char>> = UndoRedo::new();
21
22 // Push elements while recording the changes in a delta.
23 recorder.insert(1, 'A');
24 recorder.insert(2, 'B');
25 recorder.insert(3, 'C');
26
27 // The pushed elements are now present in the container.
28 assert!(*recorder.container() == HashMap::from([(1, 'A'), (2, 'B'), (3, 'C')]));
29
30 // Flush the recorder and commit the recorded delta of pushing 'A', 'B', 'C'
31 // into the undo-redo bistack.
32 undoredo.commit(&mut recorder);
33
34 // Now undo the action.
35 undoredo.undo(&mut recorder);
36
37 // The container is now empty; the action of pushing elements has been undone.
38 assert!(*recorder.container() == HashMap::from([]));
39
40 // Now redo the action.
41 undoredo.redo(&mut recorder);
42
43 // The elements are back in the container; the action has been redone.
44 assert!(*recorder.container() == HashMap::from([(1, 'A'), (2, 'B'), (3, 'C')]));
45
46 // Once you are done recording, you can dissolve the recorder to regain
47 // ownership and mutability over the recorded container.
48 let (hashmap, ..) = recorder.dissolve();
49 assert!(hashmap == HashMap::from([(1, 'A'), (2, 'B'), (3, 'C')]));
50}
51
52#[test]
53fn test() {
54 main();
55}