|
1 | | -use core::num::Wrapping; |
| 1 | +use core::num::{Saturating, Wrapping}; |
2 | 2 | use core::ops::{Add, Mul}; |
3 | 3 |
|
4 | 4 | /// Defines an additive identity element for `Self`. |
|
95 | 95 | const ZERO: Self = Wrapping(T::ZERO); |
96 | 96 | } |
97 | 97 |
|
| 98 | +impl<T: Zero> Zero for Saturating<T> |
| 99 | +where |
| 100 | + Saturating<T>: Add<Output = Saturating<T>>, |
| 101 | +{ |
| 102 | + fn is_zero(&self) -> bool { |
| 103 | + self.0.is_zero() |
| 104 | + } |
| 105 | + |
| 106 | + fn set_zero(&mut self) { |
| 107 | + self.0.set_zero(); |
| 108 | + } |
| 109 | + |
| 110 | + fn zero() -> Self { |
| 111 | + Saturating(T::zero()) |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +impl<T: ConstZero> ConstZero for Saturating<T> |
| 116 | +where |
| 117 | + Saturating<T>: Add<Output = Saturating<T>>, |
| 118 | +{ |
| 119 | + const ZERO: Self = Saturating(T::ZERO); |
| 120 | +} |
| 121 | + |
98 | 122 | /// Defines a multiplicative identity element for `Self`. |
99 | 123 | /// |
100 | 124 | /// # Laws |
@@ -196,6 +220,26 @@ where |
196 | 220 | const ONE: Self = Wrapping(T::ONE); |
197 | 221 | } |
198 | 222 |
|
| 223 | +impl<T: One> One for Saturating<T> |
| 224 | +where |
| 225 | + Saturating<T>: Mul<Output = Saturating<T>>, |
| 226 | +{ |
| 227 | + fn set_one(&mut self) { |
| 228 | + self.0.set_one(); |
| 229 | + } |
| 230 | + |
| 231 | + fn one() -> Self { |
| 232 | + Saturating(T::one()) |
| 233 | + } |
| 234 | +} |
| 235 | + |
| 236 | +impl<T: ConstOne> ConstOne for Saturating<T> |
| 237 | +where |
| 238 | + Saturating<T>: Mul<Output = Saturating<T>>, |
| 239 | +{ |
| 240 | + const ONE: Self = Saturating(T::ONE); |
| 241 | +} |
| 242 | + |
199 | 243 | // Some helper functions provided for backwards compatibility. |
200 | 244 |
|
201 | 245 | /// Returns the additive identity, `0`. |
@@ -236,3 +280,30 @@ fn wrapping_is_one() { |
236 | 280 | fn require_one<T: One>(_: &T) {} |
237 | 281 | require_one(&Wrapping(42)); |
238 | 282 | } |
| 283 | + |
| 284 | +#[test] |
| 285 | +fn saturating_identities() { |
| 286 | + macro_rules! test_saturating_identities { |
| 287 | + ($($t:ty)+) => { |
| 288 | + $( |
| 289 | + assert_eq!(zero::<$t>(), zero::<Saturating<$t>>().0); |
| 290 | + assert_eq!(one::<$t>(), one::<Saturating<$t>>().0); |
| 291 | + assert_eq!((0 as $t).is_zero(), Saturating(0 as $t).is_zero()); |
| 292 | + assert_eq!((1 as $t).is_zero(), Saturating(1 as $t).is_zero()); |
| 293 | + )+ |
| 294 | + }; |
| 295 | + } |
| 296 | + |
| 297 | + test_saturating_identities!(isize i8 i16 i32 i64 usize u8 u16 u32 u64); |
| 298 | +} |
| 299 | + |
| 300 | +#[test] |
| 301 | +fn saturating_is_zero() { |
| 302 | + fn require_zero<T: Zero>(_: &T) {} |
| 303 | + require_zero(&Saturating(42)); |
| 304 | +} |
| 305 | +#[test] |
| 306 | +fn saturating_is_one() { |
| 307 | + fn require_one<T: One>(_: &T) {} |
| 308 | + require_one(&Saturating(42)); |
| 309 | +} |
0 commit comments