Coverage Report

Created: 2025-09-27 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/phf-0.13.1/src/map.rs
Line
Count
Source
1
//! An immutable map constructed at compile time.
2
use core::fmt;
3
use core::iter::FusedIterator;
4
use core::iter::IntoIterator;
5
use core::ops::Index;
6
use core::slice;
7
use phf_shared::{self, HashKey, PhfBorrow, PhfHash};
8
#[cfg(feature = "serde")]
9
use serde::ser::{Serialize, SerializeMap, Serializer};
10
11
/// An immutable map constructed at compile time.
12
///
13
/// ## Note
14
///
15
/// The fields of this struct are public so that they may be initialized by the
16
/// `phf_map!` macro and code generation. They are subject to change at any
17
/// time and should never be accessed directly.
18
pub struct Map<K: 'static, V: 'static> {
19
    #[doc(hidden)]
20
    pub key: HashKey,
21
    #[doc(hidden)]
22
    pub disps: &'static [(u32, u32)],
23
    #[doc(hidden)]
24
    pub entries: &'static [(K, V)],
25
}
26
27
impl<K, V> fmt::Debug for Map<K, V>
28
where
29
    K: fmt::Debug,
30
    V: fmt::Debug,
31
{
32
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
33
        fmt.debug_map().entries(self.entries()).finish()
34
    }
35
}
36
37
impl<'a, K, V, T: ?Sized> Index<&'a T> for Map<K, V>
38
where
39
    T: Eq + PhfHash,
40
    K: PhfBorrow<T>,
41
{
42
    type Output = V;
43
44
    fn index(&self, k: &'a T) -> &V {
45
        self.get(k).expect("invalid key")
46
    }
47
}
48
49
impl<K, V> Default for Map<K, V> {
50
    fn default() -> Self {
51
        Self::new()
52
    }
53
}
54
55
impl<K, V> PartialEq for Map<K, V>
56
where
57
    K: PartialEq,
58
    V: PartialEq,
59
{
60
    fn eq(&self, other: &Self) -> bool {
61
        self.key == other.key && self.disps == other.disps && self.entries == other.entries
62
    }
63
}
64
65
impl<K, V> Eq for Map<K, V>
66
where
67
    K: Eq,
68
    V: Eq,
