phf/
map.rs

1//! An immutable map constructed at compile time.
2use core::fmt;
3use core::iter::FusedIterator;
4use core::iter::IntoIterator;
5use core::ops::Index;
6use core::slice;
7use phf_shared::{self, HashKey, PhfBorrow, PhfHash};
8#[cfg(feature = "serde")]
9use 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.
18pub 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
27impl<K, V> fmt::Debug for Map<K, V>
28where
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
37impl<'a, K, V, T: ?Sized> Index<&'a T> for Map<K, V>
38where
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
49impl<K, V> Default for Map<K, V> {
50    fn default() -> Self {
51        Self::new()
52    }
53}
54
55impl<K, V> PartialEq for Map<K, V>
56where
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
65impl<K, V> Eq for Map<K, V>
66where
67    K: Eq,
68    V: Eq,
69{
70}
71
72impl<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: ?Sized>(&self, key: &T) -> bool
97    where
98        T: Eq + PhfHash,
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    pub fn get<T: ?Sized>(&self, key: &T) -> Option<&V>
106    where
107        T: Eq + PhfHash,
108        K: PhfBorrow<T>,
109    {
110        self.get_entry(key).map(|e| e.1)
111    }
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: ?Sized>(&self, key: &T) -> Option<&K>
118    where
119        T: Eq + PhfHash,
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    pub fn get_entry<T: ?Sized>(&self, key: &T) -> Option<(&K, &V)>
127    where
128        T: Eq + PhfHash,
129        K: PhfBorrow<T>,
130    {
131        if self.disps.is_empty() {
132            return None;
133        } //Prevent panic on empty map
134        let hashes = phf_shared::hash(key, &self.key);
135        let index = phf_shared::get_index(&hashes, self.disps, self.entries.len());
136        let entry = &self.entries[index as usize];
137        let b: &T = entry.0.borrow();
138        if b == key {
139            Some((&entry.0, &entry.1))
140        } else {
141            None
142        }
143    }
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    pub fn entries(&self) -> Entries<'_, K, V> {
149        Entries {
150            iter: self.entries.iter(),
151        }
152    }
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
173impl<'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`.
183pub struct Entries<'a, K, V> {
184    iter: slice::Iter<'a, (K, V)>,
185}
186
187impl<'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
196impl<'a, K, V> fmt::Debug for Entries<'a, K, V>
197where
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
206impl<'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(|&(ref k, ref v)| (k, v))
211    }
212
213    fn size_hint(&self) -> (usize, Option<usize>) {
214        self.iter.size_hint()
215    }
216}
217
218impl<'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
224impl<'a, K, V> ExactSizeIterator for Entries<'a, K, V> {}
225
226impl<'a, K, V> FusedIterator for Entries<'a, K, V> {}
227
228/// An iterator over the keys in a `Map`.
229pub struct Keys<'a, K, V> {
230    iter: Entries<'a, K, V>,
231}
232
233impl<'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
242impl<'a, K, V> fmt::Debug for Keys<'a, K, V>
243where
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
251impl<'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
263impl<'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
269impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {}
270
271impl<'a, K, V> FusedIterator for Keys<'a, K, V> {}
272
273/// An iterator over the values in a `Map`.
274pub struct Values<'a, K, V> {
275    iter: Entries<'a, K, V>,
276}
277
278impl<'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
287impl<'a, K, V> fmt::Debug for Values<'a, K, V>
288where
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
296impl<'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
308impl<'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
314impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {}
315
316impl<'a, K, V> FusedIterator for Values<'a, K, V> {}
317
318#[cfg(feature = "serde")]
319impl<K, V> Serialize for Map<K, V>
320where
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}