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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
mod size_hint {
    use core::cmp;

    /// This presumably exists to prevent denial of service attacks.
    ///
    /// Original discussion: https://github.com/serde-rs/serde/issues/1114.
    #[cfg_attr(feature = "inline-more", inline)]
    pub(super) fn cautious(hint: Option<usize>) -> usize {
        cmp::min(hint.unwrap_or(0), 4096)
    }
}

mod map {
    use crate::raw::Allocator;
    use core::fmt;
    use core::hash::{BuildHasher, Hash};
    use core::marker::PhantomData;
    use serde::de::{Deserialize, Deserializer, MapAccess, Visitor};
    use serde::ser::{Serialize, Serializer};

    use crate::hash_map::HashMap;

    use super::size_hint;

    impl<K, V, H, A> Serialize for HashMap<K, V, H, A>
    where
        K: Serialize + Eq + Hash,
        V: Serialize,
        H: BuildHasher,
        A: Allocator,
    {
        #[cfg_attr(feature = "inline-more", inline)]
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.collect_map(self)
        }
    }

    impl<'de, K, V, S, A> Deserialize<'de> for HashMap<K, V, S, A>
    where
        K: Deserialize<'de> + Eq + Hash,
        V: Deserialize<'de>,
        S: BuildHasher + Default,
        A: Allocator + Default,
    {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            struct MapVisitor<K, V, S, A>
            where
                A: Allocator,
            {
                marker: PhantomData<HashMap<K, V, S, A>>,
            }

            impl<'de, K, V, S, A> Visitor<'de> for MapVisitor<K, V, S, A>
            where
                K: Deserialize<'de> + Eq + Hash,
                V: Deserialize<'de>,
                S: BuildHasher + Default,
                A: Allocator + Default,
            {
                type Value = HashMap<K, V, S, A>;

                fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                    formatter.write_str("a map")
                }

                #[cfg_attr(feature = "inline-more", inline)]
                fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
                where
                    M: MapAccess<'de>,
                {
                    let mut values = HashMap::with_capacity_and_hasher_in(
                        size_hint::cautious(map.size_hint()),
                        S::default(),
                        A::default(),
                    );

                    while let Some((key, value)) = map.next_entry()? {
                        values.insert(key, value);
                    }

                    Ok(values)
                }
            }

            let visitor = MapVisitor {
                marker: PhantomData,
            };
            deserializer.deserialize_map(visitor)
        }
    }
}

mod set {
    use crate::raw::Allocator;
    use core::fmt;
    use core::hash::{BuildHasher, Hash};
    use core::marker::PhantomData;
    use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
    use serde::ser::{Serialize, Serializer};

    use crate::hash_set::HashSet;

    use super::size_hint;

    impl<T, H, A> Serialize for HashSet<T, H, A>
    where
        T: Serialize + Eq + Hash,
        H: BuildHasher,
        A: Allocator,
    {
        #[cfg_attr(feature = "inline-more", inline)]
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.collect_seq(self)
        }
    }

    impl<'de, T, S, A> Deserialize<'de> for HashSet<T, S, A>
    where
        T: Deserialize<'de> + Eq + Hash,
        S: BuildHasher + Default,
        A: Allocator + Default,
    {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            struct SeqVisitor<T, S, A>
            where
                A: Allocator,
            {
                marker: PhantomData<HashSet<T, S, A>>,
            }

            impl<'de, T, S, A> Visitor<'de> for SeqVisitor<T, S, A>
            where
                T: Deserialize<'de> + Eq + Hash,
                S: BuildHasher + Default,
                A: Allocator + Default,
            {
                type Value = HashSet<T, S, A>;

                fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                    formatter.write_str("a sequence")
                }

                #[cfg_attr(feature = "inline-more", inline)]
                fn visit_seq<M>(self, mut seq: M) -> Result<Self::Value, M::Error>
                where
                    M: SeqAccess<'de>,
                {
                    let mut values = HashSet::with_capacity_and_hasher_in(
                        size_hint::cautious(seq.size_hint()),
                        S::default(),
                        A::default(),
                    );

                    while let Some(value) = seq.next_element()? {
                        values.insert(value);
                    }

                    Ok(values)
                }
            }

            let visitor = SeqVisitor {
                marker: PhantomData,
            };
            deserializer.deserialize_seq(visitor)
        }

        #[allow(clippy::missing_errors_doc)]
        fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
        where
            D: Deserializer<'de>,
        {
            struct SeqInPlaceVisitor<'a, T, S, A>(&'a mut HashSet<T, S, A>)
            where
                A: Allocator;

            impl<'a, 'de, T, S, A> Visitor<'de> for SeqInPlaceVisitor<'a, T, S, A>
            where
                T: Deserialize<'de> + Eq + Hash,
                S: BuildHasher + Default,
                A: Allocator,
            {
                type Value = ();

                fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                    formatter.write_str("a sequence")
                }

                #[cfg_attr(feature = "inline-more", inline)]
                fn visit_seq<M>(self, mut seq: M) -> Result<Self::Value, M::Error>
                where
                    M: SeqAccess<'de>,
                {
                    self.0.clear();
                    self.0.reserve(size_hint::cautious(seq.size_hint()));

                    while let Some(value) = seq.next_element()? {
                        self.0.insert(value);
                    }

                    Ok(())
                }
            }

            deserializer.deserialize_seq(SeqInPlaceVisitor(place))
        }
    }
}