From 2799cc7255d39dbb1450717c63909706dab8677e Mon Sep 17 00:00:00 2001 From: Michael Nelson Date: Mon, 31 Oct 2016 16:13:34 +1100 Subject: [PATCH 1/2] Add support for Saturating add and subtract. --- src/length.rs | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/src/length.rs b/src/length.rs index 8b0a2a5..2c03eaf 100644 --- a/src/length.rs +++ b/src/length.rs @@ -12,7 +12,7 @@ use scale_factor::ScaleFactor; use num::Zero; use heapsize::HeapSizeOf; -use num_traits::NumCast; +use num_traits::{NumCast, Saturating}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::cmp::Ordering; use std::ops::{Add, Sub, Mul, Div, Neg}; @@ -117,6 +117,18 @@ impl> SubAssign for Length { } } +// Saturating length + length and length - length. +impl Saturating for Length { + // type Output = Length; + fn saturating_add(self, other: Length) -> Length { + Length::new(self.get().saturating_add(other.get())) + } + + fn saturating_sub(self, other: Length) -> Length { + Length::new(self.get().saturating_sub(other.get())) + } +} + // length / length impl> Div> for Length { type Output = ScaleFactor; @@ -185,6 +197,7 @@ impl Zero for Length { #[cfg(test)] mod tests { use super::Length; + use num_traits::Saturating; use scale_factor::ScaleFactor; enum Inch {} @@ -237,6 +250,36 @@ mod tests { assert_eq!(negative_zero_feet.get(), 0.0); } + #[test] + fn test_add() { + let length1: Length = Length::new(250); + let length2: Length = Length::new(5); + + let result = length1 + length2; + + assert_eq!(result.get(), 255); + } + + #[test] + fn test_saturating_add() { + let length1: Length = Length::new(250); + let length2: Length = Length::new(6); + + let result = length1.saturating_add(length2); + + assert_eq!(result.get(), 255); + } + + #[test] + fn test_saturating_sub() { + let length1: Length = Length::new(5); + let length2: Length = Length::new(10); + + let result = length1.saturating_sub(length2); + + assert_eq!(result.get(), 0); + } + #[test] fn test_addassign() { let one_cm: Length = Length::new(10.0); From 72e9ac9a93fb372788c5b78b654a825da8b0f44a Mon Sep 17 00:00:00 2001 From: Michael Nelson Date: Sat, 19 Nov 2016 10:17:14 +1100 Subject: [PATCH 2/2] Remove commented out Output type. --- src/length.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/length.rs b/src/length.rs index 2c03eaf..0f7bf4e 100644 --- a/src/length.rs +++ b/src/length.rs @@ -119,7 +119,6 @@ impl> SubAssign for Length { // Saturating length + length and length - length. impl Saturating for Length { - // type Output = Length; fn saturating_add(self, other: Length) -> Length { Length::new(self.get().saturating_add(other.get())) }