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());