pretty arrays

This commit is contained in:
Garrett Berg 2017-07-09 15:20:29 -06:00
parent 27757113ec
commit 3ec47e6758
2 changed files with 18 additions and 4 deletions

View file

@ -142,6 +142,7 @@ pub enum Error {
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
pub struct ArraySettings { pub struct ArraySettings {
indent: u64, indent: u64,
trailing_comma: bool,
} }
/// Formatting Settings /// Formatting Settings
@ -224,6 +225,7 @@ impl<'a> Serializer<'a> {
settings: Settings { settings: Settings {
array: Some(ArraySettings { array: Some(ArraySettings {
indent: 4, indent: 4,
trailing_comma: true,
}), }),
pretty_string: true, pretty_string: true,
}, },
@ -667,12 +669,18 @@ impl<'a, 'b> ser::SerializeSeq for SerializeSeq<'a, 'b> {
match self.type_.get() { match self.type_.get() {
Some("table") => return Ok(()), Some("table") => return Ok(()),
Some(_) => { Some(_) => {
if self.ser.settings.array.is_some() { match self.ser.settings.array {
Some(ref a) => {
if a.trailing_comma {
self.ser.dst.push_str(",");
}
self.ser.dst.push_str("\n]"); self.ser.dst.push_str("\n]");
} else { },
None => {
self.ser.dst.push_str("]"); self.ser.dst.push_str("]");
} }
} }
}
None => { None => {
assert!(self.first.get()); assert!(self.first.get());
self.ser.emit_key("array")?; self.ser.emit_key("array")?;

View file

@ -5,6 +5,10 @@ use serde::ser::Serialize;
const EXAMPLE: &str = "\ const EXAMPLE: &str = "\
[example] [example]
array = [
\"item 1\",
\"item 2\",
]
text = ''' text = '''
this is the first line this is the first line
this is the second line this is the second line
@ -16,5 +20,7 @@ fn test_pretty() {
let value: toml::Value = toml::from_str(EXAMPLE).unwrap(); let value: toml::Value = toml::from_str(EXAMPLE).unwrap();
let mut result = String::with_capacity(128); let mut result = String::with_capacity(128);
value.serialize(&mut toml::Serializer::pretty(&mut result)).unwrap(); value.serialize(&mut toml::Serializer::pretty(&mut result)).unwrap();
println!("example:\n{}", EXAMPLE);
println!("result:\n{}", result);
assert_eq!(EXAMPLE, &result); assert_eq!(EXAMPLE, &result);
} }