Implement TryFrom<Value>
for all types a value can store.
This commit is contained in:
parent
e35a7e556a
commit
4927de7ac6
@ -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<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)]
|
||||
mod tests {
|
||||
use crate::value::{TupleType, Value};
|
||||
|
Loading…
Reference in New Issue
Block a user