Skip to main content

TryPatch

Trait TryPatch 

Source
pub trait TryPatch: Patchable {
    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 Patch.

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

§Usage

use patchable::{TryPatch, Patchable};
use std::fmt;

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

#[derive(Clone, PartialEq)]
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 Patchable for Config {
    type Patch = ConfigPatch;
}

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

impl TryPatch for Config {
    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 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.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<T: Patch> TryPatch for T

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