batbox_diff/
lib.rs

1//! Diffing structs
2#![warn(missing_docs)]
3
4use serde::{de::DeserializeOwned, Serialize};
5use std::fmt::Debug;
6
7pub use batbox_diff_derive::*;
8
9/// A diffable type
10///
11/// [Can be derived](::batbox_derive::Diff)
12///
13/// For [Copy] types implementation just uses the type itself as delta.
14///
15/// Most of the trait bounds should not be here, but are because of
16/// <https://github.com/rust-lang/rust/issues/20671>
17pub trait Diff:
18    Debug + Serialize + DeserializeOwned + Sync + Send + Clone + PartialEq + 'static + Unpin
19{
20    /// Object representing the difference between two states of Self
21    type Delta: Debug + Serialize + DeserializeOwned + Sync + Send + Clone + 'static + Unpin;
22
23    /// Calculate the difference between two states
24    fn diff(&self, to: &Self) -> Self::Delta;
25
26    /// Update the state using the delta
27    ///
28    /// ```
29    /// # use batbox_diff::*;
30    /// let a = 0_i32;
31    /// let b = 1_i32;
32    /// let delta = Diff::diff(&a, &b);
33    ///
34    /// let mut a = a;
35    /// a.update(&delta);
36    /// assert_eq!(a, b);
37    /// ```
38    fn update(&mut self, delta: &Self::Delta);
39}
40
41impl<
42        T: Debug + Serialize + DeserializeOwned + Sync + Send + Copy + PartialEq + 'static + Unpin,
43    > Diff for T
44{
45    type Delta = Self;
46    fn diff(&self, to: &Self) -> Self {
47        *to
48    }
49    fn update(&mut self, new_value: &Self) {
50        *self = *new_value;
51    }
52}