Fix displaying empty arrays

Closes #145
This commit is contained in:
Alex Crichton 2017-02-11 09:13:28 -08:00
parent 7b50680c7d
commit 2fd12e72d8
2 changed files with 55 additions and 8 deletions

View file

@ -366,21 +366,19 @@ impl ser::Serialize for Value {
// Be sure to visit non-tables first (and also non // Be sure to visit non-tables first (and also non
// array-of-tables) as all keys must be emitted first. // array-of-tables) as all keys must be emitted first.
for (k, v) in t { for (k, v) in t {
if !v.is_array() && !v.is_table() { if !v.is_table() && !v.is_array() ||
map.serialize_key(k)?; (v.as_array().map(|a| a.len() == 0).unwrap_or(false)) {
map.serialize_value(v)?; map.serialize_entry(k, v)?;
} }
} }
for (k, v) in t { for (k, v) in t {
if v.is_array() { if v.as_array().map(|a| a.len() > 0).unwrap_or(false) {
map.serialize_key(k)?; map.serialize_entry(k, v)?;
map.serialize_value(v)?;
} }
} }
for (k, v) in t { for (k, v) in t {
if v.is_table() { if v.is_table() {
map.serialize_key(k)?; map.serialize_entry(k, v)?;
map.serialize_value(v)?;
} }
} }
map.end() map.end()

49
tests/display-tricky.rs Normal file
View file

@ -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<String>,
#[serde(default)]
pub modules: Vec<Modules>,
#[serde(default)]
pub packages: Vec<Packages>
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Modules {
pub name: String,
pub version: Option<String>
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Packages {
pub name: String,
pub version: Option<String>
}
#[test]
fn both_ends() {
let recipe_works = toml::from_str::<Recipe>(r#"
name = "testing"
description = "example"
modules = []
[[packages]]
name = "base"
"#).unwrap();
toml::to_string(&recipe_works).unwrap();
let recipe_fails = toml::from_str::<Recipe>(r#"
name = "testing"
description = "example"
packages = []
[[modules]]
name = "base"
"#).unwrap();
let recipe_toml = toml::Value::try_from(recipe_fails).unwrap();
recipe_toml.to_string();
}