pub trait Patchable {
type Patch;
}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` if needed by enabling "cloneable" feature or manually.
// "cloneable" is enabled by default.
#[derive(PartialEq, Deserialize)]
pub struct AccumulatorPatch<T> {
prev_control_signal: T,
accumulated: u32,
}
impl<T> Patchable for Accumulator<T> {
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> {
#[inline(always)]
fn patch(&mut self, patch: Self::Patch) {
self.prev_control_signal = patch.prev_control_signal;
self.accumulated = patch.accumulated;
}
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
fn main() {
let accumulator = Accumulator {
prev_control_signal: 6,
filter: |x: &i32| *x > 300,
accumulated: 15,
};
let state_bytes = postcard::to_vec::<_, 128>(&accumulator).unwrap();
let accumulator_patch: AccumulatorPatch<i32> = postcard::from_bytes(&state_bytes).unwrap();
let mut recovered_accumulator = Accumulator {
prev_control_signal: -1,
accumulated: 0,
..accumulator
};
recovered_accumulator.patch(accumulator_patch);
assert_eq!(recovered_accumulator.prev_control_signal, accumulator.prev_control_signal);
assert_eq!(recovered_accumulator.accumulated, accumulator.accumulated);
}Declares the associated patch type.