Skip to main content

tauri_store/store/
state.rs

1use crate::error::Result;
2use crate::io_err;
3use serde::de::DeserializeOwned;
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use serde_json::{Map, Value};
6use std::result::Result as StdResult;
7
8#[cfg(feature = "preserve-order")]
9type HashMap<K, V> = indexmap::IndexMap<K, V>;
10#[cfg(not(feature = "preserve-order"))]
11type HashMap<K, V> = std::collections::HashMap<K, V>;
12
13/// Internal state of a store.
14#[derive(Clone, Debug, Default)]
15pub struct StoreState(HashMap<String, Value>);
16
17impl StoreState {
18  /// Creates an empty [`StoreState`].
19  pub fn new() -> Self {
20    Self::default()
21  }
22
23  /// Creates an empty [`StoreState`] with at least the specified capacity.
24  pub fn with_capacity(capacity: usize) -> Self {
25    Self(HashMap::with_capacity(capacity))
26  }
27
28  /// Consumes the [`StoreState`] and returns the inner [`HashMap`](std::collections::HashMap).
29  #[inline]
30  pub fn into_inner(self) -> HashMap<String, Value> {
31    self.0
32  }
33
34  /// Gets a reference to the raw value corresponding to the key.
35  pub fn get_raw(&self, key: impl AsRef<str>) -> Option<&Value> {
36    self.0.get(key.as_ref())
37  }
38
39  /// Gets a mutable reference to the raw value corresponding to the key.
40  pub fn get_raw_mut(&mut self, key: impl AsRef<str>) -> Option<&mut Value> {
41    self.0.get_mut(key.as_ref())
42  }
43
44  /// Gets a reference to the raw value corresponding to the key.
45  ///
46  /// # Safety
47  ///
48  /// This is *undefined behavior* if the key doesn't exist in the store.
49  pub unsafe fn get_raw_unchecked(&self, key: impl AsRef<str>) -> &Value {
50    unsafe { self.0.get(key.as_ref()).unwrap_unchecked() }
51  }
52
53  /// Gets a mutable reference to the raw value corresponding to the key.
54  ///
55  /// # Safety
56  ///
57  /// This is *undefined behavior* if the key doesn't exist in the store.
58  pub unsafe fn get_raw_unchecked_mut(&mut self, key: impl AsRef<str>) -> &mut Value {
59    unsafe { self.0.get_mut(key.as_ref()).unwrap_unchecked() }
60  }
61
62  /// Gets a value and tries to parse it as an instance of type `T`.
63  pub fn get<T>(&self, key: impl AsRef<str>) -> Result<T>
64  where
65    T: DeserializeOwned,
66  {
67    let key = key.as_ref();
68    let Some(value) = self.0.get(key).cloned() else {
69      return io_err!(NotFound, "key not found: {key}");
70    };
71
72    Ok(serde_json::from_value(value)?)
73  }
74
75  /// Gets a value and tries to parse it as an instance of type `T`.
76  ///
77  /// If it does not exist, returns the provided default value.
78  pub fn get_or<T>(&self, key: impl AsRef<str>, default: T) -> T
79  where
80    T: DeserializeOwned,
81  {
82    self.get(key).unwrap_or(default)
83  }
84
85  /// Gets a value and tries to parse it as an instance of type `T`.
86  ///
87  /// If it does not exist, returns the default value of `T`.
88  pub fn get_or_default<T>(&self, key: impl AsRef<str>) -> T
89  where
90    T: DeserializeOwned + Default,
91  {
92    self.get(key).unwrap_or_default()
93  }
94
95  /// Gets a value and tries to parse it as an instance of type `T`.
96  ///
97  /// If it does not exist, returns the result of the provided closure.
98  pub fn get_or_else<T>(&self, key: impl AsRef<str>, f: impl FnOnce() -> T) -> T
99  where
100    T: DeserializeOwned,
101  {
102    self.get(key).unwrap_or_else(|_| f())
103  }
104
105  /// Gets a value and parses it as an instance of type `T`.
106  ///
107  /// # Safety
108  ///
109  /// This is *undefined behavior* if the key doesn't exist in the store
110  /// **OR** if the value cannot be represented as a valid `T`.
111  pub unsafe fn get_unchecked<T>(&self, key: impl AsRef<str>) -> T
112  where
113    T: DeserializeOwned,
114  {
115    self.get(key).unwrap_unchecked()
116  }
117
118  /// Sets a key-value pair, returning the previous value, if any.
119  pub fn set(&mut self, key: impl AsRef<str>, value: impl Into<Value>) -> Option<Value> {
120    let key = key.as_ref().to_owned();
121    self.0.insert(key, value.into())
122  }
123
124  /// Patches the state.
125  pub fn patch(&mut self, state: impl Into<StoreState>) {
126    self.0.extend(state.into().0);
127  }
128
129  /// Whether a key exists.
130  pub fn has(&self, key: impl AsRef<str>) -> bool {
131    self.0.contains_key(key.as_ref())
132  }
133
134  /// Creates an iterator over the keys.
135  pub fn keys(&self) -> impl Iterator<Item = &String> {
136    self.0.keys()
137  }
138
139  /// Creates an iterator over the values.
140  pub fn values(&self) -> impl Iterator<Item = &Value> {
141    self.0.values()
142  }
143
144  /// Creates an iterator over mutable references to the values.
145  pub fn values_mut(&mut self) -> impl Iterator<Item = &mut Value> {
146    self.0.values_mut()
147  }
148
149  /// Creates an iterator over the entries.
150  pub fn entries(&self) -> impl Iterator<Item = (&String, &Value)> {
151    self.0.iter()
152  }
153
154  /// Creates an iterator over mutable references to the entries.
155  pub fn entries_mut(&mut self) -> impl Iterator<Item = (&String, &mut Value)> {
156    self.0.iter_mut()
157  }
158
159  /// Removes a key, returning the previous value, if any.
160  pub fn remove(&mut self, key: impl AsRef<str>) -> Option<Value> {
161    #[cfg(feature = "preserve-order")]
162    let value = self.0.shift_remove(key.as_ref());
163    #[cfg(not(feature = "preserve-order"))]
164    let value = self.0.remove(key.as_ref());
165
166    value
167  }
168
169  /// Retains only the values specified by the predicate.
170  pub fn retain<F>(&mut self, f: F)
171  where
172    F: FnMut(&String, &mut Value) -> bool,
173  {
174    self.0.retain(f);
175  }
176
177  /// Clears the store state, removing all key-value pairs.
178  #[inline]
179  pub fn clear(&mut self) {
180    self.0.clear();
181  }
182
183  /// Returns the amount of items.
184  #[inline]
185  pub fn len(&self) -> usize {
186    self.0.len()
187  }
188
189  /// Whether it is empty.
190  #[inline]
191  pub fn is_empty(&self) -> bool {
192    self.0.is_empty()
193  }
194}
195
196impl Serialize for StoreState {
197  fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
198  where
199    S: Serializer,
200  {
201    self.0.serialize(serializer)
202  }
203}
204
205impl<'de> Deserialize<'de> for StoreState {
206  fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
207  where
208    D: Deserializer<'de>,
209  {
210    type Map = HashMap<String, Value>;
211    Ok(Self(Map::deserialize(deserializer)?))
212  }
213}
214
215impl From<HashMap<String, Value>> for StoreState {
216  fn from(map: HashMap<String, Value>) -> Self {
217    Self(map)
218  }
219}
220
221impl<K, V> FromIterator<(K, V)> for StoreState
222where
223  K: Into<String>,
224  V: Into<Value>,
225{
226  fn from_iter<I>(iter: I) -> Self
227  where
228    I: IntoIterator<Item = (K, V)>,
229  {
230    let state = iter
231      .into_iter()
232      .map(|(k, v)| (k.into(), v.into()))
233      .collect();
234
235    Self(state)
236  }
237}
238
239impl<K, V> From<(K, V)> for StoreState
240where
241  K: Into<String>,
242  V: Into<Value>,
243{
244  fn from((key, value): (K, V)) -> Self {
245    Self::from_iter([(key, value)])
246  }
247}
248
249impl<K, V> From<Vec<(K, V)>> for StoreState
250where
251  K: Into<String>,
252  V: Into<Value>,
253{
254  fn from(pairs: Vec<(K, V)>) -> Self {
255    Self::from_iter(pairs)
256  }
257}
258
259impl<const N: usize, K, V> From<[(K, V); N]> for StoreState
260where
261  K: Into<String>,
262  V: Into<Value>,
263{
264  fn from(pairs: [(K, V); N]) -> Self {
265    Self::from_iter(pairs)
266  }
267}
268
269impl From<StoreState> for Value {
270  fn from(state: StoreState) -> Self {
271    Value::from(Map::from_iter(state.0))
272  }
273}
274
275impl From<&StoreState> for Value {
276  fn from(state: &StoreState) -> Self {
277    Value::from(state.clone())
278  }
279}