Skip to main content

Patchable

Trait Patchable 

Source
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;
    }
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

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§

Source

type Patch

The type of patch associated with this structure.

Implementors§