Skip to main content

TryRecall

Trait TryRecall 

Source
pub trait TryRecall: Recallable {
    type Error: Error + Send + Sync + 'static;

    // Required method
    fn try_recall(&mut self, memento: Self::Memento) -> Result<(), Self::Error>;
}
Expand description

A fallible variant of Recall.

This trait lets you apply a memento with validation and return a custom error if it cannot be applied.

§Usage

use recallable::{TryRecall, Recallable};
use core::fmt;

#[derive(Debug)]
struct Config {
    concurrency: u32,
}

#[derive(Clone, PartialEq)]
struct ConfigMemento {
    concurrency: u32,
}

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

impl fmt::Display for RecallError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl core::error::Error for RecallError {}

impl Recallable for Config {
    type Memento = ConfigMemento;
}

impl From<Config> for ConfigMemento {
    fn from(c: Config) -> Self {
        Self { concurrency: c.concurrency }
    }
}

impl TryRecall for Config {
    type Error = RecallError;

    fn try_recall(&mut self, memento: Self::Memento) -> Result<(), Self::Error> {
        if memento.concurrency == 0 {
            return Err(RecallError("Concurrency must be > 0".into()));
        }
        self.concurrency = memento.concurrency;
        Ok(())
    }
}

fn main() {
    let mut config = Config { concurrency: 1 };
    let valid_memento = ConfigMemento { concurrency: 4 };
    config.try_recall(valid_memento).unwrap();
    assert_eq!(config.concurrency, 4);

    let invalid_memento = ConfigMemento { concurrency: 0 };
    assert!(config.try_recall(invalid_memento).is_err());
}

Required Associated Types§

Source

type Error: Error + Send + Sync + 'static

The error type returned when applying a memento fails.

Required Methods§

Source

fn try_recall(&mut self, memento: Self::Memento) -> Result<(), Self::Error>

Applies the provided recall to self.

§Errors

Returns an error if the memento is invalid or cannot be applied.

Implementors§

Source§

impl<T: Recall> TryRecall for T

Blanket implementation for all Recall types, where recalling is infallible.