69
{
70
}
71
72
impl<K, V> Map<K, V> {
73
    /// Create a new, empty, immutable map.
74
    #[inline]
75
    pub const fn new() -> Self {
76
        Self {
77
            key: 0,
78
            disps: &[],
79
            entries: &[],
80
        }
81
    }
82
83
    /// Returns the number of entries in the `Map`.
84
    #[inline]
85
    pub const fn len(&self) -> usize {
86
        self.entries.len()
87
    }
88
89
    /// Returns true if the `Map` is empty.
90
    #[inline]
91
    pub const fn is_empty(&self) -> bool {
92
        self.len() == 0
93
    }
94
95
    /// Determines if `key` is in the `Map`.
96
    pub fn contains_key<T>(&self, key: &T) -> bool
97
    where
98
        T: Eq + PhfHash + ?Sized,
99
        K: PhfBorrow<T>,
100
    {
101
        self.get(key).is_some()
102
    }
103
104
    /// Returns a reference to the value that `key` maps to.
105
410k
    pub fn get<T>(&self, key: &T) -> Option<&V>
106
410k
    where
107
410k
        T: Eq + PhfHash + ?Sized,
108
410k
        K: PhfBorrow<T>,
109
    {
110
410k
        self.get_entry(key).map(|e| e.1)
111
410k
    }
Unexecuted instantiation: <phf::map::Map<&str, (u8, u8, u8)>>::get::<str>
<phf::map::Map<&str, (u32, u32)>>::get::<str>
Line
Count
Source
105
410k
    pub fn get<T>(&self, key: &T) -> Option<&V>
106
410k
    where
107
410k
        T: Eq + PhfHash + ?Sized,
108
410k
        K: PhfBorrow<T>,
109
    {
110
410k
        self.get_entry(key).map(|e| e.1)
111
410k
    }
112
113
    /// Returns a reference to the map's internal static instance of the given
114
    /// key.
115
    ///
116
    /// This can be useful for interning schemes.
117
    pub fn get_key<T>(&self, key: &T) -> Option<&K>
118
    where
119
        T: Eq + PhfHash + ?Sized,
120
        K: PhfBorrow<T>,
121
    {
122
        self.get_entry(key).map(|e| e.0)
123
    }
124
125
    /// Like `get`, but returns both the key and the value.
126
410k
    pub fn get_entry<T>(&self, key: &T) -> Option<(&K, &V)>
127
410k
    where
128
410k
        T: Eq + PhfHash + ?Sized,
129
410k
        K: PhfBorrow<T>,
130
    {
131
410k
        if self.disps.is_empty() {
132
0
            return None;
133
410k
        } //Prevent panic on empty map
134
410k
        let hashes = phf_shared::hash(key, &self.key);
135
410k
        let index = phf_shared::get_index(&hashes, self.disps, self.entries.len());
136
410k
        let entry = &self.entries[index as usize];
137
410k
        let b: &T = entry.0.borrow();
138
410k
        if b == key {
139
267k
            Some((&entry.0, &entry.1))
140
        } else {
141
143k
            None
142
        }
143
410k
    }
Unexecuted instantiation: <phf::map::Map<&str, (u8, u8, u8)>>::get_entry::<str>
<phf::map::Map<&str, (u32, u32)>>::get_entry::<str>
Line
Count
Source
126
410k
    pub fn get_entry<T>(&self, key: &T) -> Option<(&K, &V)>
127
410k
    where
128
410k
        T: Eq + PhfHash + ?Sized,
129
410k
        K: PhfBorrow<T>,
130
    {
131
410k
        if self.disps.is_empty() {
132
0
            return None;
133
410k
        } //Prevent panic on empty map
134
410k
        let hashes = phf_shared::hash(key, &self.key);
135
410k
        let index = phf_shared::get_index(&hashes, self.disps, self.entries.len());
136
410k
        let entry = &self.entries[index as usize];
137
410k
        let b: &T = entry.0.borrow();
138
410k
        if b == key {
139
267k
            Some((&entry.0, &entry.1))
140
        } else {
141
143k
            None
142
        }
143
410k
    }
144
145
    /// Returns an iterator over the key/value pairs in the map.
146
    ///
147
    /// Entries are returned in an arbitrary but fixed order.
148
0
    pub fn entries(&self) -> Entries<'_, K, V> {
149
0
        Entries {
150
0
            iter: self.entries.iter(),
151
0
        }
152
0
    }
153
154
    /// Returns an iterator over the keys in the map.
155
    ///
156
    /// Keys are returned in an arbitrary but fixed order.
157
    pub fn keys(&self) -> Keys<'_, K, V> {
158
        Keys {
159
            iter: self.entries(),
160
        }
161
    }
162
163
    /// Returns an iterator over the values in the map.
164
    ///
165
    /// Values are returned in an arbitrary but fixed order.
166
    pub fn values(&self) -> Values<'_, K, V> {
167
        Values {
168
            iter: self.entries(),
169
        }
170
    }
171
}
172
173
impl<'a, K, V> IntoIterator for &'a Map<K, V> {
174
    type Item = (&'a K, &'a V);
175
    type IntoIter = Entries<'a, K, V>;
176
177
    fn into_iter(self) -> Entries<'a, K, V> {
178
        self.entries()
179
    }
180
}
181
182
/// An iterator over the key/value pairs in a `Map`.
183
pub struct Entries<'a, K, V> {
184
    iter: slice::Iter<'a, (K, V)>,
185
}
186
187
impl<'a, K, V> Clone for Entries<'a, K, V> {
188
    #[inline]
189
    fn clone(&self) -> Self {
190
        Self {
191
            iter: self.iter.clone(),
192
        }
193
    }
194
}
195
196
impl<'a, K, V> fmt::Debug for Entries<'a, K, V>
197
where
198
    K: fmt::Debug,
