Skip to main content

cmd_commit/
cmd_commit.rs

1// SPDX-FileCopyrightText: 2025 undoredo contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Example showing how to store metadata ("cmd") along with each edit.
6
7use std::collections::HashMap;
8use undoredo::aliases::{HashMapDelta, HashMapHalfDelta};
9use undoredo::{Recorder, UndoRedo};
10
11/// Representation of the command that originated the recorded delta.
12#[derive(Debug, Clone, PartialEq)]
13enum Command {
14    PushChar,
15}
16
17fn main() {
18    let mut recorder: Recorder<HashMap<usize, char>, HashMapHalfDelta<usize, char>> =
19        Recorder::new(HashMap::new());
20    let mut undoredo: UndoRedo<HashMapDelta<usize, char>, Command> = UndoRedo::new();
21
22    recorder.insert(1, 'A');
23
24    // Commit `Command::PushChar` enum variant as command metadata ("cmd") along
25    // with the recorded delta.
26    undoredo.cmd_commit(Command::PushChar, &mut recorder);
27
28    // `Command::PushChar` is now the top element of the stack of done cmd-deltas.
29    assert_eq!(undoredo.done().last().unwrap().cmd, Command::PushChar);
30
31    undoredo.undo(&mut recorder);
32
33    // After undo, `Command::PushChar` is now the top element of the stack of
34    // undone cmd-deltas.
35    assert_eq!(undoredo.undone().last().unwrap().cmd, Command::PushChar);
36}
37
38#[test]
39fn test() {
40    main();
41}