inc_complete/storage/
singleton.rs

1use serde::{Deserialize, ser::SerializeStruct};
2
3use super::{Computation, StorageFor};
4use crate::Cell;
5
6/// Helper to store a simple computation type which has no fields and thus
7/// does not require a map to cache each possible value.
8///
9/// Examples include `struct SourceFile;` or `struct Time;`
10pub struct SingletonStorage<K: Computation> {
11    cell: std::sync::OnceLock<Cell>,
12    key: std::sync::OnceLock<K>,
13    value: std::sync::Mutex<Option<K::Output>>,
14}
15
16impl<K: Computation> Default for SingletonStorage<K> {
17    fn default() -> Self {
18        Self {
19            cell: Default::default(),
20            value: Default::default(),
21            key: Default::default(),
22        }
23    }
24}
25
26impl<K> StorageFor<K> for SingletonStorage<K>
27where
28    K: Computation + Clone,
29    K::Output: Eq + Clone,
30{
31    fn get_cell_for_computation(&self, _: &K) -> Option<Cell> {
32        self.cell.get().copied()
33    }
34
35    fn insert_new_cell(&self, cell: Cell, key: K) {
36        assert!(
37            self.cell.set(cell).is_ok(),
38            "Overwriting previous singleton value - are you using SingleStorage<{}> with a non-singleton type?",
39            std::any::type_name::<K>()
40        );
41        self.key
42            .set(key)
43            .unwrap_or_else(|_| panic!("insert_new_cell: cell already initialized"));
44    }
45
46    fn try_get_input(&self, _: Cell) -> Option<K> {
47        self.key.get().cloned()
48    }
49
50    fn get_output(&self, _: Cell) -> Option<K::Output> {
51        self.value.lock().unwrap().clone()
52    }
53
54    fn update_output(&self, _: Cell, new_value: K::Output) -> bool {
55        let mut guard = self.value.lock().unwrap();
56        let changed = K::ASSUME_CHANGED || guard.as_ref().is_none_or(|value| *value != new_value);
57        *guard = Some(new_value);
58        changed
59    }
60
61    fn gc(&mut self, used_cells: &std::collections::HashSet<Cell>) {
62        if let Some(this_cell) = self.cell.get() {
63            if !used_cells.contains(this_cell) {
64                if let Ok(val) = self.value.get_mut() {
65                    *val = None;
66                }
67            }
68        }
69    }
70}
71
72impl<K> serde::Serialize for SingletonStorage<K>
73where
74    K: serde::Serialize + Computation,
75    K::Output: serde::Serialize,
76{
77    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
78    where
79        S: serde::Serializer,
80    {
81        let mut s = serializer.serialize_struct("SingletonStorage", 3)?;
82        if let Some(cell) = self.cell.get() {
83            s.serialize_field("cell", cell)?;
84        }
85        if let Some(key) = self.key.get() {
86            s.serialize_field("key", key)?;
87        }
88        if let Ok(lock) = self.value.lock() {
89            if let Some(value) = &*lock {
90                s.serialize_field("value", value)?;
91            }
92        }
93        s.end()
94    }
95}
96
97impl<'de, K> serde::Deserialize<'de> for SingletonStorage<K>
98where
99    K: serde::Deserialize<'de> + Computation,
100    K::Output: serde::Deserialize<'de>,
101{
102    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
103    where
104        D: serde::Deserializer<'de>,
105    {
106        let wrapper: SerializeWrapper<K> = Deserialize::deserialize(deserializer)?;
107        Ok(wrapper.into_storage())
108    }
109}
110
111#[derive(Deserialize)]
112struct SerializeWrapper<K: Computation> {
113    #[serde(default)]
114    cell: Option<Cell>,
115
116    // Serde complains we need a `K: Default` without this, but that shouldn't be necessary.
117    #[serde(default = "none")]
118    key: Option<K>,
119
120    #[serde(default)]
121    #[serde(bound = "K::Output: Deserialize<'de>")]
122    value: Option<K::Output>,
123}
124
125fn none<T>() -> Option<T> {
126    None
127}
128
129impl<K: Computation> SerializeWrapper<K> {
130    fn into_storage(self) -> SingletonStorage<K> {
131        let cell = match self.cell {
132            Some(cell) => std::sync::OnceLock::from(cell),
133            None => std::sync::OnceLock::new(),
134        };
135        let key = match self.key {
136            Some(key) => std::sync::OnceLock::from(key),
137            None => std::sync::OnceLock::new(),
138        };
139        let value = std::sync::Mutex::new(self.value);
140        SingletonStorage { cell, key, value }
141    }
142}