empty_collections/
map.rs

1//! Empty maps. Dark, and alone.
2
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5use std::hash::Hash;
6
7use crate::Empty;
8use std::borrow::Borrow;
9use std::collections::HashMap;
10use std::marker::PhantomData;
11
12/// A map that is guaranteed to be empty.
13///
14/// Naturally, the following operations are impossible with [`EMap`]:
15///
16/// - `entry`
17/// - `insert`
18/// - `remove`
19///
20/// And many others have been elided for being pointless.
21#[cfg_attr(
22    feature = "serde",
23    derive(Deserialize, Serialize),
24    serde(bound(
25        serialize = "K: Eq + Hash + Clone + Serialize, V: Clone + Serialize ",
26        deserialize = "K: Eq + Hash + Clone + Deserialize<'de>, V: Deserialize<'de>"
27    )),
28    serde(into = "HashMap<K, V>", try_from = "HashMap<K, V>")
29)]
30#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct EMap<K, V> {
32    key: PhantomData<K>,
33    val: PhantomData<V>,
34}
35
36impl<K, V> EMap<K, V> {
37    /// No it doesn't.
38    pub const fn contains_key<Q>(&self, _: &Q) -> bool
39    where
40        K: Borrow<Q>,
41    {
42        false
43    }
44
45    /// All the keys of this empty map.
46    pub fn keys(&self) -> Empty<&K> {
47        Empty::new()
48    }
49
50    /// All the keys of this empty map.
51    pub fn into_keys(self) -> Empty<K> {
52        Empty::new()
53    }
54
55    /// All the values of this empty map.
56    pub fn into_values(self) -> Empty<V> {
57        Empty::new()
58    }
59
60    /// Yes.
61    pub const fn is_empty(&self) -> bool {
62        true
63    }
64
65    /// All key-value pairs of this empty map.
66    pub fn iter(&self) -> Empty<(K, V)> {
67        Empty::new()
68    }
69
70    /// It's 0.
71    pub const fn len(&self) -> usize {
72        0
73    }
74
75    /// Think of the possibilities!
76    pub fn new() -> EMap<K, V> {
77        EMap {
78            key: PhantomData,
79            val: PhantomData,
80        }
81    }
82
83    /// All the values of this empty map.
84    pub fn values(&self) -> Empty<&V> {
85        Empty::new()
86    }
87}
88
89impl<K, V> IntoIterator for EMap<K, V> {
90    type Item = (K, V);
91
92    type IntoIter = Empty<(K, V)>;
93
94    fn into_iter(self) -> Self::IntoIter {
95        Empty::new()
96    }
97}
98
99impl<K, V> From<EMap<K, V>> for HashMap<K, V> {
100    fn from(_: EMap<K, V>) -> Self {
101        HashMap::new()
102    }
103}
104
105impl<K, V> TryFrom<HashMap<K, V>> for EMap<K, V> {
106    type Error = &'static str;
107
108    fn try_from(value: HashMap<K, V>) -> Result<Self, Self::Error> {
109        if value.is_empty() {
110            Ok(EMap::new())
111        } else {
112            Err("Cannot convert a non-empty HashMap into an empty one")
113        }
114    }
115}
116
117impl<K, V> std::fmt::Debug for EMap<K, V> {
118    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        // FIXME: 2024-08-29 Critical inefficiency here.
120        let m: HashMap<usize, usize> = HashMap::new();
121        m.fmt(f)
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    #[test]
130    fn eq() {
131        let a: EMap<usize, usize> = EMap::new();
132        let b = EMap::new();
133        assert_eq!(a, b);
134    }
135
136    #[test]
137    fn ord() {
138        let a: EMap<usize, usize> = EMap::new();
139        let b = EMap::new();
140        assert!(!(a < b));
141        assert!(!(a > b));
142    }
143
144    #[cfg(feature = "serde")]
145    mod serialize {
146        use crate::EMap;
147
148        #[test]
149        fn roundtrip() {
150            let a: EMap<usize, usize> = EMap::new();
151            let j = serde_json::to_string(&a).unwrap();
152            let r = serde_json::from_str(&j).unwrap();
153            assert_eq!(a, r);
154        }
155    }
156}