From 4927de7ac695bc6cbade48132be3758fbb82d632 Mon Sep 17 00:00:00 2001 From: Sebastian Schmidt Date: Mon, 4 Jul 2022 14:19:41 +0300 Subject: [PATCH] Implement `TryFrom` for all types a value can store. --- src/value/mod.rs | 73 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/src/value/mod.rs b/src/value/mod.rs index b5b14a4..05eaf50 100644 --- a/src/value/mod.rs +++ b/src/value/mod.rs @@ -1,4 +1,5 @@ use crate::error::{EvalexprError, EvalexprResult}; +use std::convert::TryFrom; mod display; pub mod value_type; @@ -193,6 +194,78 @@ impl From<()> for Value { } } +impl TryFrom for String { + type Error = EvalexprError; + + fn try_from(value: Value) -> Result { + if let Value::String(value) = value { + Ok(value) + } else { + Err(EvalexprError::ExpectedString { actual: value }) + } + } +} + +impl TryFrom for FloatType { + type Error = EvalexprError; + + fn try_from(value: Value) -> Result { + if let Value::Float(value) = value { + Ok(value) + } else { + Err(EvalexprError::ExpectedFloat { actual: value }) + } + } +} + +impl TryFrom for IntType { + type Error = EvalexprError; + + fn try_from(value: Value) -> Result { + if let Value::Int(value) = value { + Ok(value) + } else { + Err(EvalexprError::ExpectedInt { actual: value }) + } + } +} + +impl TryFrom for bool { + type Error = EvalexprError; + + fn try_from(value: Value) -> Result { + if let Value::Boolean(value) = value { + Ok(value) + } else { + Err(EvalexprError::ExpectedBoolean { actual: value }) + } + } +} + +impl TryFrom for TupleType { + type Error = EvalexprError; + + fn try_from(value: Value) -> Result { + if let Value::Tuple(value) = value { + Ok(value) + } else { + Err(EvalexprError::ExpectedTuple { actual: value }) + } + } +} + +impl TryFrom for () { + type Error = EvalexprError; + + fn try_from(value: Value) -> Result { + if let Value::Empty = value { + Ok(()) + } else { + Err(EvalexprError::ExpectedEmpty { actual: value }) + } + } +} + #[cfg(test)] mod tests { use crate::value::{TupleType, Value};