1
0

Improve addition implementation

This commit is contained in:
Jeff 2023-09-28 23:53:37 -04:00
parent adbd69b17c
commit 4983975e59
2 changed files with 51 additions and 13 deletions

View File

@ -236,19 +236,11 @@ impl Operation {
) -> Result<Value> {
let left = self.left.run(context, &mut cursor, source)?;
let right = self.right.run(context, &mut cursor, source)?;
let result = match self.operator {
"+" => left + right,
_ => return Err(Error::CustomMessage("Operator not supported.".to_string())),
};
match self.operator {
"+" => {
let integer_result = left.as_int()? + right.as_int()?;
Ok(Value::Integer(integer_result))
}
"-" => {
let integer_result = left.as_int()? - right.as_int()?;
Ok(Value::Integer(integer_result))
}
_ => Ok(Value::Empty),
}
Ok(result?)
}
}

View File

@ -17,6 +17,7 @@ use std::{
convert::TryFrom,
fmt::{self, Display, Formatter},
marker::PhantomData,
ops::Add,
};
pub mod function;
@ -241,6 +242,51 @@ impl Value {
}
}
impl Add for Value {
type Output = Result<Value>;
fn add(self, right: Self) -> Self::Output {
match (self, right) {
(Value::String(left), Value::String(right)) => {
let concatenated = left + &right;
Ok(Value::String(concatenated))
}
(Value::String(string), other) | (other, Value::String(string)) => {
Err(Error::ExpectedString { actual: other })
}
(Value::Float(left), Value::Float(right)) => {
let addition = left + right;
Ok(Value::Float(addition))
}
(Value::Float(_), other) | (other, Value::Float(_)) => {
Err(Error::ExpectedFloat { actual: other })
}
(Value::Integer(left), Value::Integer(right)) => Ok(Value::Integer(left + right)),
(Value::Integer(_), other) | (other, Value::Integer(_)) => {
Err(Error::ExpectedInt { actual: other })
}
(Value::Boolean(_), Value::Boolean(_)) => todo!(),
(Value::Boolean(_), other) | (other, Value::Boolean(_)) => {
Err(Error::ExpectedBoolean { actual: other })
}
(Value::List(_), Value::List(_)) => todo!(),
(Value::List(_), other) | (other, Value::List(_)) => {
Err(Error::ExpectedList { actual: other })
}
(Value::Map(_), Value::Map(_)) => todo!(),
(Value::Map(_), other) | (other, Value::Map(_)) => {
Err(Error::ExpectedMap { actual: other })
}
(Value::Empty, Value::Empty) => Ok(Value::Empty),
_ => Err(Error::CustomMessage(
"Cannot add the given types.".to_string(),
)),
}
}
}
impl Eq for Value {}
impl PartialOrd for Value {