pub trait Patchable: Sized {
type Patch: Clone;
}Expand description
A type that declares a companion patch type.
§Usage
use patchable::{Patch, Patchable};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize)]
pub struct Accumulator<T> {
prev_control_signal: T,
#[serde(skip)]
filter: fn(&i32) -> bool,
accumulated: u32,
}
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// If we derive `Patchable` and `Patch` for `Accumulator`, the following `AccumulatorPatch` type
// and the `Patchable`/`Patch` implementations can be generated automatically.
//
// When deriving `Patchable`, a `From<Accumulator>` implementation is generated if the
// `impl_from` feature is enabled. For derived implementations, mark non-state fields with
// `#[patchable(skip)]` (and add `#[serde(skip)]` as needed when using serde).
#[derive(Clone, PartialEq, Deserialize)]
pub struct AccumulatorPatch<T> {
prev_control_signal: T,
accumulated: u32,
}
impl<T> Patchable for Accumulator<T>
where
T: Clone,
{
type Patch = AccumulatorPatch<T>;
}
impl<T> From<Accumulator<T>> for AccumulatorPatch<T> {
fn from(acc: Accumulator<T>) -> Self {
Self {
prev_control_signal: acc.prev_control_signal,
accumulated: acc.accumulated,
}
}
}
impl<T> Patch for Accumulator<T>
where
T: Clone,
{
#[inline(always)]
fn patch(&mut self, patch: Self::Patch) {
self.prev_control_signal = patch.prev_control_signal;
self.accumulated = patch.accumulated;
}
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
let mut accumulator = Accumulator {
prev_control_signal: -1,
filter: |x: &i32| *x > 300,
accumulated: 0,
};
let accumulator_patch: AccumulatorPatch<i32> = serde_json::from_str(
r#"{
"prev_control_signal": 6,
"accumulated": 15
}"#
).unwrap();
accumulator.patch(accumulator_patch);
assert_eq!(accumulator.prev_control_signal, 6i32);
assert_eq!(accumulator.accumulated, 15u32);Declares the associated patch type.
Required Associated Types§
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.