floxide_core/merge.rs
1//! Merge trait for user-defined context merging
2
3use std::ops::Deref;
4
5use serde::{Deserialize, Serialize};
6
7/// A trait representing a merge operation (monoid) over values of the same type.
8///
9/// Types implementing `Merge` must also implement `Default`, which serves as the identity element.
10/// The `merge` method combines `other` into `self`, consuming `other`.
11/// Implementations should respect monoid laws:
12/// - left identity: `Default::default().merge(x)` yields `x` (up to equivalence)
13/// - right identity: `x.merge(Default::default())` yields `x` (up to equivalence)
14/// - associativity: `(x.merge(y)).merge(z)` yields the same result as `x.merge(y.merge(z))`.
15pub trait Merge: Default {
16 /// Merge `other` into `self`, consuming `other`.
17 fn merge(&mut self, other: Self);
18}
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct Fixed<T> {
22 value: T,
23}
24
25impl<T> Fixed<T> {
26 pub fn new(value: T) -> Self {
27 Self { value }
28 }
29}
30
31impl<T> Fixed<T> {
32 pub fn get(&self) -> &T {
33 &self.value
34 }
35}
36
37impl<T: Default> Merge for Fixed<T> {
38 fn merge(&mut self, _other: Self) {
39 // No-op
40 }
41}
42
43impl<T: Default> Default for Fixed<T> {
44 fn default() -> Self {
45 Self {
46 value: Default::default(),
47 }
48 }
49}
50
51// Implement getting reference trait for Fixed
52impl<T> Deref for Fixed<T> {
53 type Target = T;
54
55 fn deref(&self) -> &Self::Target {
56 &self.value
57 }
58}