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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
//! This module provides a `Serializer` which supports serializing values into various output
//! encodings.

use crate::{key::flatten_keys, value::ValueExt, Encoding, Error, Result};
use serde_json::Value;

/// Options for the `Serializer`. The options are context specific and may only be honored when
/// serializing into a certain `Encoding`.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct SerializeOptions {
    /// Emit output data in a compact format. This will disable pretty printing for encodings that
    /// support it.
    pub compact: bool,
    /// Append a trailing newline to the serialized data.
    pub newline: bool,
    /// When the input is an array of objects and the output encoding is CSV, the field names of
    /// the first object will be used as CSV headers. Field values of all following objects will
    /// be matched to the right CSV column based on their key. Missing fields produce empty columns
    /// while excess fields are ignored.
    pub keys_as_csv_headers: bool,
    /// Optional custom delimiter for CSV output.
    pub csv_delimiter: Option<u8>,
    /// Optional seprator to join text output with.
    pub text_join_separator: Option<String>,
}

impl SerializeOptions {
    /// Creates new `SerializeOptions`.
    pub fn new() -> Self {
        Self::default()
    }
}

/// A `SerializerBuilder` can be used to build a `Serializer` with certain
/// `SerializeOptions`.
///
/// ## Example
///
/// ```
/// use dts::{ser::SerializerBuilder, Encoding};
///
/// let writer = std::io::stdout();
/// let mut serializer = SerializerBuilder::new()
///     .newline(true)
///     .build(writer);
/// ```
#[derive(Debug, Default, Clone)]
pub struct SerializerBuilder {
    opts: SerializeOptions,
}

impl SerializerBuilder {
    /// Creates a new `SerializerBuilder`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Emit output data in a compact format. This will disable pretty printing for encodings that
    /// support it.
    pub fn compact(&mut self, yes: bool) -> &mut Self {
        self.opts.compact = yes;
        self
    }

    /// Append a trailing newline to the serialized data.
    pub fn newline(&mut self, yes: bool) -> &mut Self {
        self.opts.newline = yes;
        self
    }

    /// When the input is an array of objects and the output encoding is CSV, the field names of
    /// the first object will be used as CSV headers. Field values of all following objects will
    /// be matched to the right CSV column based on their key. Missing fields produce empty columns
    /// while excess fields are ignored.
    pub fn keys_as_csv_headers(&mut self, yes: bool) -> &mut Self {
        self.opts.keys_as_csv_headers = yes;
        self
    }

    /// Sets a custom CSV delimiter.
    pub fn csv_delimiter(&mut self, delim: u8) -> &mut Self {
        self.opts.csv_delimiter = Some(delim);
        self
    }

    /// Sets a custom separator to join text output with.
    pub fn text_join_separator<S>(&mut self, sep: S) -> &mut Self
    where
        S: AsRef<str>,
    {
        self.opts.text_join_separator = Some(sep.as_ref().to_owned());
        self
    }

    /// Builds the `Serializer` for the given writer.
    pub fn build<W>(&self, writer: W) -> Serializer<W>
    where
        W: std::io::Write,
    {
        Serializer::with_options(writer, self.opts.clone())
    }
}

/// A `Serializer` can serialize a `Value` into an encoded byte stream.
pub struct Serializer<W> {
    writer: W,
    opts: SerializeOptions,
}

