From 384dae69f5f4a6e26fe9db5c264b0013015b892b Mon Sep 17 00:00:00 2001 From: Aravinth Manivannan Date: Wed, 18 Sep 2024 14:05:04 +0530 Subject: [PATCH] feat: impl Add for Price --- src/types/currency.rs | 78 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/src/types/currency.rs b/src/types/currency.rs index c476512..e005242 100644 --- a/src/types/currency.rs +++ b/src/types/currency.rs @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: AGPL-3.0-or-later -use std::str::FromStr; +use std::{ops::Add, str::FromStr}; use async_trait::async_trait; use cqrs_es::Aggregate; @@ -62,6 +62,16 @@ impl Price { } } +impl Add for Price { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { + let self_minor = self.major_as_minor() + self.minor; + let rhs_minor = rhs.major_as_minor() + rhs.minor; + + Self::from_minor(self_minor + rhs_minor, self.currency) + } +} + #[cfg(test)] mod tests { use super::*; @@ -110,4 +120,70 @@ mod tests { } ); } + + #[test] + fn test_price_add() { + let a = Price { + minor: 10, + major: 100, + currency: Currency::INR, + }; + + let b = Price { + minor: 1, + major: 200, + currency: Currency::INR, + }; + + assert_eq!( + a + b, + Price { + minor: 11, + major: 300, + currency: Currency::INR + } + ); + } + + #[test] + fn test_price_add_zero() { + let a = Price { + minor: 0, + major: 0, + currency: Currency::INR, + }; + + assert_eq!( + a.clone() + a, + Price { + minor: 0, + major: 0, + currency: Currency::INR + } + ); + } + + #[test] + fn test_price_add_overflow() { + let a = Price { + minor: 80, + major: 100, + currency: Currency::INR, + }; + + let b = Price { + minor: 80, + major: 200, + currency: Currency::INR, + }; + + assert_eq!( + a + b, + Price { + minor: 60, + major: 301, + currency: Currency::INR + } + ); + } }