1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
//! An optional implementation of serialization/deserialization.
extern crate serde;
use std::fmt::{Formatter, Result as FmtResult};
use std::hash::{BuildHasher, Hash};
use std::marker::PhantomData;
use super::LinkedHashMap;
use self::serde::de::{Error, MapAccess, Visitor};
use self::serde::ser::SerializeMap;
use self::serde::{Deserialize, Deserializer, Serialize, Serializer};
impl<K, V, S> Serialize for LinkedHashMap<K, V, S>
where
K: Serialize + Eq + Hash,
V: Serialize,
S: BuildHasher,
{
#[inline]
fn serialize<T>(&self, serializer: T) -> Result<T::Ok, T::Error>
where
T: Serializer,
{
let mut map_serializer = serializer.serialize_map(Some(self.len()))?;
for (k, v) in self {
map_serializer.serialize_key(k)?;
map_serializer.serialize_value(v)?;
}
map_serializer.end()
}
}
#[derive(Debug)]
/// `serde::de::Visitor` for a linked hash map.
pub struct LinkedHashMapVisitor<K, V> {
marker: PhantomData<LinkedHashMap<K, V>>,
}
impl<K, V> LinkedHashMapVisitor<K, V> {
/// Creates a new visitor for a linked hash map.
pub fn new() -> Self {
LinkedHashMapVisitor {
marker: PhantomData,
}
}
}
impl<K, V> Default for LinkedHashMapVisitor<K, V> {
fn default() -> Self {
LinkedHashMapVisitor::new()
}
}
impl<'de, K, V> Visitor<'de> for LinkedHashMapVisitor<K, V>
where
K: Deserialize<'de> + Eq + Hash,
V: Deserialize<'de>,
{
type Value = LinkedHashMap<K, V>;
fn expecting(&self, formatter: &mut Formatter) -> FmtResult {
write!(formatter, "a map")
}
#[inline]
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(LinkedHashMap::new())
}
#[inline]
fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut values = LinkedHashMap::with_capacity(map.size_hint().unwrap_or(0));
while let Some((key, value)) = map.next_entry()? {
values.insert(key, value);
}
Ok(values)
}
}
impl<'de, K, V> Deserialize<'de> for LinkedHashMap<K, V>
where
K: Deserialize<'de> + Eq + Hash,
V: Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<LinkedHashMap<K, V>, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_map(LinkedHashMapVisitor::new())
}
}
|