From 5ba5dfa6e64e3a8dbc2ea55e6b86b787ee395fa1 Mon Sep 17 00:00:00 2001 From: "lincoln auster [they/them]" Date: Tue, 28 Sep 2021 23:06:37 -0600 Subject: [PATCH] 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. --- saphyr/src/yaml.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/saphyr/src/yaml.rs b/saphyr/src/yaml.rs index 0d02f34..a6dc1f0 100644 --- a/saphyr/src/yaml.rs +++ b/saphyr/src/yaml.rs @@ -383,6 +383,23 @@ impl Yaml { pub fn into_f64(self) -> Option { self.as_f64() } + + /// 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_rust2::yaml::Yaml; + /// + /// assert_eq!(Yaml::BadValue.or(Yaml::Integer(3)), Yaml::Integer(3)); + /// assert_eq!(Yaml::Integer(3).or(Yaml::BadValue), Yaml::Integer(3)); + /// ``` + #[must_use] + pub fn or(self, other: Self) -> Self { + match self { + Yaml::BadValue | Yaml::Null => other, + this => this, + } + } } #[cfg_attr(feature = "cargo-clippy", allow(clippy::should_implement_trait))] @@ -490,7 +507,7 @@ impl Iterator for YamlIter { #[cfg(test)] mod test { - use super::YamlDecoder; + use super::{Yaml, YamlDecoder}; #[test] fn test_read_bom() { @@ -573,4 +590,10 @@ c: [1, 2] assert_eq!(doc["c"][1].as_i64().unwrap(), 2i64); assert!(doc["d"][0].is_badvalue()); } + + #[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)); + } }