From 8e2359d3ab6ffdfc661d3a63188c36de57ffaa41 Mon Sep 17 00:00:00 2001 From: Richard Newman Date: Thu, 9 Feb 2017 17:12:55 -0800 Subject: [PATCH] Implement TypedValue::is_congruent_with and ::matches_type. r=jsantell --- core/src/lib.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/core/src/lib.rs b/core/src/lib.rs index 5f7709be..1054f895 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -48,6 +48,18 @@ pub enum TypedValue { } impl TypedValue { + /// Returns true if the provided type is `Some` and matches this value's type, or if the + /// provided type is `None`. + #[inline] + pub fn is_congruent_with>>(&self, t: T) -> bool { + t.into().map_or(true, |x| self.matches_type(x)) + } + + #[inline] + pub fn matches_type(&self, t: ValueType) -> bool { + self.value_type() == t + } + pub fn value_type(&self) -> ValueType { match self { &TypedValue::Ref(_) => ValueType::Ref, @@ -60,6 +72,15 @@ impl TypedValue { } } +#[test] +fn test_typed_value() { + assert!(TypedValue::Boolean(false).is_congruent_with(None)); + assert!(TypedValue::Boolean(false).is_congruent_with(ValueType::Boolean)); + assert!(!TypedValue::String("foo".to_string()).is_congruent_with(ValueType::Boolean)); + assert!(TypedValue::String("foo".to_string()).is_congruent_with(ValueType::String)); + assert!(TypedValue::String("foo".to_string()).is_congruent_with(None)); +} + /// A Mentat schema attribute has a value type and several other flags determining how assertions /// with the attribute are interpreted. ///