euv_cli/hmr/impl.rs
1use super::*;
2
3/// Inherent implementation of [`HmrState`].
4impl HmrState {
5 /// Creates a new empty `HmrState`.
6 pub fn new() -> Self {
7 Self::default()
8 }
9
10 /// Creates an `HmrState` from an iterator of
11 /// `(key, value)` pairs. Later pairs overwrite
12 /// earlier ones for the same key.
13 ///
14 /// # Arguments
15 ///
16 /// - `I: IntoIterator<Item = (String, String)>` - A generic type parameter.
17 pub fn from_entries<I>(entries: I) -> Self
18 where
19 I: IntoIterator<Item = (String, String)>,
20 {
21 let mut state: Self = Self::new();
22 for (key, value) in entries {
23 state.entries.insert(key, value);
24 }
25 state
26 }
27
28 /// Sets a key-value pair. Overwrites any existing
29 /// value for the key.
30 ///
31 /// # Arguments
32 ///
33 /// - `K: Into<String>` - A generic type parameter.
34 /// - `V: Into<String>` - A generic type parameter.
35 pub fn set<K, V>(&mut self, key: K, value: V)
36 where
37 K: Into<String>,
38 V: Into<String>,
39 {
40 self.entries.insert(key.into(), value.into());
41 }
42
43 /// Returns the value for the given key, or `None`.
44 ///
45 /// # Arguments
46 ///
47 /// - `&str` - Shared reference to a `str`.
48 ///
49 /// # Returns
50 ///
51 /// - `Option<str>` - The current value (or a snapshot thereof).
52 pub fn get(&self, key: &str) -> Option<&str> {
53 self.entries.get(key).map(|s: &String| s.as_str())
54 }
55
56 /// Removes the entry for the given key, returning
57 /// the previous value if any.
58 ///
59 /// # Arguments
60 ///
61 /// - `&str` - Shared reference to a `str`.
62 ///
63 /// # Returns
64 ///
65 /// - `Option<String>` - `Some(...)` on success, `None` otherwise.
66 pub fn remove(&mut self, key: &str) -> Option<String> {
67 self.entries.remove(key)
68 }
69
70 /// Removes every entry.
71 pub fn clear(&mut self) {
72 self.entries.clear();
73 }
74
75 /// Returns the number of entries.
76 ///
77 /// # Returns
78 ///
79 /// - `usize` - The number of items in the collection.
80 pub fn len(&self) -> usize {
81 self.entries.len()
82 }
83
84 /// Returns `true` if the state is empty.
85 ///
86 /// # Returns
87 ///
88 /// - `bool` - `true` when the collection is empty.
89 pub fn is_empty(&self) -> bool {
90 self.entries.is_empty()
91 }
92
93 /// Returns `true` if the state contains the given
94 /// key.
95 ///
96 /// # Arguments
97 ///
98 /// - `&str` - Shared reference to a `str`.
99 ///
100 /// # Returns
101 ///
102 /// - `bool` - A boolean.
103 pub fn contains(&self, key: &str) -> bool {
104 self.entries.contains_key(key)
105 }
106
107 /// Returns an iterator over the entries.
108 ///
109 /// # Returns
110 ///
111 /// - `impl Iterator<Item` - A `impl Iterator<Item` value.
112 pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
113 self.entries
114 .iter()
115 .map(|(k, v): (&String, &String)| (k.as_str(), v.as_str()))
116 }
117}