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