Skip to main content

Patchable

Trait Patchable 

Source
pub trait Patchable {
    type Patch: Clone;

    // Required method
    fn patch(&mut self, patch: Self::Patch);
}
Expand description

A data structure that can be updated using a corresponding patch.

§Usage

use patchable::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` for `Accumulator`, the following `AccumulatorState` and `Patchable`
// implementation for `Accumulator` can be generated automatically.

#[derive(Clone, Deserialize)]
pub struct AccumulatorState<T> {
    prev_control_signal: T,
    accumulated: u32,
}

impl<T> Patchable for Accumulator<T>
where
    T: Clone,
{
    type Patch = AccumulatorState<T>;

    #[inline(always)]
    fn patch(&mut self, state: Self::Patch) {
        self.prev_control_signal = state.prev_control_signal;
        self.accumulated = state.accumulated;
    }
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

let mut accumulator = Accumulator {
    prev_control_signal: -1,
    filter: |x: &i32| *x > 300,
    accumulated: 0,
};

let accumulator_state: AccumulatorState<i32> = serde_json::from_str(
    r#"{
        "prev_control_signal": 6,
        "accumulated": 15
    }"#
).unwrap();

accumulator.patch(accumulator_state);

assert_eq!(accumulator.prev_control_signal, 6i32);
assert_eq!(accumulator.accumulated, 15u32);

Required Associated Types§

Source

type Patch: Clone

The type of patch associated with this structure.

Required Methods§

Source

fn patch(&mut self, patch: Self::Patch)

Applies the given patch to update the structure.

Implementors§