Skip to content

Instantly share code, notes, and snippets.

@PsichiX
Last active November 25, 2024 23:03
Show Gist options
  • Save PsichiX/8e69792d6e207413331d1b3188d8785f to your computer and use it in GitHub Desktop.
Save PsichiX/8e69792d6e207413331d1b3188d8785f to your computer and use it in GitHub Desktop.
Transaction interface for editable data
#[test]
fn test_editable() {
let mut editable = Editable::new(0usize);
assert_eq!(editable.done_count(), 0);
assert_eq!(editable.undone_count(), 0);
editable
.edit_snapshot("set 42", |data| {
*data = 42;
Ok(())
})
.unwrap();
assert_eq!(editable.done_count(), 1);
assert_eq!(editable.undone_count(), 0);
assert_eq!(*editable.data(), 42);
editable.undo_last().unwrap();
assert_eq!(editable.done_count(), 0);
assert_eq!(editable.undone_count(), 1);
assert_eq!(*editable.data(), 0);
editable.redo_last().unwrap();
assert_eq!(editable.done_count(), 1);
assert_eq!(editable.undone_count(), 0);
assert_eq!(*editable.data(), 42);
editable
.edit_snapshot("add 8", |data| {
*data += 8;
Ok(())
})
.unwrap();
assert_eq!(editable.done_count(), 2);
assert_eq!(editable.undone_count(), 0);
assert_eq!(*editable.data(), 50);
editable
.edit_snapshot("div 5", |data| {
*data /= 5;
Ok(())
})
.unwrap();
assert_eq!(editable.done_count(), 3);
assert_eq!(editable.undone_count(), 0);
assert_eq!(*editable.data(), 10);
editable.undo_many(2).unwrap();
assert_eq!(editable.done_count(), 1);
assert_eq!(editable.undone_count(), 2);
assert_eq!(*editable.data(), 42);
editable.redo_all().unwrap();
assert_eq!(editable.done_count(), 3);
assert_eq!(editable.undone_count(), 0);
assert_eq!(*editable.data(), 10);
editable.undo_last().unwrap();
assert_eq!(
editable.history().collect::<Vec<_>>(),
vec![
("set 42", EditHistoryKind::Done, 2),
("add 8", EditHistoryKind::Done, 1),
("div 5", EditHistoryKind::Undone, 1)
]
);
editable
.edit_snapshot("mul 2", |data| {
*data *= 2;
Ok(())
})
.unwrap();
assert_eq!(editable.done_count(), 3);
assert_eq!(editable.undone_count(), 0);
assert_eq!(*editable.data(), 100);
editable.undo_all().unwrap();
editable.clear_undone();
assert_eq!(editable.done_count(), 0);
assert_eq!(editable.undone_count(), 0);
assert_eq!(editable.commit(), 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment