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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// Take a look at the license at the top of the repository in the LICENSE file.

#![allow(clippy::upper_case_acronyms)]

use std::fmt;

use glib::{value::ToValue, Date};
use serde::{
    de,
    de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor},
    ser,
    ser::{Serialize, SerializeSeq, SerializeTuple, Serializer},
};

use crate::{
    date_time_serde, value::*, value_serde::*, Buffer, DateTime, Sample, Structure, StructureRef,
};

struct FieldSe<'a>(&'static str, &'a glib::SendValue);
impl<'a> Serialize for FieldSe<'a> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        ser_value!(self.1, |type_, value| {
            let mut tup = serializer.serialize_tuple(3)?;
            tup.serialize_element(self.0)?;
            tup.serialize_element(type_)?;
            tup.serialize_element(&value)?;
            tup.end()
        })
    }
}

struct StructureForIter<'a>(&'a StructureRef);
impl<'a> Serialize for StructureForIter<'a> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let iter = self.0.iter();
        let size = iter.size_hint().0;
        if size > 0 {
            let mut seq = serializer.serialize_seq(Some(size))?;
            for field in iter {
                seq.serialize_element(&FieldSe(field.0, field.1))?;
            }
            seq.end()
        } else {
            let seq = serializer.serialize_seq(None)?;
            seq.end()
        }
    }
}

impl Serialize for StructureRef {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut tup = serializer.serialize_tuple(2)?;
        tup.serialize_element(self.name().as_str())?;
        tup.serialize_element(&StructureForIter(self))?;
        tup.end()
    }
}

impl Serialize for Structure {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        <StructureRef as Serialize>::serialize(self.as_ref(), serializer)
    }
}

struct FieldDe(String, SendValue);
impl From<FieldDe> for (String, glib::SendValue) {
    fn from(field_de: FieldDe) -> Self {
        skip_assert_initialized!();
        (field_de.0, field_de.1.into())
    }
}

struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
    type Value = FieldDe;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str(
            "a tuple of 3 elements (name: `String`, type name: `String`, value: `Value`)",
        )
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
        let name = seq
            .next_element::<String>()?
            .ok_or_else(|| de::Error::custom("Expected a value for `Value` name"))?;
        let type_name = seq
            .next_element::<String>()?
            .ok_or_else(|| de::Error::custom("Expected a value for `Value` type"))?;
        let send_value = de_send_value!(type_name, seq)?
            .ok_or_else(|| de::Error::custom("Expected a value for `Value`"))?;
        Ok(FieldDe(name, send_value))
    }
}

impl<'de> Deserialize<'de> for FieldDe {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        skip_assert_initialized!();
        deserializer.deserialize_tuple(3, FieldVisitor)
    }
}

struct FieldsDe<'a>(&'a mut StructureRef);

struct FieldsVisitor<'a>(&'a mut StructureRef);
impl<'de, 'a> Visitor<'de> for FieldsVisitor<'a> {
    type Value = ();

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a sequence of `Structure` `Field`s")
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> {
        while let Some(field) = seq.next_element::<FieldDe>()? {
            let (name, value): (String, glib::SendValue) = field.into();
            self.0.set_value(name.as_str(), value);
        }

        Ok(())
    }
}

impl<'de, 'a> DeserializeSeed<'de> for FieldsDe<'a> {
    type Value = ();

    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<(), D::Error> {
        skip_assert_initialized!();
        deserializer.deserialize_seq(FieldsVisitor(self.0))
    }
}

struct StructureVisitor;
impl<'de> Visitor<'de> for StructureVisitor {
    type Value = Structure;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a `Structure` (name, sequence of `Field`s)")
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
        let name = seq
            .next_element::<String>()?
            .ok_or_else(|| de::Error::custom("Expected a name for the `Structure`"))?;
        let mut structure = Structure::new_empty(name);
        seq.next_element_seed(FieldsDe(structure.as_mut()))?
            .ok_or_else(|| de::Error::custom("Expected a sequence of `Field`s"))?;

        Ok(structure)
    }
}

impl<'de> Deserialize<'de> for Structure {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        skip_assert_initialized!();
        deserializer.deserialize_tuple(2, StructureVisitor)
    }
}

#[cfg(test)]
mod tests {
    use glib::{Date, DateMonth};

    use crate::{Array, DateTime, Fraction, Structure};

    #[test]
    fn test_serialize() {
        crate::init().unwrap();

        let s = Structure::builder("test")
            .field("f1", "abc")
            .field("f2", String::from("bcd"))
            .field("f3", 123i32)
            .field("fraction", Fraction::new(1, 2))
            .field("date", Date::from_dmy(19, DateMonth::August, 2019).unwrap())
            .field(
                "date_time",
                DateTime::new(2f32, 2019, 8, 19, 13, 34, 42f64).unwrap(),
            )
            .field("array", Array::new([1, 2]))
            .build();

        let pretty_config = ron::ser::PrettyConfig::new().new_line("".to_string());

        let res = ron::ser::to_string_pretty(&s, pretty_config);
        assert_eq!(
            Ok(concat!(
                r#"("test", ["#,
                r#"    ("f1", "String", Some("abc")),"#,
                r#"    ("f2", "String", Some("bcd")),"#,
                r#"    ("f3", "i32", 123),"#,
                r#"    ("fraction", "Fraction", (1, 2)),"#,
                r#"    ("date", "Date", Some(YMD(2019, 8, 19))),"#,
                r#"    ("date_time", "DateTime", Some(YMDhmsTz(2019, 8, 19, 13, 34, 42.0, 2.0))),"#,
                r#"    ("array", "Array", ["#,
                r#"        ("i32", 1),"#,
                r#"        ("i32", 2),"#,
                r#"    ]),"#,
                r#"])"#,
            )
            .to_owned()),
            res,
        );
    }

    #[test]
    fn test_deserialize() {
        crate::init().unwrap();

        let s_ron = r#"
            ("test", [
                ("f1", "String", Some("abc")),
                ("f2", "String", Some("bcd")),
                ("f3", "i32", 123),
                ("fraction", "Fraction", (1, 2)),
                ("date", "Date", Some(YMD(2019, 8, 19))),
                ("date_time", "DateTime", Some(YMDhmsTz(2019, 8, 19, 13, 34, 42, 2))),
                ("array", "Array", [
                    ("i32", 1),
                    ("i32", 2),
                ]),
            ])"#;
        let s: Structure = ron::de::from_str(s_ron).unwrap();
        assert_eq!(
            s.as_ref(),
            Structure::builder("test")
                .field("f1", "abc")
                .field("f2", "bcd")
                .field("f3", 123)
                .field("date", Date::from_dmy(19, DateMonth::August, 2019).unwrap())
                .field(
                    "date_time",
                    DateTime::new(2f32, 2019, 8, 19, 13, 34, 42f64).unwrap()
                )
                .field("fraction", Fraction::new(1, 2))
                .field("array", Array::new([1, 2]))
                .build()
                .as_ref()
        );
    }

    #[test]
    fn test_serde_roundtrip() {
        crate::init().unwrap();

        let s = Structure::builder("test")
            .field("f1", "abc")
            .field("f2", "bcd".to_owned())
            .field("f3", 123i32)
            .field("fraction", Fraction::new(1, 2))
            .field("date", Date::from_dmy(19, DateMonth::August, 2019).unwrap())
            .field(
                "date_time",
                DateTime::new(2f32, 2019, 8, 19, 13, 34, 42f64).unwrap(),
            )
            .field("array", Array::new([1, 2]))
            .build();
        let s_ser = ron::ser::to_string(&s).unwrap();
        let s_de: Structure = ron::de::from_str(s_ser.as_str()).unwrap();
        assert_eq!(s_de.as_ref(), s.as_ref());
    }
}