Debian Codegraph @

src/serde.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 //! Implementations of `serde::Serialize` and `serde::Deserialize` for
2 //! `BiHashMap` and `BiBTreeMap`.
3 //!
4 //! You do not need to import anything from this module to use this
5 //! functionality, simply enable the `serde` feature in your dependency
6 //! manifest. Note that currently, this requires the `std` feature to also be
7 //! enabled, and thus cannot be used in `no_std` enviroments.
8 //!
9 //! # Examples
10 //!
11 //! You can easily serialize and deserialize bimaps with any serde-compatbile
12 //! serializer or deserializer.
13 //!
14 //! Serializing and deserializing a [`BiHashMap`]:
15 //!
16 //! ```
17 //! # use bimap::BiHashMap;
18 //! // create a new bimap
19 //! let mut map = BiHashMap::new();
20 //!
21 //! // insert some pairs
22 //! map.insert('A', 1);
23 //! map.insert('B', 2);
24 //! map.insert('C', 3);
25 //!
26 //! // convert the bimap to json
27 //! let json = serde_json::to_string(&map).unwrap();
28 //!
29 //! // convert the json back into a bimap
30 //! let map2 = serde_json::from_str(&json).unwrap();
31 //!
32 //! // check that the two bimaps are equal
33 //! assert_eq!(map, map2);
34 //! ```
35 //!
36 //! Serializing and deserializing a [`BiBTreeMap`]:
37 //! ```
38 //! # use bimap::BiBTreeMap;
39 //! // create a new bimap
40 //! let mut map = BiBTreeMap::new();
41 //!
42 //! // insert some pairs
43 //! map.insert('A', 3);
44 //! map.insert('B', 2);
45 //! map.insert('C', 1);
46 //!
47 //! // convert the bimap to json
48 //! let json = serde_json::to_string(&map).unwrap();
49 //!
50 //! // convert the json back into a bimap
51 //! let map2 = serde_json::from_str(&json).unwrap();
52 //!
53 //! // check that the two bimaps are equal
54 //! assert_eq!(map, map2);
55 //! ```
56 //!
57 //! Of course, this is only possible for bimaps where the values also implement
58 //! `Serialize` and `Deserialize` respectively:
59 //!
60 //! ```compile_fail
61 //! # use bimap::BiHashMap;
62 //! // this type doesn't implement Serialize or Deserialize!
63 //! #[derive(PartialEq, Eq, Hash)]
64 //! enum MyEnum { A, B, C }
65 //!
66 //! // create a bimap and add some pairs
67 //! let mut map = BiHashMap::new();
68 //! map.insert(MyEnum::A, 1);
69 //! map.insert(MyEnum::B, 2);
70 //! map.insert(MyEnum::C, 3);
71 //!
72 //! // this line will cause the code to fail to compile
73 //! let json = serde_json::to_string(&map).unwrap();
74 //! ```
75 //!
76 //! # Implementation details
77 //!
78 //! Bimaps are serialized and deserialized as a map data type in serde.
79 //! Consequentially, it is possible to serialize and deserialize bimaps to/from
80 //! other types that are represented the same way. *This is considered an
81 //! implementation detail and should not be relied upon.*
82 //!
83 //! For example, a bimap can be deserialized from the serialized form of a
84 //! standard [`HashMap`]. However, *deserializing a bimap silently overwrites
85 //! any conflicting pairs*, leading to non-deterministic results.
86 //! ```
87 //! # use std::collections::HashMap;
88 //! # use bimap::BiHashMap;
89 //! // construct a regular map
90 //! let mut map = HashMap::new();
91 //!
92 //! // insert some entries
93 //! // note that both 'B' and 'C' are associated with the value 2 here
94 //! map.insert('A', 1);
95 //! map.insert('B', 2);
96 //! map.insert('C', 2);
97 //!
98 //! // serialize the map
99 //! let json = serde_json::to_string(&map).unwrap();
100 //!
101 //! // deserialize it into a bimap
102 //! let bimap: BiHashMap<char, i32> = serde_json::from_str(&json).unwrap();
103 //!
104 //! // deserialization succeeds, but the bimap is now in a non-deterministic
105 //! // state - either ('B', 2) or ('C', 2) will have been overwritten while
106 //! // deserializing, but this depends on the iteration order of the original
107 //! // HashMap that was serialized.
108 //!
109 //! // we can still demonstrate that certain properties of the bimap are still
110 //! // in a known state, but this shouldn't be relied upon
111 //! assert_eq!(bimap.len(), 2);
112 //! assert_eq!(bimap.get_by_left(&'A'), Some(&1));
113 //! assert!(bimap.get_by_left(&'B') == Some(&2) || bimap.get_by_left(&'C') == Some(&2))
114 //! ```
115 //!
116 //! The reverse is also possible: bimaps may be serialized and then
117 //! deserialized as other compatible types, such as a [`HashMap`].
118 //!
119 //! ```
120 //! # use std::collections::HashMap;
121 //! # use bimap::BiHashMap;
122 //! // construct a bimap
123 //! let mut bimap = BiHashMap::new();
124 //!
125 //! // insert some pairs
126 //! bimap.insert('A', 1);
127 //! bimap.insert('B', 2);
128 //! bimap.insert('C', 3);
129 //!
130 //! // serialize the bimap
131 //! let json = serde_json::to_string(&bimap).unwrap();
132 //!
133 //! // deserialize it as a regular map
134 //! let map: HashMap<char, i32> = serde_json::from_str(&json).unwrap();
135 //!
136 //! // this succeeds and the result is sensible, but this is still an
137 //! // implementation detail and shouldn't be relied upon.
138 //! assert_eq!(map.len(), 3);
139 //! assert_eq!(map[&'A'], 1);
140 //! assert_eq!(map[&'B'], 2);
141 //! assert_eq!(map[&'C'], 3);
142 //! ```
143 //! [`BiHashMap`]: crate::BiHashMap
144 //! [`BiBTreeMap`]: crate::BiBTreeMap
145 //! [`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html
146
147 use crate::{BiBTreeMap, BiHashMap};
148 use serde::{
149 de::{MapAccess, Visitor},
150 Deserialize, Deserializer, Serialize, Serializer,
151 };
152 use std::{
153 default::Default,
154 fmt::{Formatter, Result as FmtResult},
155 hash::{BuildHasher, Hash},
156 marker::PhantomData,
157 };
158
159 /// Serializer for `BiHashMap`
160 impl<L, R, LS, RS> Serialize for BiHashMap<L, R, LS, RS>
161 where
162 L: Serialize + Eq + Hash,
163 R: Serialize + Eq + Hash,
164 LS: BuildHasher + Default,
165 RS: BuildHasher + Default,
166 {
167 fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
168 ser.collect_map(self.iter())
169 }
170 }
171
172 /// Visitor to construct `BiHashMap` from serialized map entries
173 struct BiHashMapVisitor<L, R, LS, RS> {
174 marker: PhantomData<BiHashMap<L, R, LS, RS>>,
175 }
176
177 impl<'de, L, R, LS, RS> Visitor<'de> for BiHashMapVisitor<L, R, LS, RS>
178 where
179 L: Deserialize<'de> + Eq + Hash,
180 R: Deserialize<'de> + Eq + Hash,
181 LS: BuildHasher + Default,
182 RS: BuildHasher + Default,
183 {
184 fn expecting(&self, f: &mut Formatter) -> FmtResult {
185 write!(f, "a map")
186 }
187
188 type Value = BiHashMap<L, R, LS, RS>;
189 fn visit_map<A: MapAccess<'de>>(self, mut entries: A) -> Result<Self::Value, A::Error> {
190 let mut map = match entries.size_hint() {
191 Some(s) => BiHashMap::<L, R, LS, RS>::with_capacity_and_hashers(
192 s,
193 LS::default(),
194 RS::default(),
195 ),
196 None => BiHashMap::<L, R, LS, RS>::with_hashers(LS::default(), RS::default()),
197 };
198 while let Some((l, r)) = entries.next_entry()? {
199 map.insert(l, r);
200 }
201 Ok(map)
202 }
203 }
204
205 /// Deserializer for `BiHashMap`
206 impl<'de, L, R, LS, RS> Deserialize<'de> for BiHashMap<L, R, LS, RS>
207 where
208 L: Deserialize<'de> + Eq + Hash,
209 R: Deserialize<'de> + Eq + Hash,
210 LS: BuildHasher + Default,
211 RS: BuildHasher + Default,
212 {
213 fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
214 de.deserialize_map(BiHashMapVisitor::<L, R, LS, RS> {
215 marker: PhantomData::default(),
216 })
217 }
218 }
219
220 /// Serializer for `BiBTreeMap`
221 impl<L, R> Serialize for BiBTreeMap<L, R>
222 where
223 L: Serialize + Ord,
224 R: Serialize + Ord,
225 {
226 fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
227 ser.collect_map(self.iter())
228 }
229 }
230
231 /// Visitor to construct `BiBTreeMap` from serialized map entries
232 struct BiBTreeMapVisitor<L, R> {
233 marker: PhantomData<BiBTreeMap<L, R>>,
234 }
235
236 impl<'de, L, R> Visitor<'de> for BiBTreeMapVisitor<L, R>
237 where
238 L: Deserialize<'de> + Ord,
239 R: Deserialize<'de> + Ord,
240 {
241 fn expecting(&self, f: &mut Formatter) -> FmtResult {
242 write!(f, "a map")
243 }
244
245 type Value = BiBTreeMap<L, R>;
246 fn visit_map<A: MapAccess<'de>>(self, mut entries: A) -> Result<Self::Value, A::Error> {
247 let mut map = BiBTreeMap::new();
248 while let Some((l, r)) = entries.next_entry()? {
249 map.insert(l, r);
250 }
251 Ok(map)
252 }
253 }
254
255 /// Deserializer for `BiBTreeMap`
256 impl<'de, L, R> Deserialize<'de> for BiBTreeMap<L, R>
257 where
258 L: Deserialize<'de> + Ord,
259 R: Deserialize<'de> + Ord,
260 {
261 fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
262 de.deserialize_map(BiBTreeMapVisitor {
263 marker: PhantomData::default(),
264 })
265 }
266 }
267
268 #[cfg(test)]
269 mod tests {
270 use super::*;
271 use serde::de::value::Error;
272 use std::hash::BuildHasherDefault;
273
274 #[test]
275 fn serde_hash() {
276 let mut bimap = BiHashMap::new();
277 bimap.insert('a', 1);
278 bimap.insert('b', 2);
279 bimap.insert('c', 3);
280
281 let json = serde_json::to_string(&bimap).unwrap();
282 let bimap2 = serde_json::from_str(&json).unwrap();
283
284 assert_eq!(bimap, bimap2);
285 }
286
287 #[test]
288 fn serde_hash_w_fnv_hasher() {
289 let hasher_builder = BuildHasherDefault::<fnv::FnvHasher>::default();
290 let mut bimap = BiHashMap::<
291 char,
292 u8,
293 BuildHasherDefault<fnv::FnvHasher>,
294 BuildHasherDefault<fnv::FnvHasher>,
295 >::with_capacity_and_hashers(
296 4, hasher_builder.clone(), hasher_builder.clone()
297 );
298 bimap.insert('f', 1);
299 bimap.insert('g', 2);
300 bimap.insert('h', 3);
301
302 let json = serde_json::to_string(&bimap).unwrap();
303 let bimap2 = serde_json::from_str(&json).unwrap();
304
305 assert_eq!(bimap, bimap2);
306 }
307
308 #[test]
309 fn serde_hash_w_hashbrown_hasher() {
310 let hasher_builder = hashbrown::hash_map::DefaultHashBuilder::default();
311 let mut bimap = BiHashMap::<
312 char,
313 u8,
314 hashbrown::hash_map::DefaultHashBuilder,
315 hashbrown::hash_map::DefaultHashBuilder,
316 >::with_capacity_and_hashers(
317 4, hasher_builder.clone(), hasher_builder.clone()
318 );
319 bimap.insert('x', 1);
320 bimap.insert('y', 2);
321 bimap.insert('z', 3);
322
323 let json = serde_json::to_string(&bimap).unwrap();
324 let bimap2 = serde_json::from_str(&json).unwrap();
325
326 assert_eq!(bimap, bimap2);
327 }
328
329 #[test]
330 fn serde_btree() {
331 let mut bimap = BiBTreeMap::new();
332 bimap.insert('a', 1);
333 bimap.insert('b', 2);
334 bimap.insert('c', 3);
335
336 let json = serde_json::to_string(&bimap).unwrap();
337 let bimap2 = serde_json::from_str(&json).unwrap();
338
339 assert_eq!(bimap, bimap2);
340 }
341
342 #[test]
343 fn expecting_btree() {
344 let visitor = BiBTreeMapVisitor {
345 marker: PhantomData::<BiBTreeMap<char, i32>>,
346 };
347 let error_str = format!("{:?}", visitor.visit_bool::<Error>(true));
348 let expected = "Err(Error(\"invalid type: boolean `true`, expected a map\"))";
349 assert_eq!(error_str, expected);
350 }
351
352 #[test]
353 fn expecting_hash() {
354 let visitor = BiHashMapVisitor {
355 marker: PhantomData::<BiHashMap<char, i32>>,
356 };
357 let error_str = format!("{:?}", visitor.visit_bool::<Error>(true));
358 let expected = "Err(Error(\"invalid type: boolean `true`, expected a map\"))";
359 assert_eq!(error_str, expected);
360 }
361 }