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§
Required Methods§
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.