inc_complete/storage/
hashmapped.rs

1use std::collections::HashMap;
2
3use crate::{Cell, storage::StorageFor};
4use std::hash::Hash;
5
6use super::OutputType;
7
8#[derive(Clone)]
9pub struct HashMapStorage<K: OutputType> {
10    key_to_cell: HashMap<K, Cell>,
11    cell_to_key: HashMap<Cell, (K, Option<K::Output>)>,
12}
13
14impl<K: OutputType> Default for HashMapStorage<K> {
15    fn default() -> Self {
16        Self {
17            key_to_cell: Default::default(),
18            cell_to_key: Default::default(),
19        }
20    }
21}
22
23impl<K> StorageFor<K> for HashMapStorage<K>
24where
25    K: Clone + Eq + Hash + OutputType,
26    K::Output: Eq,
27{
28    fn get_cell_for_computation(&self, key: &K) -> Option<Cell> {
29        self.key_to_cell.get(key).copied()
30    }
31
32    fn insert_new_cell(&mut self, cell: Cell, key: K) {
33        self.key_to_cell.insert(key.clone(), cell);
34        self.cell_to_key.insert(cell, (key, None));
35    }
36
37    fn get_input(&self, cell: Cell) -> &K {
38        &self.cell_to_key[&cell].0
39    }
40
41    fn get_output(&self, cell: Cell) -> Option<&K::Output> {
42        self.cell_to_key[&cell].1.as_ref()
43    }
44
45    fn update_output(&mut self, cell: Cell, new_value: K::Output) -> bool {
46        let previous_output = &mut self.cell_to_key.get_mut(&cell).unwrap().1;
47        let changed = previous_output
48            .as_ref()
49            .is_none_or(|value| *value != new_value);
50        *previous_output = Some(new_value);
51        changed
52    }
53}
54
55impl<K> serde::Serialize for HashMapStorage<K>
56where
57    K: serde::Serialize + OutputType,
58    K::Output: serde::Serialize,
59{
60    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
61    where
62        S: serde::Serializer,
63    {
64        self.cell_to_key.serialize(serializer)
65    }
66}
67
68impl<'de, K> serde::Deserialize<'de> for HashMapStorage<K>
69where
70    K: serde::Deserialize<'de> + Hash + Eq + OutputType + Clone,
71    K::Output: serde::Deserialize<'de>,
72{
73    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
74    where
75        D: serde::Deserializer<'de>,
76    {
77        let cell_to_key: HashMap<Cell, (K, Option<K::Output>)> =
78            serde::Deserialize::deserialize(deserializer)?;
79        let key_to_cell = cell_to_key
80            .iter()
81            .map(|(cell, (key, _))| (key.clone(), *cell))
82            .collect();
83        Ok(HashMapStorage {
84            cell_to_key,
85            key_to_cell,
86        })
87    }
88}