From fba7778782193f0d0899f82d6b322da59a9044a0 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sat, 11 Feb 2017 09:13:28 -0800 Subject: Fix displaying empty arrays Closes #145 --- src/value.rs | 14 ++++++-------- tests/display-tricky.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 8 deletions(-) create mode 100644 tests/display-tricky.rs diff --git a/src/value.rs b/src/value.rs index 99e6d23..4d56023 100644 --- a/src/value.rs +++ b/src/value.rs @@ -366,21 +366,19 @@ impl ser::Serialize for Value { // Be sure to visit non-tables first (and also non // array-of-tables) as all keys must be emitted first. for (k, v) in t { - if !v.is_array() && !v.is_table() { - map.serialize_key(k)?; - map.serialize_value(v)?; + if !v.is_table() && !v.is_array() || + (v.as_array().map(|a| a.len() == 0).unwrap_or(false)) { + map.serialize_entry(k, v)?; } } for (k, v) in t { - if v.is_array() { - map.serialize_key(k)?; - map.serialize_value(v)?; + if v.as_array().map(|a| a.len() > 0).unwrap_or(false) { + map.serialize_entry(k, v)?; } } for (k, v) in t { if v.is_table() { - map.serialize_key(k)?; - map.serialize_value(v)?; + map.serialize_entry(k, v)?; } } map.end() diff --git a/tests/display-tricky.rs b/tests/display-tricky.rs new file mode 100644 index 0000000..069e0f9 --- /dev/null +++ b/tests/display-tricky.rs @@ -0,0 +1,49 @@ +extern crate toml; +#[macro_use] extern crate serde_derive; + +#[derive(Debug, Serialize, Deserialize)] +pub struct Recipe { + pub name: String, + pub description: Option, + #[serde(default)] + pub modules: Vec, + #[serde(default)] + pub packages: Vec +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Modules { + pub name: String, + pub version: Option +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Packages { + pub name: String, + pub version: Option +} + +#[test] +fn both_ends() { + let recipe_works = toml::from_str::(r#" + name = "testing" + description = "example" + modules = [] + + [[packages]] + name = "base" + "#).unwrap(); + toml::to_string(&recipe_works).unwrap(); + + let recipe_fails = toml::from_str::(r#" + name = "testing" + description = "example" + packages = [] + + [[modules]] + name = "base" + "#).unwrap(); + + let recipe_toml = toml::Value::try_from(recipe_fails).unwrap(); + recipe_toml.to_string(); +} -- cgit v1.2.3