From 756007f438cee52a47f757447149c7744be3208a Mon Sep 17 00:00:00 2001 From: Gris Ge Date: Sat, 4 Jan 2025 16:53:11 +0800 Subject: [PATCH] Serializer should always produce YAML end with '\n' Signed-off-by: Gris Ge --- src/serializer.rs | 5 ++++- src/value.rs | 2 ++ tests/to_string.rs | 17 +++++++++++------ 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/serializer.rs b/src/serializer.rs index d898f80..11786dc 100644 --- a/src/serializer.rs +++ b/src/serializer.rs @@ -59,9 +59,12 @@ where ..Default::default() }; value.serialize(&mut serializer)?; - if serializer.output.ends_with("\n") { + if serializer.output.ends_with("\n\n") { serializer.output.pop(); } + if !serializer.output.ends_with("\n") { + serializer.output.push('\n'); + } Ok(serializer.output) } diff --git a/src/value.rs b/src/value.rs index 7e1761d..0b7053a 100644 --- a/src/value.rs +++ b/src/value.rs @@ -60,6 +60,8 @@ impl YamlValue { // The `as_str()` is called to get tag name of enum instead of // content. Ok(tag.name.as_str()) + } else if &self.data == &YamlValueData::Null { + Ok("") } else { Err(RmsdError::unexpected_yaml_node_type( format!("Expecting a string, but got {}", &self.data), diff --git a/tests/to_string.rs b/tests/to_string.rs index 5bf6f3f..ef34dae 100644 --- a/tests/to_string.rs +++ b/tests/to_string.rs @@ -25,7 +25,8 @@ fn test_struct_to_string() -> Result<(), RmsdError> { yaml_str, r#"uint_a: 129 str_b: abc -bool_c: false"# +bool_c: false +"# ); assert_eq!(rmsd_yaml::from_str::(&yaml_str)?, data); @@ -37,7 +38,7 @@ fn test_array_to_string() -> Result<(), RmsdError> { let data = vec![1u8, 2, 3, 4]; let yaml_str = rmsd_yaml::to_string_with_opt(&data, Default::default())?; - assert_eq!(yaml_str, "- 1\n- 2\n- 3\n- 4"); + assert_eq!(yaml_str, "- 1\n- 2\n- 3\n- 4\n"); assert_eq!(rmsd_yaml::from_str::>(&yaml_str)?, data); Ok(()) @@ -77,7 +78,8 @@ fn test_array_of_map() -> Result<(), RmsdError> { bool_c: false - uint_a: 128 str_b: abd - bool_c: true"# + bool_c: true +"# ); assert_eq!(rmsd_yaml::from_str::>(&yaml_str)?, data); @@ -108,7 +110,8 @@ uint_a: - 129 - 128 - 127 -str_b: abc"# +str_b: abc +"# ); assert_eq!(rmsd_yaml::from_str::(&yaml_str)?, data); @@ -132,7 +135,8 @@ fn test_nested_array() -> Result<(), RmsdError> { - - 5 - 6 - 7 - - 8"# + - 8 +"# ); assert_eq!(rmsd_yaml::from_str::(&yaml_str)?, data); @@ -171,7 +175,8 @@ bar: - 1 - 2 - 3 - - 4"# + - 4 +"# ); assert_eq!(rmsd_yaml::from_str::(&yaml_str)?, data);