Trait undo::UndoCmd [] [src]

pub trait UndoCmd {
    type Err;
    fn redo(&mut self) -> Result<Self::Err>;
    fn undo(&mut self) -> Result<Self::Err>;

    fn id(&self) -> Option<u64> { ... }
}

Trait that defines the functionality of a command.

Every command needs to implement this trait to be able to be used with the UndoStack.

Associated Types

The error type.

This needs to be the same for all UndoCmds that is going to be used in the same stack or group.

Required Methods

Executes the desired command and returns Ok if everything went fine, and Err if something went wrong.

Restores the state as it was before redo was called and returns Ok if everything went fine, and Err if something went wrong.

Provided Methods

Used for merging of UndoCmds.

Two commands are merged together when a command is pushed on the UndoStack, and it has the same id as the top command already on the stack. When commands are merged together, undoing and redoing them are done in one step. An example where this is useful is a text editor where you might want to undo a whole word instead of each character.

Default implementation returns None, which means the command will never be merged.

Examples

use undo::{self, UndoCmd, UndoStack};

#[derive(Clone, Copy)]
struct PopCmd {
    vec: *mut Vec<i32>,
    e: Option<i32>,
}

impl UndoCmd for PopCmd {
    type Err = ();

    fn redo(&mut self) -> undo::Result<()> {
        self.e = unsafe {
            let ref mut vec = *self.vec;
            vec.pop()
        };
        Ok(())
    }

    fn undo(&mut self) -> undo::Result<()> {
        unsafe {
            let ref mut vec = *self.vec;
            let e = self.e.ok_or(())?;
            vec.push(e);
        }
        Ok(())
    }

    fn id(&self) -> Option<u64> {
        Some(1)
    }
}

fn foo() -> undo::Result<()> {
    let mut vec = vec![1, 2, 3];
    let mut stack = UndoStack::new();
    let cmd = PopCmd { vec: &mut vec, e: None };

    stack.push(cmd)?;
    stack.push(cmd)?;
    stack.push(cmd)?;

    assert!(vec.is_empty());
    stack.undo()?;
    assert_eq!(vec.len(), 3);
    stack.redo()?;
    assert!(vec.is_empty());
    Ok(())
}

Trait Implementations

impl<'a, E> Debug for UndoCmd<Err=E> + 'a
[src]

Formats the value using the given formatter.

Implementors