impl<W> Serializer<W>
where
    W: std::io::Write,
{
    /// Creates a new `Serializer` for writer with default options.
    pub fn new(writer: W) -> Self {
        Self::with_options(writer, Default::default())
    }

    /// Creates a new `Serializer` for writer with options.
    pub fn with_options(writer: W, opts: SerializeOptions) -> Self {
        Self { writer, opts }
    }

    /// Serializes the given `Value` and writes the encoded data to the writer.
    ///
    /// ## Example
    ///
    /// ```
    /// use dts::{ser::SerializerBuilder, Encoding};
    /// use serde_json::json;
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let mut buf = Vec::new();
    /// let mut ser = SerializerBuilder::new().compact(true).build(&mut buf);
    /// ser.serialize(Encoding::Json, json!(["foo"]))?;
    ///
    /// assert_eq!(&buf, r#"["foo"]"#.as_bytes());
    /// #     Ok(())
    /// # }
    /// ```
    pub fn serialize(&mut self, encoding: Encoding, value: Value) -> Result<()> {
        match encoding {
            Encoding::Yaml => self.serialize_yaml(value)?,
            Encoding::Json => self.serialize_json(value)?,
            Encoding::Toml => self.serialize_toml(value)?,
            Encoding::Csv => self.serialize_csv(value)?,
            Encoding::QueryString => self.serialize_query_string(value)?,
            Encoding::Xml => self.serialize_xml(value)?,
            Encoding::Text => self.serialize_text(value)?,
            Encoding::Gron => self.serialize_gron(value)?,
            Encoding::Hcl => self.serialize_hcl(value)?,
            encoding => return Err(Error::UnsupportedEncoding(encoding)),
        };

        if self.opts.newline {
            self.writer.write_all(b"\n")?;
        }

        Ok(())
    }

    fn serialize_yaml(&mut self, value: Value) -> Result<()> {
        Ok(serde_yaml::to_writer(&mut self.writer, &value)?)
    }

    fn serialize_json(&mut self, value: Value) -> Result<()> {
        if self.opts.compact {
            serde_json::to_writer(&mut self.writer, &value)?
        } else {
            serde_json::to_writer_pretty(&mut self.writer, &value)?
        }

        Ok(())
    }

    fn serialize_toml(&mut self, value: Value) -> Result<()> {
        let value = toml::Value::try_from(value)?;

        let s = if self.opts.compact {
            toml::ser::to_string(&value)?
        } else {
            toml::ser::to_string_pretty(&value)?
        };

        Ok(self.writer.write_all(s.as_bytes())?)
    }

    fn serialize_csv(&mut self, value: Value) -> Result<()> {
        // Because individual row items may produce errors during serialization because they are of
        // unexpected type, write into a buffer first and only flush out to the writer only if
        // serialization of all rows succeeded. This avoids writing out partial data.
        let mut buf = Vec::new();
        {
            let mut csv_writer = csv::WriterBuilder::new()
                .delimiter(self.opts.csv_delimiter.unwrap_or(b','))
                .from_writer(&mut buf);

            let mut headers: Option<Vec<String>> = None;
            let empty_value = Value::String("".into());

            for row in value.into_array().into_iter() {
                let row_data = if !self.opts.keys_as_csv_headers {
                    row.into_array()
                        .into_iter()
                        .map(Value::into_string)
                        .collect::<Vec<_>>()
                } else {
                    let row = row.into_object("csv");

                    // The first row dictates the header fields.
                    if headers.is_none() {
                        let header_data = row.keys().cloned().collect();
                        csv_writer.serialize(&header_data)?;
                        headers = Some(header_data);
                    }

                    headers
                        .as_ref()
                        .unwrap()
                        .iter()
                        .map(|header| row.get(header).unwrap_or(&empty_value))
                        .cloned()
                        .map(Value::into_string)
                        .collect::<Vec<_>>()
                };

                csv_writer.serialize(row_data)?;
            }
        }

        Ok(self.writer.write_all(&buf)?)
    }

    fn serialize_query_string(&mut self, value: Value) -> Result<()> {
        Ok(serde_qs::to_writer(&value, &mut self.writer)?)
    }

    fn serialize_xml(&mut self, value: Value) -> Result<()> {
        Ok(serde_xml_rs::to_writer(&mut self.writer, &value)?)
    }

    fn serialize_text(&mut self, value: Value) -> Result<()> {
        let sep = self
            .opts
            .text_join_separator
            .clone()
            .unwrap_or_else(|| String::from('\n'));

        let text = value
            .into_array()
            .into_iter()
            .map(Value::into_string)
            .collect::<Vec<String>>()
            .join(&sep);

        Ok(self.writer.write_all(text.as_bytes())?)
    }

    fn serialize_gron(&mut self, value: Value) -> Result<()> {
        let output = flatten_keys(value, "json")
            .as_object()
            .unwrap()
            .into_iter()
            .map(|(k, v)| format!("{} = {};\n", k, v))
            .collect::<String>();

        Ok(self.writer.write_all(output.as_bytes())?)
    }

    fn serialize_hcl(&mut self, value: Value) -> Result<()> {
        Ok(hcl::to_writer(&mut self.writer, &value)?)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use pretty_assertions::assert_eq;
    use serde_json::json;
    use std::str;

    #[track_caller]
    fn assert_serializes_to(encoding: Encoding, value: Value, expected: &str) {
        assert_builder_serializes_to(&mut SerializerBuilder::new(), encoding, value, expected)
    }

    #[track_caller]
    fn assert_builder_serializes_to(
        builder: &mut SerializerBuilder,
        encoding: Encoding,
        value: Value,
        expected: &str,
    ) {
        let mut buf = Vec::new();
        let mut ser = builder.build(&mut buf);

        ser.serialize(encoding, value).unwrap();
        assert_eq!(str::from_utf8(&buf).unwrap(), expected);
    }

    #[track_caller]
    fn assert_serialize_error(encoding: Encoding, value: Value) {
        let mut buf = Vec::new();
        let mut ser = SerializerBuilder::new().build(&mut buf);

        assert!(ser.serialize(encoding, value).is_err())
    }

    #[test]
    fn test_serialize_json() {
        assert_builder_serializes_to(
            &mut SerializerBuilder::new().compact(true),
            Encoding::Json,
            json!(["one", "two"]),
            "[\"one\",\"two\"]",
        );
        assert_serializes_to(
            Encoding::Json,
            json!(["one", "two"]),
            "[\n  \"one\",\n  \"two\"\n]",
        );
    }

    #[test]
    fn test_serialize_csv() {
        assert_serializes_to(
            Encoding::Csv,
            json!([["one", "two"], ["three", "four"]]),
            "one,two\nthree,four\n",
        );
        assert_builder_serializes_to(
            &mut SerializerBuilder::new().keys_as_csv_headers(true),
            Encoding::Csv,
            json!([
                {"one": "val1", "two": "val2"},
                {"one": "val3", "three": "val4"},
                {"two": "val5"}
            ]),
            "one,two\nval1,val2\nval3,\n,val5\n",
        );
        assert_builder_serializes_to(
            &mut SerializerBuilder::new().keys_as_csv_headers(true),
            Encoding::Csv,
            json!({"one": "val1", "two": "val2"}),
            "one,two\nval1,val2\n",
        );
        assert_serializes_to(Encoding::Csv, json!("non-array"), "non-array\n");
        assert_serializes_to(
            Encoding::Csv,
            json!([{"non-array": "row"}]),
            "\"{\"\"non-array\"\":\"\"row\"\"}\"\n",
        );
        assert_builder_serializes_to(
            &mut SerializerBuilder::new().keys_as_csv_headers(true),
            Encoding::Csv,
            json!([["non-object-row"]]),
            "csv\n\"[\"\"non-object-row\"\"]\"\n",
        );
    }

    #[test]
    fn test_serialize_text() {
        assert_serializes_to(Encoding::Text, json!(["one", "two"]), "one\ntwo");
        assert_serializes_to(
            Encoding::Text,
            json!([{"foo": "bar"}, "baz"]),
            "{\"foo\":\"bar\"}\nbaz",
        );
        assert_serializes_to(Encoding::Text, json!({"foo": "bar"}), "{\"foo\":\"bar\"}");
    }

    #[test]
    fn test_serialize_hcl() {
        assert_serializes_to(Encoding::Hcl, json!([{"foo": "bar"}]), "foo = \"bar\"\n");
        assert_serializes_to(
            Encoding::Hcl,
            json!({"foo": "bar", "bar": 2}),
            "foo = \"bar\"\nbar = 2\n",
        );
    }
}