pub struct UndoStack<T> { /* private fields */ }
Expand description
A structure which allows you to undo and redo changes based on saved states of T
.
To use, simply save
, undo
, and
redo
later if needed;
// Create with initial state
let mut undo = UndoStack::new(5u8);
// make a savepoint and get a reference to the new current value
// our stack looks like [5, 5] currently, our current value being the second
let newref = undo.save();
// we modified the new current value, our stack looks like [5, 10] now
*newref *= 2;
// but we made a mistake! we want to go back now, and since we are
// sure we saved earlier we can unwrap here to get the Ok variant
// our stack still looks like [5, 10], but now we point to the 5
let oldref = undo.undo().unwrap();
// turns out it wasnt a mistake, lets redo and unwrap to be sure we got the newer value
undo.redo().unwrap();
// UndoStack implements Deref and DerefMut, we can make sure we got the new value like this
assert_eq!(undo, 10);
This is useful when you want to be able to make changes in a way where you can undo a change, and then reapply it later, but do not wish to write a complex incremental structure that could track changes like that. This type provides a generic (read: you can use it on anything) interface to achieve that effect, even if it may use more memory than a more targeted approach.
UndoStack
is also “transparently T”, meaning the default traits it implements all act like
the current value of T, so hashing UndoStack<T>
and T produce the same hash, Eq and Ord work
the same etc. This also includes Display
, but does not include Debug
.
Implementations§
Source§impl<T> UndoStack<T>
impl<T> UndoStack<T>
Sourcepub fn new(start: T) -> Self
pub fn new(start: T) -> Self
Creates a new UndoStack
with a starting value to act as the current value
Sourcepub fn push(&mut self, new_current: T) -> &mut T
pub fn push(&mut self, new_current: T) -> &mut T
Pushes the given value to the stack, making it the new current value and invalidating future history, returns a reference to the new current value
This is functionally identical to save
but does not have a Clone
bound, instead sourcing its new value from the caller.
§Panics
This will panic if allocation failed
Sourcepub fn undo(&mut self) -> Result<&mut T, &mut T>
pub fn undo(&mut self) -> Result<&mut T, &mut T>
If there is a previous state in the history stack, backtrack to that and return Ok(&mut T)
to the new current value, otherwise return Err(&mut T)
to the unchanged current value.
Sourcepub fn redo(&mut self) -> Result<&mut T, &mut T>
pub fn redo(&mut self) -> Result<&mut T, &mut T>
If there is a future state in the history stack that has been undone from, redo to that
position and return Ok(&mut T)
of the new current value after advancing, else return
Err(&mut T)
of the current unchanged value, if there was no future history.