Implement TryFrom<Value> for all types a value can store.

This commit is contained in:
Sebastian Schmidt 2022-07-04 14:19:41 +03:00
parent e35a7e556a
commit 4927de7ac6

View File

@ -1,4 +1,5 @@
use crate::error::{EvalexprError, EvalexprResult}; use crate::error::{EvalexprError, EvalexprResult};
use std::convert::TryFrom;
mod display; mod display;
pub mod value_type; pub mod value_type;
@ -193,6 +194,78 @@ impl From<()> for Value {
} }
} }
impl TryFrom<Value> for String {
type Error = EvalexprError;
fn try_from(value: Value) -> Result<Self, Self::Error> {
if let Value::String(value) = value {
Ok(value)
} else {
Err(EvalexprError::ExpectedString { actual: value })
}
}
}
impl TryFrom<Value> for FloatType {
type Error = EvalexprError;
fn try_from(value: Value) -> Result<Self, Self::Error> {
if let Value::Float(value) = value {
Ok(value)
} else {
Err(EvalexprError::ExpectedFloat { actual: value })
}
}
}
impl TryFrom<Value> for IntType {
type Error = EvalexprError;
fn try_from(value: Value) -> Result<Self, Self::Error> {
if let Value::Int(value) = value {
Ok(value)
} else {
Err(EvalexprError::ExpectedInt { actual: value })
}
}
}
impl TryFrom<Value> for bool {
type Error = EvalexprError;
fn try_from(value: Value) -> Result<Self, Self::Error> {
if let Value::Boolean(value) = value {
Ok(value)
} else {
Err(EvalexprError::ExpectedBoolean { actual: value })
}
}
}
impl TryFrom<Value> for TupleType {
type Error = EvalexprError;
fn try_from(value: Value) -> Result<Self, Self::Error> {
if let Value::Tuple(value) = value {
Ok(value)
} else {
Err(EvalexprError::ExpectedTuple { actual: value })
}
}
}
impl TryFrom<Value> for () {
type Error = EvalexprError;
fn try_from(value: Value) -> Result<Self, Self::Error> {
if let Value::Empty = value {
Ok(())
} else {
Err(EvalexprError::ExpectedEmpty { actual: value })
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::value::{TupleType, Value}; use crate::value::{TupleType, Value};