From 027e8be26a25584fb75dbdd0321461313a3a37ce Mon Sep 17 00:00:00 2001 From: Christopher Armstrong Date: Sat, 23 Dec 2017 17:05:40 -0600 Subject: [PATCH] implement Saturating when the backend type supports Saturating. Fixes #35. --- src/system.rs | 14 ++++++++++++++ src/tests.rs | 29 ++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/system.rs b/src/system.rs index 6e4a8b39..27fe09bc 100644 --- a/src/system.rs +++ b/src/system.rs @@ -839,6 +839,20 @@ macro_rules! system { } } + impl $crate::num::Saturating for Quantity + where + D: Dimension + ?Sized, + U: Units + ?Sized, + V: $crate::num::Saturating + $crate::num::Num + $crate::Conversion, + { + fn saturating_add(self, v: Self) -> Self { + Quantity {value: self.value.saturating_add(v.value), ..self} + } + fn saturating_sub(self, v: Self) -> Self { + Quantity {value: self.value.saturating_sub(v.value), ..self} + } + } + impl $crate::num::Zero for Quantity where D: Dimension + ?Sized, diff --git a/src/tests.rs b/src/tests.rs index 21452424..fce552ff 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -3,7 +3,7 @@ use self::mass::kilogram; #[allow(unused_imports)] use {Conversion, ConversionFactor}; #[allow(unused_imports)] -use num::{Float, FromPrimitive, One, Signed, Zero}; +use num::{Float, FromPrimitive, One, Saturating, Signed, Zero}; use quickcheck::TestResult; use lib::fmt::Debug; use lib::marker::PhantomData; @@ -379,6 +379,33 @@ mod quantity_macro { } mod system_macro { + + mod int { + storage_types! { + types: PrimInt, BigInt, BigUint; + + use tests::*; + + Q!(tests, V); + + quickcheck! { + #[allow(trivial_casts)] + fn saturating_add(l: A, r: A) -> bool { + Test::eq(&(l.saturating_add(*r)), + &(Length::new::((*l).clone()) + .saturating_add(Length::new::((*r).clone())).get(meter))) + } + + #[allow(trivial_casts)] + fn saturating_sub(l: A, r: A) -> bool { + Test::eq(&(l.saturating_sub(*r)), + &(Length::new::((*l).clone()) + .saturating_sub(Length::new::((*r).clone())).get(meter))) + } + } + } + } + storage_types! { use tests::*;