From 4983975e59f53365922999b1cb38248b2dce0013 Mon Sep 17 00:00:00 2001 From: Jeff Date: Thu, 28 Sep 2023 23:53:37 -0400 Subject: [PATCH] Improve addition implementation --- src/interface.rs | 18 +++++------------- src/value/mod.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 13 deletions(-) diff --git a/src/interface.rs b/src/interface.rs index f6b0f9a..8e48450 100644 --- a/src/interface.rs +++ b/src/interface.rs @@ -236,19 +236,11 @@ impl Operation { ) -> Result { 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?) } } diff --git a/src/value/mod.rs b/src/value/mod.rs index c89ccde..461eebe 100644 --- a/src/value/mod.rs +++ b/src/value/mod.rs @@ -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; + + 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 {