Skip to content

Commit

Permalink
Serializer should always produce YAML end with '\n'
Browse files Browse the repository at this point in the history
Signed-off-by: Gris Ge <[email protected]>
  • Loading branch information
cathay4t committed Jan 4, 2025
1 parent 8436d46 commit 756007f
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
5 changes: 4 additions & 1 deletion src/serializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
2 changes: 2 additions & 0 deletions src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
17 changes: 11 additions & 6 deletions tests/to_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<FooTest>(&yaml_str)?, data);
Expand All @@ -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::<Vec<u8>>(&yaml_str)?, data);
Ok(())
Expand Down Expand Up @@ -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::<Vec<FooTest>>(&yaml_str)?, data);
Expand Down Expand Up @@ -108,7 +110,8 @@ uint_a:
- 129
- 128
- 127
str_b: abc"#
str_b: abc
"#
);

assert_eq!(rmsd_yaml::from_str::<FooTest>(&yaml_str)?, data);
Expand All @@ -132,7 +135,8 @@ fn test_nested_array() -> Result<(), RmsdError> {
- - 5
- 6
- 7
- 8"#
- 8
"#
);

assert_eq!(rmsd_yaml::from_str::<FooTest>(&yaml_str)?, data);
Expand Down Expand Up @@ -171,7 +175,8 @@ bar:
- 1
- 2
- 3
- 4"#
- 4
"#
);

assert_eq!(rmsd_yaml::from_str::<FooTest>(&yaml_str)?, data);
Expand Down

0 comments on commit 756007f

Please sign in to comment.