Skip to main content

TryPatch

Trait TryPatch 

Source
pub trait TryPatch {
    type Patch: Clone;
    type Error: Error + Send + Sync + 'static;

    // Required method
    fn try_patch(&mut self, patch: Self::Patch) -> Result<(), Self::Error>;
}
Expand description

A fallible variant of Patchable.

This trait allows applying a patch with validation, returning a custom error if the patch cannot be applied.

§Usage

use patchable::TryPatch;
use std::fmt;

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

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

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

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

impl std::error::Error for PatchError {}

impl TryPatch for Config {
    type Patch = ConfigPatch;
    type Error = PatchError;

    fn try_patch(&mut self, patch: Self::Patch) -> Result<(), Self::Error> {
        if patch.concurrency == 0 {
            return Err(PatchError("Concurrency must be > 0".into()));
        }
        self.concurrency = patch.concurrency;
        Ok(())
    }
}

let mut config = Config { concurrency: 1 };
let valid_patch = ConfigPatch { concurrency: 4 };
config.try_patch(valid_patch).unwrap();
assert_eq!(config.concurrency, 4);

let invalid_patch = ConfigPatch { concurrency: 0 };
assert!(config.try_patch(invalid_patch).is_err());

Required Associated Types§

Source

type Patch: Clone

The type of patch associated with this structure.

Source

type Error: Error + Send + Sync + 'static

The error type returned when applying a patch fails.

Required Methods§

Source

fn try_patch(&mut self, patch: Self::Patch) -> Result<(), Self::Error>

Applies the provided patch to self.

§Errors

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

Implementors§

Source§

impl<T: Patchable> TryPatch for T

Blanket implementation for all Patchable types, where patching is infallible.