From d6d0b0f26d7bbf81b57f22b96d06195543f869bb Mon Sep 17 00:00:00 2001 From: "lincoln auster [they/them]" Date: Tue, 28 Sep 2021 23:06:37 -0600 Subject: [PATCH 1/2] introduce `or` function Similarly to `or` for Rust's options, this patch provides a way to 'override' the value of a Yaml node if it's some form of error. --- src/yaml.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/yaml.rs b/src/yaml.rs index 4bb70da..a6af0fd 100644 --- a/src/yaml.rs +++ b/src/yaml.rs @@ -280,6 +280,22 @@ impl Yaml { _ => None, } } + + /// If a value is null or otherwise bad (see variants), consume it and + /// replace it with a given value `other`. Otherwise, return self unchanged. + /// + /// ``` + /// use yaml_rust::yaml::Yaml; + /// + /// assert_eq!(Yaml::BadValue.or(Yaml::Integer(3)), Yaml::Integer(3)); + /// assert_eq!(Yaml::Integer(3).or(Yaml::BadValue), Yaml::Integer(3)); + /// ``` + pub fn or(self, other: Self) -> Self { + match self { + Yaml::BadValue | Yaml::Null => other, + this => this, + } + } } #[cfg_attr(feature = "cargo-clippy", allow(should_implement_trait))] @@ -736,4 +752,10 @@ subcommands3: let s = "[".repeat(10_000) + &"]".repeat(10_000); assert!(YamlLoader::load_from_str(&s).is_err()); } + + #[test] + fn test_or() { + assert_eq!(Yaml::Null.or(Yaml::Integer(3)), Yaml::Integer(3)); + assert_eq!(Yaml::Integer(3).or(Yaml::Integer(7)), Yaml::Integer(3)); + } } From af6f4ea8c808c0733c9ed41d5b460e998484a50f Mon Sep 17 00:00:00 2001 From: "lincoln auster [they/them]" Date: Fri, 1 Oct 2021 19:11:09 -0600 Subject: [PATCH 2/2] implement `borrowed_or` Allow the usage of `or` without consuming self. This can be useful for pipelines that maintain some sort of owned state. --- src/yaml.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/yaml.rs b/src/yaml.rs index a6af0fd..713fb95 100644 --- a/src/yaml.rs +++ b/src/yaml.rs @@ -296,6 +296,15 @@ impl Yaml { this => this, } } + + /// See `or` for behavior. This performs the same operations, but with + /// borrowed values for less linear pipelines. + pub fn borrowed_or<'a>(&'a self, other: &'a Self) -> &'a Self { + match self { + Yaml::BadValue | Yaml::Null => other, + this => this, + } + } } #[cfg_attr(feature = "cargo-clippy", allow(should_implement_trait))]