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
use crate::Error;
use impl_serialize::impl_serialize;
use serde::ser;
use crate::JsonMap;

mod map_key_serializer;
use map_key_serializer::MapKeySerializer;

mod pair_serializer;
mod pair;
use pair_serializer::PairSerializer;

#[derive(Default)]
pub struct MapSerializer {
    map: JsonMap,
    next_key: Option<String>
}

impl MapSerializer {
    pub fn new() -> MapSerializer {
        MapSerializer::default()
    }
}

impl ser::Serializer for MapSerializer {
    type Ok = JsonMap;
    type Error = Error;

    type SerializeMap = Self;
    type SerializeSeq = Self;
    type SerializeTuple = Self;

    type SerializeStruct = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeStructVariant = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeTupleStruct = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeTupleVariant = ser::Impossible<Self::Ok, Self::Error>;

    impl_serialize!(
        Err(Error::CannotSerializeAsObject(value_type.to_string())),
        [
            bool,
            bytes,
            i8, i16, i32, i64,
            u8, u16, u32, u64,
            f32, f64,
            char,
            str,
            none, some, unit,
            unit_struct, unit_variant,
            newtype_struct, newtype_variant,
            tuple_struct, tuple_variant,
            struct, struct_variant
        ]
    );

    impl_serialize!(
        Ok(self),
        [
            seq, map, tuple
        ]
    );
}

impl ser::SerializeMap for MapSerializer {
    type Ok = JsonMap;
    type Error = Error;

    fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
    where
        T: serde::Serialize,
    {
        self.next_key = Some(key.serialize(MapKeySerializer)?);
        Ok(())
    }

    fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: serde::Serialize,
    {
        let key = self.next_key.take();
        
        // Panic because this indicates a bug in the program rather than an
        // expected failure.
        let key = key.expect("serialize_value called before serialize_key");
        self.map.insert(key, serde_json::to_value(&value)?);
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(self.map)
    }
}

impl ser::SerializeSeq for MapSerializer {
    type Ok = JsonMap;
    type Error = Error;

    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: serde::Serialize
    {
        ser::SerializeTuple::serialize_element(self, value)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        ser::SerializeTuple::end(self)
    }
}

impl ser::SerializeTuple for MapSerializer {
    type Ok = JsonMap;
    type Error = Error;

    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: serde::Serialize
    {
        let pair = value.serialize(PairSerializer::new())?;
        self.map.insert(pair.key, pair.value);

        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(self.map)
    }
}

#[cfg(test)]
mod tests {
    use serde::Serialize;
    use serde_json::Value;
    
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn map() {
        let map_serializer = MapSerializer::new();
        let hash_map = HashMap::from([("foo", "bar"), ("baz", "qux")]);
        let map = hash_map.serialize(map_serializer).unwrap();

        let mut correct_result = JsonMap::new();
        correct_result.insert(String::from("foo"), Value::String(String::from("bar")));
        correct_result.insert(String::from("baz"), Value::String(String::from("qux")));

        assert_eq!(map, correct_result);
    }

    #[test]
    fn seq() {
        let map_serializer = MapSerializer::new();
        let seq = vec![("foo", "bar"), ("baz", "qux")];
        let map = seq.serialize(map_serializer).unwrap();

        let mut correct_result = JsonMap::new();
        correct_result.insert(String::from("foo"), Value::String(String::from("bar")));
        correct_result.insert(String::from("baz"), Value::String(String::from("qux")));

        assert_eq!(map, correct_result);
    }

    #[test]
    fn tuple() {
        let map_serializer = MapSerializer::new();
        let tuple = (("foo", "bar"), ("baz", "qux"));
        let map = tuple.serialize(map_serializer).unwrap();

        let mut correct_result = JsonMap::new();
        correct_result.insert(String::from("foo"), Value::String(String::from("bar")));
        correct_result.insert(String::from("baz"), Value::String(String::from("qux")));

        assert_eq!(map, correct_result);
    }

    #[test]
    fn not_a_pair() {
        let map_serializer = MapSerializer::new();
        let tuple = (("foo", "qux", "baz"), ("bar"));
        
        assert_eq!(
            tuple.serialize(map_serializer).err().unwrap(),
            Error::NotAPair
        );
    }
}