From 3db3ce22f5a140d8ac4d992444b98d71de5ccb41 Mon Sep 17 00:00:00 2001 From: Kevin Ballard Date: Mon, 5 Aug 2013 20:04:52 -0700 Subject: [PATCH] Update Iterator impls to use Saturating Replace hand-rolled saturation math with calls to Saturating. Fix one impl that didn't use saturating math. --- src/libstd/iterator.rs | 35 ++++++++++------------------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/src/libstd/iterator.rs b/src/libstd/iterator.rs index 0769aa6a7646..d71bc3156a56 100644 --- a/src/libstd/iterator.rs +++ b/src/libstd/iterator.rs @@ -18,7 +18,7 @@ implementing the `Iterator` trait. */ use cmp; -use num::{Zero, One}; +use num::{Zero, One, Saturating}; use option::{Option, Some, None}; use ops::{Add, Mul}; use cmp::Ord; @@ -863,15 +863,10 @@ impl, U: Iterator> Iterator for Chain { let (a_lower, a_upper) = self.a.size_hint(); let (b_lower, b_upper) = self.b.size_hint(); - let lower = if uint::max_value - a_lower < b_lower { - uint::max_value - } else { - a_lower + b_lower - }; + let lower = a_lower.saturating_add(b_lower); let upper = match (a_upper, b_upper) { - (Some(x), Some(y)) if uint::max_value - x < y => Some(uint::max_value), - (Some(x), Some(y)) => Some(x + y), + (Some(x), Some(y)) => Some(x.saturating_add(y)), _ => None }; @@ -895,12 +890,7 @@ for Chain { #[inline] fn indexable(&self) -> uint { let (a, b) = (self.a.indexable(), self.b.indexable()); - let total = a + b; - if total < a || total < b { - uint::max_value - } else { - total - } + a.saturating_add(b) } #[inline] @@ -1252,11 +1242,10 @@ impl> Iterator for Skip { fn size_hint(&self) -> (uint, Option) { let (lower, upper) = self.iter.size_hint(); - let lower = if lower >= self.n { lower - self.n } else { 0 }; + let lower = lower.saturating_sub(self.n); let upper = match upper { - Some(x) if x >= self.n => Some(x - self.n), - Some(_) => Some(0), + Some(x) => Some(x.saturating_sub(self.n)), None => None }; @@ -1267,12 +1256,7 @@ impl> Iterator for Skip { impl> RandomAccessIterator for Skip { #[inline] fn indexable(&self) -> uint { - let N = self.iter.indexable(); - if N < self.n { - 0 - } else { - N - self.n - } + self.iter.indexable().saturating_sub(self.n) } #[inline] @@ -1389,9 +1373,10 @@ impl<'self, A, T: Iterator, B, U: Iterator> Iterator for fn size_hint(&self) -> (uint, Option) { let (flo, fhi) = self.frontiter.map_default((0, Some(0)), |it| it.size_hint()); let (blo, bhi) = self.backiter.map_default((0, Some(0)), |it| it.size_hint()); + let lo = flo.saturating_add(blo); match (self.iter.size_hint(), fhi, bhi) { - ((0, Some(0)), Some(a), Some(b)) => (flo + blo, Some(a + b)), - _ => (flo + blo, None) + ((0, Some(0)), Some(a), Some(b)) => (lo, Some(a.saturating_add(b))), + _ => (lo, None) } } }