Trait redo::RedoCmd [] [src]

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

    fn merge(&mut self, cmd: &Self) -> Option<Result<Self::Err>> { ... }
}

Trait that defines the functionality of a command.

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

Associated Types

The error type.

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 manual merging of two RedoCmds.

Returns Some(Ok) if the merging was successful, Some(Err) if something went wrong when trying to merge, and None if it did not try to merge. This method is always called by the push method in RedoStack, with self being the top command on the stack and cmd being the new command. If None is returned from this method, cmd will be pushed on the stack as normal. However, if the return value is Some(x) it will not push the command on to the stack since either it was merged or an error has occurred, and then the stack returns the x value.

Default implementation returns None.

Examples

use redo::{self, RedoCmd, RedoStack};

#[derive(Debug)]
struct TxtCmd {
    txt: String,
    c: char,
}

impl TxtCmd {
    fn new(c: char) -> Self {
        TxtCmd { c: c, txt: String::new() }
    }
}

impl RedoCmd for TxtCmd {
    type Err = ();

    fn redo(&mut self) -> redo::Result<()> {
        Ok(())
    }

    fn undo(&mut self) -> redo::Result<()> {
        Ok(())
    }

    fn merge(&mut self, cmd: &Self) -> Option<redo::Result<()>> {
        // Merge cmd if not a space.
        if cmd.c != ' ' {
            self.txt.push(cmd.c);
            Some(Ok(()))
        } else {
            None
        }
    }
}

fn foo() -> redo::Result<()> {
    let mut stack = RedoStack::new();
    stack.push(TxtCmd::new('a'))?;
    stack.push(TxtCmd::new('b'))?;
    stack.push(TxtCmd::new('c'))?; // 'a', 'b' and 'c' is merged.
    stack.push(TxtCmd::new(' '))?;
    stack.push(TxtCmd::new('d'))?; // ' ' and 'd' is merged.

    println!("{:#?}", stack);
    Ok(())
}

Output:

RedoStack {
    stack: [
        TxtCmd {
            txt: "bc",
            c: 'a'
        },
        TxtCmd {
            txt: "d",
            c: ' '
        }
    ],
    idx: 2,
    limit: None
}

Implementors