Skip to main content

amethystate_core/
change.rs

1use uuid::Uuid;
2
3/// Who made a change the store is telling people about.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Source {
6    /// A handle in this process, by the id its writes carry.
7    Handle(Uuid),
8
9    /// A write through the store's own API, with no handle behind it.
10    Store,
11
12    /// The file was edited outside this process, and the watcher read it.
13    Disk,
14
15    /// Another page of the same site wrote to the browser's storage, and the
16    /// browser announced it here.
17    AnotherPage,
18}
19
20impl Source {
21    /// The handle that made it, for a subscriber telling its own writes from
22    /// everyone else's.
23    pub fn handle(self) -> Option<Uuid> {
24        match self {
25            Source::Handle(id) => Some(id),
26            Source::Store | Source::Disk | Source::AnotherPage => None,
27        }
28    }
29}
30
31impl From<Option<Uuid>> for Source {
32    fn from(handle: Option<Uuid>) -> Self {
33        handle.map_or(Source::Store, Source::Handle)
34    }
35}
36
37#[derive(Debug, Clone, PartialEq)]
38pub struct Change<T> {
39    pub source: Option<Uuid>,
40    pub old_value: T,
41    pub new_value: T,
42}
43
44#[derive(Debug, Clone, PartialEq)]
45pub enum MapChange<K, V> {
46    Insert {
47        key: K,
48        value: V,
49        source: Option<Uuid>,
50    },
51    Update {
52        key: K,
53        /// What was there before. Bytes that will not read as `V` fall back to
54        /// what the map last held, so a key it knows always carries one.
55        old_value: Option<V>,
56        new_value: V,
57        source: Option<Uuid>,
58    },
59    Remove {
60        key: K,
61        old_value: Option<V>,
62        source: Option<Uuid>,
63    },
64    Clear {
65        source: Option<Uuid>,
66    },
67}
68
69impl<K, V> MapChange<K, V> {
70    pub fn key(&self) -> Option<&K> {
71        match self {
72            MapChange::Insert { key, .. } => Some(key),
73            MapChange::Update { key, .. } => Some(key),
74            MapChange::Remove { key, .. } => Some(key),
75            MapChange::Clear { .. } => None,
76        }
77    }
78
79    pub fn source(&self) -> Option<Uuid> {
80        match self {
81            MapChange::Insert { source, .. } => *source,
82            MapChange::Update { source, .. } => *source,
83            MapChange::Remove { source, .. } => *source,
84            MapChange::Clear { source } => *source,
85        }
86    }
87}