@@ -468,55 +468,42 @@ impl<T: Zero> Zero for ~T {
468
468
}
469
469
470
470
/// Saturating math operations
471
- pub trait Saturating : Int {
471
+ pub trait Saturating {
472
472
/// Saturating addition operator.
473
473
/// Returns a+b, saturating at the numeric bounds instead of overflowing.
474
+ fn saturating_add ( self , v : Self ) -> Self ;
475
+
476
+ /// Saturating subtraction operator.
477
+ /// Returns a-b, saturating at the numeric bounds instead of overflowing.
478
+ fn saturating_sub ( self , v : Self ) -> Self ;
479
+ }
480
+
481
+ impl < T : CheckedAdd +CheckedSub +Zero +Ord +Bounded > Saturating for T {
474
482
#[ inline]
475
- fn saturating_add ( self , v : Self ) -> Self {
476
- let x = self + v;
477
- if v >= Zero :: zero ( ) {
478
- if x < self {
479
- // overflow
480
- Bounded :: max_value :: < Self > ( )
481
- } else { x }
482
- } else {
483
- if x > self {
484
- // underflow
485
- Bounded :: min_value :: < Self > ( )
486
- } else { x }
483
+ fn saturating_add ( self , v : T ) -> T {
484
+ match self . checked_add ( & v) {
485
+ Some ( x) => x,
486
+ None => if v >= Zero :: zero ( ) {
487
+ Bounded :: max_value :: < T > ( )
488
+ } else {
489
+ Bounded :: min_value :: < T > ( )
490
+ }
487
491
}
488
492
}
489
493
490
- /// Saturating subtraction operator.
491
- /// Returns a-b, saturating at the numeric bounds instead of overflowing.
492
494
#[ inline]
493
- fn saturating_sub ( self , v : Self ) -> Self {
494
- let x = self - v;
495
- if v >= Zero :: zero ( ) {
496
- if x > self {
497
- // underflow
498
- Bounded :: min_value :: < Self > ( )
499
- } else { x }
500
- } else {
501
- if x < self {
502
- // overflow
503
- Bounded :: max_value :: < Self > ( )
504
- } else { x }
495
+ fn saturating_sub ( self , v : T ) -> T {
496
+ match self . checked_sub ( & v) {
497
+ Some ( x) => x,
498
+ None => if v >= Zero :: zero ( ) {
499
+ Bounded :: min_value :: < T > ( )
500
+ } else {
501
+ Bounded :: max_value :: < T > ( )
502
+ }
505
503
}
506
504
}
507
505
}
508
506
509
- impl Saturating for int { }
510
- impl Saturating for i8 { }
511
- impl Saturating for i16 { }
512
- impl Saturating for i32 { }
513
- impl Saturating for i64 { }
514
- impl Saturating for uint { }
515
- impl Saturating for u8 { }
516
- impl Saturating for u16 { }
517
- impl Saturating for u32 { }
518
- impl Saturating for u64 { }
519
-
520
507
pub trait CheckedAdd : Add < Self , Self > {
521
508
fn checked_add ( & self , v : & Self ) -> Option < Self > ;
522
509
}
0 commit comments