diff --git a/src/length.rs b/src/length.rs index 8b0a2a5..0f7bf4e 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,17 @@ impl> SubAssign for Length { } } +// Saturating length + length and length - length. +impl Saturating for 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 +196,7 @@ impl Zero for Length { #[cfg(test)] mod tests { use super::Length; + use num_traits::Saturating; use scale_factor::ScaleFactor; enum Inch {} @@ -237,6 +249,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);