199
    V: fmt::Debug,
200
{
201
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
202
        f.debug_list().entries(self.clone()).finish()
203
    }
204
}
205
206
impl<'a, K, V> Iterator for Entries<'a, K, V> {
207
    type Item = (&'a K, &'a V);
208
209
    fn next(&mut self) -> Option<(&'a K, &'a V)> {
210
        self.iter.next().map(|(k, v)| (k, v))
211
    }
212
213
    fn size_hint(&self) -> (usize, Option<usize>) {
214
        self.iter.size_hint()
215
    }
216
}
217
218
impl<'a, K, V> DoubleEndedIterator for Entries<'a, K, V> {
219
    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
220
        self.iter.next_back().map(|e| (&e.0, &e.1))
221
    }
222
}
223
224
impl<'a, K, V> ExactSizeIterator for Entries<'a, K, V> {}
225
226
impl<'a, K, V> FusedIterator for Entries<'a, K, V> {}
227
228
/// An iterator over the keys in a `Map`.
229
pub struct Keys<'a, K, V> {
230
    iter: Entries<'a, K, V>,
231
}
232
233
impl<'a, K, V> Clone for Keys<'a, K, V> {
234
    #[inline]
235
    fn clone(&self) -> Self {
236
        Self {
237
            iter: self.iter.clone(),
238
        }
239
    }
240
}
241
242
impl<'a, K, V> fmt::Debug for Keys<'a, K, V>
243
where
244
    K: fmt::Debug,
245
{
246
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
247
        f.debug_list().entries(self.clone()).finish()
248
    }
249
}
250
251
impl<'a, K, V> Iterator for Keys<'a, K, V> {
252
    type Item = &'a K;
253
254
    fn next(&mut self) -> Option<&'a K> {
255
        self.iter.next().map(|e| e.0)
256
    }
257
258
    fn size_hint(&self) -> (usize, Option<usize>) {
259
        self.iter.size_hint()
260
    }
261
}
262
263
impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
264
    fn next_back(&mut self) -> Option<&'a K> {
265
        self.iter.next_back().map(|e| e.0)
266
    }
267
}
268
269
impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {}
270
271
impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
272
273
/// An iterator over the values in a `Map`.
274
pub struct Values<'a, K, V> {
275
    iter: Entries<'a, K, V>,
276
}
277
278
impl<'a, K, V> Clone for Values<'a, K, V> {
279
    #[inline]
280
    fn clone(&self) -> Self {
281
        Self {
282
            iter: self.iter.clone(),
283
        }
284
    }
285
}
286
287
impl<'a, K, V> fmt::Debug for Values<'a, K, V>
288
where
289
    V: fmt::Debug,
290
{
291
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
292
        f.debug_list().entries(self.clone()).finish()
293
    }
294
}
295
296
impl<'a, K, V> Iterator for Values<'a, K, V> {
297
    type Item = &'a V;
298
299
    fn next(&mut self) -> Option<&'a V> {
300
        self.iter.next().map(|e| e.1)
301
    }
302
303
    fn size_hint(&self) -> (usize, Option<usize>) {
304
        self.iter.size_hint()
305
    }
306
}
307
308
impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
309
    fn next_back(&mut self) -> Option<&'a V> {
310
        self.iter.next_back().map(|e| e.1)
311
    }
312
}
313
314
impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {}
315
316
impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
317
318
#[cfg(feature = "serde")]
319
impl<K, V> Serialize for Map<K, V>
320
where
321
    K: Serialize,
322
    V: Serialize,
323
{
324
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
325
    where
326
        S: Serializer,
327
    {
328
        let mut map = serializer.serialize_map(Some(self.len()))?;
329
        for (k, v) in self.entries() {
330
            map.serialize_entry(k, v)?;
331
        }
332
        map.end()
333
    }
334
}