1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use std::hash::Hash;

use fxhash::FxHashMap;
use serde::{ser::SerializeStruct, Serialize};

use crate::{
    change::Lamport,
    id::{Counter, PeerID, ID},
    span::{HasId, HasLamport},
    InternalString, LoroValue,
};

#[derive(Default, Debug, Clone, Serialize)]
pub struct MapDelta {
    pub updated: FxHashMap<InternalString, MapValue>,
}

impl MapDelta {
    pub(crate) fn compose(&self, x: MapDelta) -> MapDelta {
        let mut updated = self.updated.clone();
        for (k, v) in x.updated.into_iter() {
            if let Some(old) = updated.get_mut(&k) {
                if v.lamport > old.lamport {
                    *old = v;
                }
            } else {
                updated.insert(k, v);
            }
        }
        MapDelta { updated }
    }

    #[inline]
    pub fn new() -> Self {
        MapDelta {
            updated: FxHashMap::default(),
        }
    }

    #[inline]
    pub fn with_entry(mut self, key: InternalString, map_value: MapValue) -> Self {
        self.updated.insert(key, map_value);
        self
    }
}

#[derive(Debug, Clone)]
pub struct MapValue {
    pub counter: Counter,
    pub value: Option<LoroValue>,
    pub lamport: (Lamport, PeerID),
}

impl Hash for MapValue {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // value is not being hashed
        self.counter.hash(state);
        self.lamport.hash(state);
    }
}

impl HasId for MapValue {
    fn id_start(&self) -> crate::id::ID {
        ID::new(self.lamport.1, self.counter)
    }
}

impl HasLamport for MapValue {
    fn lamport(&self) -> Lamport {
        self.lamport.0
    }
}

impl PartialEq for MapValue {
    fn eq(&self, other: &Self) -> bool {
        self.lamport == other.lamport
    }
}

impl Eq for MapValue {}

impl PartialOrd for MapValue {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for MapValue {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.lamport.cmp(&other.lamport)
    }
}

impl Serialize for MapValue {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut s = serializer.serialize_struct("MapValue", 2)?;
        s.serialize_field("value", &self.value)?;
        s.serialize_field("lamport", &self.lamport)?;
        s.end()
    }
}

impl MapValue {
    pub fn new(id: ID, lamport: Lamport, value: Option<LoroValue>) -> Self {
        MapValue {
            counter: id.counter,
            value,
            lamport: (lamport, id.peer),
        }
    }
}