Skip to content
This repository has been archived by the owner on Mar 25, 2024. It is now read-only.

Commit

Permalink
handle old bool YAML keywords in serializer for backwards compatibili…
Browse files Browse the repository at this point in the history
…ty instead of the deserializer
  • Loading branch information
NiklasRosenstein committed Feb 22, 2024
1 parent d0bba85 commit f909910
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 25 deletions.
4 changes: 2 additions & 2 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -931,8 +931,8 @@ fn parse_null(scalar: &[u8]) -> Option<()> {

fn parse_bool(scalar: &str) -> Option<bool> {
match scalar {
"true" | "True" | "TRUE" | "on" | "ON" | "yes" | "YES" => Some(true),
"false" | "False" | "FALSE" | "off" | "OFF" | "no" | "NO" => Some(false),
"true" | "True" | "TRUE" => Some(true),
"false" | "False" | "FALSE" => Some(false),
_ => None,
}
}
Expand Down
23 changes: 13 additions & 10 deletions src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,16 +352,19 @@ where
}
}

let style = if value.contains('\n') {
ScalarStyle::Literal
} else {
let result = crate::de::visit_untagged_scalar(
InferScalarStyle,
value,
None,
libyaml::parser::ScalarStyle::Plain,
);
result.unwrap_or(ScalarStyle::Any)
let style = match value {
// Backwards compatibility with pre-YAML 1.2.2 spec for boolean keywords.
"on" | "ON" | "yes" | "YES" | "no" | "NO" | "off" | "OFF" => ScalarStyle::SingleQuoted,
_ if value.contains('\n') => ScalarStyle::Literal,
_ => {
let result = crate::de::visit_untagged_scalar(
InferScalarStyle,
value,
None,
libyaml::parser::ScalarStyle::Plain,
);
result.unwrap_or(ScalarStyle::Any)
}
};

self.emit_scalar(Scalar {
Expand Down
20 changes: 7 additions & 13 deletions tests/test_serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,22 +271,16 @@ fn test_string_escapes() {
}

#[test]
fn test_can_deser_bool_keywords_and_quote_as_strings() {
for (thing, yaml) in vec![
(true, "on"),
(false, "off"),
(true, "yes"),
(false, "no"),
(true, "true"),
(false, "false"),
] {
// Serializing YAML bool keywords to strings adds quotes.
fn test_bool_keywords_are_serialized_for_backwards_compatibility() {
for yaml in vec!["on", "off", "yes", "no"] {
// Serializing YAML bool keywords to strings adds quotes for compatibility with
// older YAML specs.
let formatted: String = serde_yaml::to_string(yaml).unwrap();
assert_eq!(formatted, format!("'{}'\n", yaml));

// YAML boolean keywords can be deserialized into bool.
let value: bool = serde_yaml::from_str(yaml).unwrap();
assert_eq!(thing, value);
// Old YAML boolean keywords can NOT be deserialized into bool.
let value: Result<bool, _> = serde_yaml::from_str(yaml);
assert!(value.is_err());
}
}

Expand Down

0 comments on commit f909910

Please sign in to comment.