Trait redo::Command[][src]

pub trait Command<R> {
    type Error;
    fn apply(&mut self, receiver: &mut R) -> Result<(), Self::Error>;
fn undo(&mut self, receiver: &mut R) -> Result<(), Self::Error>; fn redo(&mut self, receiver: &mut R) -> Result<(), Self::Error> { ... }
fn merge(&mut self, cmd: Self) -> Result<(), Self>
    where
        Self: Sized
, { ... } }

Base functionality for all commands.

Associated Types

The error type.

Required Methods

Applies the command on the receiver and returns Ok if everything went fine, and Err if something went wrong.

Restores the state of the receiver as it was before the command was applied and returns Ok if everything went fine, and Err if something went wrong.

Provided Methods

Reapplies the command on the receiver and return Ok if everything went fine, and Err if something went wrong.

The default implementation uses the apply implementation.

Used for manual merging of two commands.

Returns Ok if commands was merged and Err if not.

Examples

#[derive(Debug)]
struct Add(String);

impl Command<String> for Add {
    type Error = ();

    fn apply(&mut self, s: &mut String) -> Result<(), ()> {
        s.push_str(&self.0);
        Ok(())
    }

    fn undo(&mut self, s: &mut String) -> Result<(), ()> {
        let len = s.len() - self.0.len();
        s.truncate(len);
        Ok(())
    }

    fn merge(&mut self, Add(s): Self) -> Result<(), Self> {
        self.0.push_str(&s);
        Ok(())
    }
}

fn main() -> Result<(), Error<String, Add>> {
    let mut record = Record::default();

    // The `a`, `b`, and `c` commands are merged.
    record.apply(Add("a".into()))?;
    record.apply(Add("b".into()))?;
    record.apply(Add("c".into()))?;
    assert_eq!(record.as_receiver(), "abc");

    // Calling `undo` once will undo all the merged commands.
    record.undo().unwrap()?;
    assert_eq!(record.as_receiver(), "");

    // Calling `redo` once will redo all the merged commands.
    record.redo().unwrap()?;
    assert_eq!(record.as_receiver(), "abc");

    Ok(())
}

Implementors