From fe894fee6cedf85f2b2d9ac6526b372a34a387c6 Mon Sep 17 00:00:00 2001 From: Garrett Berg Date: Sun, 9 Jul 2017 14:58:48 -0600 Subject: [PATCH] add pretty sting serialization --- src/ser.rs | 41 ++++++++++++++++++++++++++++++++++++++--- tests/pretty.rs | 20 ++++++++++++++++++++ 2 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 tests/pretty.rs diff --git a/src/ser.rs b/src/ser.rs index bf12278..d92b8a3 100644 --- a/src/ser.rs +++ b/src/ser.rs @@ -214,6 +214,22 @@ impl<'a> Serializer<'a> { } } + /// instantiate a "pretty" formatter + /// + /// TODO: add better docs + pub fn pretty(dst: &'a mut String) -> Serializer<'a> { + Serializer { + dst: dst, + state: State::End, + settings: Settings { + array: Some(ArraySettings { + indent: 4, + }), + pretty_string: true, + }, + } + } + fn display(&mut self, t: T, type_: &'static str) -> Result<(), Error> { @@ -300,12 +316,27 @@ impl<'a> Serializer<'a> { } fn emit_str(&mut self, value: &str) -> Result<(), Error> { - drop(write!(self.dst, "\"")); + let do_pretty = if self.settings.pretty_string { + value.contains('\n') + } else { + false + }; + if do_pretty { + drop(write!(self.dst, "'''\n")); + } else { + drop(write!(self.dst, "\"")); + } for ch in value.chars() { match ch { '\u{8}' => drop(write!(self.dst, "\\b")), '\u{9}' => drop(write!(self.dst, "\\t")), - '\u{a}' => drop(write!(self.dst, "\\n")), + '\u{a}' => { + if do_pretty { + drop(write!(self.dst, "\n")); + } else { + drop(write!(self.dst, "\\n")); + } + }, '\u{c}' => drop(write!(self.dst, "\\f")), '\u{d}' => drop(write!(self.dst, "\\r")), '\u{22}' => drop(write!(self.dst, "\\\"")), @@ -316,7 +347,11 @@ impl<'a> Serializer<'a> { ch => drop(write!(self.dst, "{}", ch)), } } - drop(write!(self.dst, "\"")); + if do_pretty { + drop(write!(self.dst, "'''")); + } else { + drop(write!(self.dst, "\"")); + } Ok(()) } diff --git a/tests/pretty.rs b/tests/pretty.rs new file mode 100644 index 0000000..71c9e63 --- /dev/null +++ b/tests/pretty.rs @@ -0,0 +1,20 @@ +extern crate toml; +extern crate serde; + +use serde::ser::Serialize; + +const example: &str = "\ +[example] +text = ''' +this is the first line +this is the second line +''' +"; + +#[test] +fn test_pretty() { + let value: toml::Value = toml::from_str(example).unwrap(); + let mut result = String::with_capacity(128); + value.serialize(&mut toml::Serializer::pretty(&mut result)).unwrap(); + assert_eq!(example, &result); +}