about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2013-09-14 23:00:52 -0700
committerbors <bors@rust-lang.org>2013-09-14 23:00:52 -0700
commit36872e4180331e4a7f00329abe7972488ce216cf (patch)
tree0712d374de8cf52a7df5e2205f756d2a9015d943 /src/libstd
parentccadbd3b7c936dacab69856cc3963aad477c7f06 (diff)
parent48f61ecbf93740359b62ad5326e70759e738d9e6 (diff)
downloadrust-36872e4180331e4a7f00329abe7972488ce216cf.tar.gz
rust-36872e4180331e4a7f00329abe7972488ce216cf.zip
auto merge of #9203 : thestinger/rust/range_step, r=huonw
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/char.rs7
-rw-r--r--src/libstd/iter.rs58
-rw-r--r--src/libstd/num/int_macros.rs145
-rw-r--r--src/libstd/num/uint_macros.rs151
-rw-r--r--src/libstd/os.rs4
-rw-r--r--src/libstd/rand.rs27
-rw-r--r--src/libstd/trie.rs28
7 files changed, 64 insertions, 356 deletions
diff --git a/src/libstd/char.rs b/src/libstd/char.rs
index 3a01e5908d9..911d883f88a 100644
--- a/src/libstd/char.rs
+++ b/src/libstd/char.rs
@@ -12,7 +12,7 @@
 
 use cast::transmute;
 use option::{None, Option, Some};
-use i32;
+use iter::{Iterator, range_step};
 use str::StrSlice;
 use unicode::{derived_property, general_category, decompose};
 use to_str::ToStr;
@@ -286,15 +286,14 @@ pub fn escape_unicode(c: char, f: &fn(char)) {
         (c <= '\uffff') { f('u'); 4 }
         _               { f('U'); 8 }
     );
-    do i32::range_step(4 * (pad - 1), -1, -4) |offset| {
+    for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
         unsafe {
             match ((c as i32) >> offset) & 0xf {
                 i @ 0 .. 9 => { f(transmute('0' as i32 + i)); }
                 i => { f(transmute('a' as i32 + (i - 10))); }
             }
         }
-        true
-    };
+    }
 }
 
 ///
diff --git a/src/libstd/iter.rs b/src/libstd/iter.rs
index 22e8a1defbd..07d2aeac627 100644
--- a/src/libstd/iter.rs
+++ b/src/libstd/iter.rs
@@ -1790,17 +1790,17 @@ pub fn range_inclusive<A: Add<A, A> + Ord + Clone + One>(start: A, stop: A) -> R
     RangeInclusive{range: range(start, stop), done: false}
 }
 
-impl<A: Add<A, A> + Ord + Clone> Iterator<A> for RangeInclusive<A> {
+impl<A: Add<A, A> + Eq + Ord + Clone> Iterator<A> for RangeInclusive<A> {
     #[inline]
     fn next(&mut self) -> Option<A> {
         match self.range.next() {
             Some(x) => Some(x),
             None => {
-                if self.done {
-                    None
-                } else {
+                if !self.done && self.range.state == self.range.stop {
                     self.done = true;
                     Some(self.range.stop.clone())
+                } else {
+                    None
                 }
             }
         }
@@ -1829,11 +1829,11 @@ impl<A: Sub<A, A> + Integer + Ord + Clone> DoubleEndedIterator<A> for RangeInclu
             let result = self.range.stop.clone();
             self.range.stop = self.range.stop - self.range.one;
             Some(result)
-        } else if self.done {
-            None
-        } else {
+        } else if !self.done && self.range.state == self.range.stop {
             self.done = true;
             Some(self.range.stop.clone())
+        } else {
+            None
         }
     }
 }
@@ -1857,7 +1857,7 @@ pub fn range_step<A: CheckedAdd + Ord + Clone + Zero>(start: A, stop: A, step: A
 impl<A: CheckedAdd + Ord + Clone> Iterator<A> for RangeStep<A> {
     #[inline]
     fn next(&mut self) -> Option<A> {
-        if (self.rev && self.state > self.stop) || self.state < self.stop {
+        if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
             let result = self.state.clone();
             match self.state.checked_add(&self.step) {
                 Some(x) => self.state = x,
@@ -1891,22 +1891,14 @@ pub fn range_step_inclusive<A: CheckedAdd + Ord + Clone + Zero>(start: A, stop:
 impl<A: CheckedAdd + Ord + Clone + Eq> Iterator<A> for RangeStepInclusive<A> {
     #[inline]
     fn next(&mut self) -> Option<A> {
-        if !self.done {
-            if (self.rev && self.state > self.stop) || self.state < self.stop {
-                let result = self.state.clone();
-                match self.state.checked_add(&self.step) {
-                    Some(x) => self.state = x,
-                    None => self.done = true
-                }
-                Some(result)
-            } else {
-                if self.state == self.stop {
-                    self.done = true;
-                    Some(self.state.clone())
-                } else {
-                    None
-                }
+        if !self.done && ((self.rev && self.state >= self.stop) ||
+                          (!self.rev && self.state <= self.stop)) {
+            let result = self.state.clone();
+            match self.state.checked_add(&self.step) {
+                Some(x) => self.state = x,
+                None => self.done = true
             }
+            Some(result)
         } else {
             None
         }
@@ -2717,23 +2709,43 @@ mod tests {
     }
 
     #[test]
+    fn test_range() {
+        assert_eq!(range(0i, 5).collect::<~[int]>(), ~[0i, 1, 2, 3, 4]);
+        assert_eq!(range(0i, 5).invert().collect::<~[int]>(), ~[4, 3, 2, 1, 0]);
+        assert_eq!(range(200, -5).collect::<~[int]>(), ~[]);
+        assert_eq!(range(200, -5).invert().collect::<~[int]>(), ~[]);
+        assert_eq!(range(200, 200).collect::<~[int]>(), ~[]);
+        assert_eq!(range(200, 200).invert().collect::<~[int]>(), ~[]);
+    }
+
+    #[test]
     fn test_range_inclusive() {
         assert_eq!(range_inclusive(0i, 5).collect::<~[int]>(), ~[0i, 1, 2, 3, 4, 5]);
         assert_eq!(range_inclusive(0i, 5).invert().collect::<~[int]>(), ~[5i, 4, 3, 2, 1, 0]);
+        assert_eq!(range_inclusive(200, -5).collect::<~[int]>(), ~[]);
+        assert_eq!(range_inclusive(200, -5).invert().collect::<~[int]>(), ~[]);
+        assert_eq!(range_inclusive(200, 200).collect::<~[int]>(), ~[200]);
+        assert_eq!(range_inclusive(200, 200).invert().collect::<~[int]>(), ~[200]);
     }
 
     #[test]
     fn test_range_step() {
         assert_eq!(range_step(0i, 20, 5).collect::<~[int]>(), ~[0, 5, 10, 15]);
         assert_eq!(range_step(20i, 0, -5).collect::<~[int]>(), ~[20, 15, 10, 5]);
+        assert_eq!(range_step(20i, 0, -6).collect::<~[int]>(), ~[20, 14, 8, 2]);
         assert_eq!(range_step(200u8, 255, 50).collect::<~[u8]>(), ~[200u8, 250]);
+        assert_eq!(range_step(200, -5, 1).collect::<~[int]>(), ~[]);
+        assert_eq!(range_step(200, 200, 1).collect::<~[int]>(), ~[]);
     }
 
     #[test]
     fn test_range_step_inclusive() {
         assert_eq!(range_step_inclusive(0i, 20, 5).collect::<~[int]>(), ~[0, 5, 10, 15, 20]);
         assert_eq!(range_step_inclusive(20i, 0, -5).collect::<~[int]>(), ~[20, 15, 10, 5, 0]);
+        assert_eq!(range_step_inclusive(20i, 0, -6).collect::<~[int]>(), ~[20, 14, 8, 2]);
         assert_eq!(range_step_inclusive(200u8, 255, 50).collect::<~[u8]>(), ~[200u8, 250]);
+        assert_eq!(range_step_inclusive(200, -5, 1).collect::<~[int]>(), ~[]);
+        assert_eq!(range_step_inclusive(200, 200, 1).collect::<~[int]>(), ~[200]);
     }
 
     #[test]
diff --git a/src/libstd/num/int_macros.rs b/src/libstd/num/int_macros.rs
index ae2a56b835d..39f32c5ff42 100644
--- a/src/libstd/num/int_macros.rs
+++ b/src/libstd/num/int_macros.rs
@@ -41,101 +41,6 @@ impl CheckedDiv for $T {
     }
 }
 
-enum Range { Closed, HalfOpen }
-
-#[inline]
-///
-/// Iterate through a range with a given step value.
-///
-/// Let `term` denote the closed interval `[stop-step,stop]` if `r` is Closed;
-/// otherwise `term` denotes the half-open interval `[stop-step,stop)`.
-/// Iterates through the range `[x_0, x_1, ..., x_n]` where
-/// `x_j == start + step*j`, and `x_n` lies in the interval `term`.
-///
-/// If no such nonnegative integer `n` exists, then the iteration range
-/// is empty.
-///
-fn range_step_core(start: $T, stop: $T, step: $T, r: Range, it: &fn($T) -> bool) -> bool {
-    let mut i = start;
-    if step == 0 {
-        fail!(~"range_step called with step == 0");
-    } else if step == (1 as $T) { // elide bounds check to tighten loop
-        while i < stop {
-            if !it(i) { return false; }
-            // no need for overflow check;
-            // cannot have i + 1 > max_value because i < stop <= max_value
-            i += (1 as $T);
-        }
-    } else if step == (-1 as $T) { // elide bounds check to tighten loop
-        while i > stop {
-            if !it(i) { return false; }
-            // no need for underflow check;
-            // cannot have i - 1 < min_value because i > stop >= min_value
-            i -= (1 as $T);
-        }
-    } else if step > 0 { // ascending
-        while i < stop {
-            if !it(i) { return false; }
-            // avoiding overflow. break if i + step > max_value
-            if i > max_value - step { return true; }
-            i += step;
-        }
-    } else { // descending
-        while i > stop {
-            if !it(i) { return false; }
-            // avoiding underflow. break if i + step < min_value
-            if i < min_value - step { return true; }
-            i += step;
-        }
-    }
-    match r {
-        HalfOpen => return true,
-        Closed => return (i != stop || it(i))
-    }
-}
-
-#[inline]
-///
-/// Iterate through the range [`start`..`stop`) with a given step value.
-///
-/// Iterates through the range `[x_0, x_1, ..., x_n]` where
-/// * `x_i == start + step*i`, and
-/// * `n` is the greatest nonnegative integer such that `x_n < stop`
-///
-/// (If no such `n` exists, then the iteration range is empty.)
-///
-/// # Arguments
-///
-/// * `start` - lower bound, inclusive
-/// * `stop` - higher bound, exclusive
-///
-/// # Examples
-/// ~~~
-/// let mut sum = 0;
-/// for int::range(1, 5) |i| {
-///     sum += i;
-/// }
-/// assert!(sum == 10);
-/// ~~~
-///
-pub fn range_step(start: $T, stop: $T, step: $T, it: &fn($T) -> bool) -> bool {
-    range_step_core(start, stop, step, HalfOpen, it)
-}
-
-#[inline]
-///
-/// Iterate through a range with a given step value.
-///
-/// Iterates through the range `[x_0, x_1, ..., x_n]` where
-/// `x_i == start + step*i` and `x_n <= last < step + x_n`.
-///
-/// (If no such nonnegative integer `n` exists, then the iteration
-///  range is empty.)
-///
-pub fn range_step_inclusive(start: $T, last: $T, step: $T, it: &fn($T) -> bool) -> bool {
-    range_step_core(start, last, step, Closed, it)
-}
-
 impl Num for $T {}
 
 #[cfg(not(test))]
@@ -879,56 +784,6 @@ mod tests {
     }
 
     #[test]
-    fn test_ranges() {
-        let mut l = ~[];
-
-        do range_step(20,26,2) |i| {
-            l.push(i);
-            true
-        };
-        do range_step(36,30,-2) |i| {
-            l.push(i);
-            true
-        };
-        do range_step(max_value - 2, max_value, 2) |i| {
-            l.push(i);
-            true
-        };
-        do range_step(max_value - 3, max_value, 2) |i| {
-            l.push(i);
-            true
-        };
-        do range_step(min_value + 2, min_value, -2) |i| {
-            l.push(i);
-            true
-        };
-        do range_step(min_value + 3, min_value, -2) |i| {
-            l.push(i);
-            true
-        };
-        assert_eq!(l, ~[20,22,24,
-                        36,34,32,
-                        max_value-2,
-                        max_value-3,max_value-1,
-                        min_value+2,
-                        min_value+3,min_value+1]);
-
-        // None of the `fail`s should execute.
-        do range_step(10,0,1) |_i| {
-            fail!(~"unreachable");
-        };
-        do range_step(0,10,-1) |_i| {
-            fail!(~"unreachable");
-        };
-    }
-
-    #[test]
-    #[should_fail]
-    fn test_range_step_zero_step() {
-        do range_step(0,10,0) |_i| { true };
-    }
-
-    #[test]
     fn test_signed_checked_div() {
         assert_eq!(10i.checked_div(&2), Some(5));
         assert_eq!(5i.checked_div(&0), None);
diff --git a/src/libstd/num/uint_macros.rs b/src/libstd/num/uint_macros.rs
index 3deb7312b04..4c64efb9114 100644
--- a/src/libstd/num/uint_macros.rs
+++ b/src/libstd/num/uint_macros.rs
@@ -42,101 +42,6 @@ impl CheckedDiv for $T {
     }
 }
 
-enum Range { Closed, HalfOpen }
-
-#[inline]
-///
-/// Iterate through a range with a given step value.
-///
-/// Let `term` denote the closed interval `[stop-step,stop]` if `r` is Closed;
-/// otherwise `term` denotes the half-open interval `[stop-step,stop)`.
-/// Iterates through the range `[x_0, x_1, ..., x_n]` where
-/// `x_j == start + step*j`, and `x_n` lies in the interval `term`.
-///
-/// If no such nonnegative integer `n` exists, then the iteration range
-/// is empty.
-///
-fn range_step_core(start: $T, stop: $T, step: $T_SIGNED, r: Range, it: &fn($T) -> bool) -> bool {
-    let mut i = start;
-    if step == 0 {
-        fail!("range_step called with step == 0");
-    } else if step == (1 as $T_SIGNED) { // elide bounds check to tighten loop
-        while i < stop {
-            if !it(i) { return false; }
-            // no need for overflow check;
-            // cannot have i + 1 > max_value because i < stop <= max_value
-            i += (1 as $T);
-        }
-    } else if step == (-1 as $T_SIGNED) { // elide bounds check to tighten loop
-        while i > stop {
-            if !it(i) { return false; }
-            // no need for underflow check;
-            // cannot have i - 1 < min_value because i > stop >= min_value
-            i -= (1 as $T);
-        }
-    } else if step > 0 { // ascending
-        while i < stop {
-            if !it(i) { return false; }
-            // avoiding overflow. break if i + step > max_value
-            if i > max_value - (step as $T) { return true; }
-            i += step as $T;
-        }
-    } else { // descending
-        while i > stop {
-            if !it(i) { return false; }
-            // avoiding underflow. break if i + step < min_value
-            if i < min_value + ((-step) as $T) { return true; }
-            i -= -step as $T;
-        }
-    }
-    match r {
-        HalfOpen => return true,
-        Closed => return (i != stop || it(i))
-    }
-}
-
-#[inline]
-///
-/// Iterate through the range [`start`..`stop`) with a given step value.
-///
-/// Iterates through the range `[x_0, x_1, ..., x_n]` where
-/// - `x_i == start + step*i`, and
-/// - `n` is the greatest nonnegative integer such that `x_n < stop`
-///
-/// (If no such `n` exists, then the iteration range is empty.)
-///
-/// # Arguments
-///
-/// * `start` - lower bound, inclusive
-/// * `stop` - higher bound, exclusive
-///
-/// # Examples
-/// ~~~ {.rust}
-/// let nums = [1,2,3,4,5,6,7];
-///
-/// for uint::range_step(0, nums.len() - 1, 2) |i| {
-///     printfln!("%d & %d", nums[i], nums[i+1]);
-/// }
-/// ~~~
-///
-pub fn range_step(start: $T, stop: $T, step: $T_SIGNED, it: &fn($T) -> bool) -> bool {
-    range_step_core(start, stop, step, HalfOpen, it)
-}
-
-#[inline]
-///
-/// Iterate through a range with a given step value.
-///
-/// Iterates through the range `[x_0, x_1, ..., x_n]` where
-/// `x_i == start + step*i` and `x_n <= last < step + x_n`.
-///
-/// (If no such nonnegative integer `n` exists, then the iteration
-///  range is empty.)
-///
-pub fn range_step_inclusive(start: $T, last: $T, step: $T_SIGNED, it: &fn($T) -> bool) -> bool {
-    range_step_core(start, last, step, Closed, it)
-}
-
 impl Num for $T {}
 
 #[cfg(not(test))]
@@ -654,62 +559,6 @@ mod tests {
     }
 
     #[test]
-    pub fn test_ranges() {
-        let mut l = ~[];
-
-        do range_step(20,26,2) |i| {
-            l.push(i);
-            true
-        };
-        do range_step(36,30,-2) |i| {
-            l.push(i);
-            true
-        };
-        do range_step(max_value - 2, max_value, 2) |i| {
-            l.push(i);
-            true
-        };
-        do range_step(max_value - 3, max_value, 2) |i| {
-            l.push(i);
-            true
-        };
-        do range_step(min_value + 2, min_value, -2) |i| {
-            l.push(i);
-            true
-        };
-        do range_step(min_value + 3, min_value, -2) |i| {
-            l.push(i);
-            true
-        };
-
-        assert_eq!(l, ~[20,22,24,
-                        36,34,32,
-                        max_value-2,
-                        max_value-3,max_value-1,
-                        min_value+2,
-                        min_value+3,min_value+1]);
-
-        // None of the `fail`s should execute.
-        do range_step(10,0,1) |_i| {
-            fail!("unreachable");
-        };
-        do range_step(0,1,-10) |_i| {
-            fail!("unreachable");
-        };
-    }
-
-    #[test]
-    #[should_fail]
-    fn test_range_step_zero_step_up() {
-        do range_step(0,10,0) |_i| { true };
-    }
-    #[test]
-    #[should_fail]
-    fn test_range_step_zero_step_down() {
-        do range_step(0,-10,0) |_i| { true };
-    }
-
-    #[test]
     fn test_unsigned_checked_div() {
         assert_eq!(10u.checked_div(&2), Some(5));
         assert_eq!(5u.checked_div(&0), None);
diff --git a/src/libstd/os.rs b/src/libstd/os.rs
index aeeae207204..5269eca888a 100644
--- a/src/libstd/os.rs
+++ b/src/libstd/os.rs
@@ -1895,8 +1895,8 @@ mod tests {
         setenv("USERPROFILE", "/home/PaloAlto");
         assert_eq!(os::homedir(), Some(Path("/home/MountainView")));
 
-        oldhome.iter().advance(|s| { setenv("HOME", *s); true });
-        olduserprofile.iter().advance(|s| { setenv("USERPROFILE", *s); true });
+        for s in oldhome.iter() { setenv("HOME", *s) }
+        for s in olduserprofile.iter() { setenv("USERPROFILE", *s) }
     }
 
     #[test]
diff --git a/src/libstd/rand.rs b/src/libstd/rand.rs
index 813901207bb..1330096ee36 100644
--- a/src/libstd/rand.rs
+++ b/src/libstd/rand.rs
@@ -48,7 +48,7 @@ use clone::Clone;
 use cmp;
 use container::Container;
 use int;
-use iter::{Iterator, range};
+use iter::{Iterator, range, range_step};
 use local_data;
 use num;
 use prelude::*;
@@ -748,7 +748,7 @@ impl IsaacRng {
         if use_rsl {
             macro_rules! memloop (
                 ($arr:expr) => {{
-                    do u32::range_step(0, RAND_SIZE, 8) |i| {
+                    for i in range_step(0u32, RAND_SIZE, 8) {
                         a+=$arr[i  ]; b+=$arr[i+1];
                         c+=$arr[i+2]; d+=$arr[i+3];
                         e+=$arr[i+4]; f+=$arr[i+5];
@@ -758,22 +758,20 @@ impl IsaacRng {
                         self.mem[i+2]=c; self.mem[i+3]=d;
                         self.mem[i+4]=e; self.mem[i+5]=f;
                         self.mem[i+6]=g; self.mem[i+7]=h;
-                        true
-                    };
+                    }
                 }}
             );
 
             memloop!(self.rsl);
             memloop!(self.mem);
         } else {
-            do u32::range_step(0, RAND_SIZE, 8) |i| {
+            for i in range_step(0u32, RAND_SIZE, 8) {
                 mix!();
                 self.mem[i  ]=a; self.mem[i+1]=b;
                 self.mem[i+2]=c; self.mem[i+3]=d;
                 self.mem[i+4]=e; self.mem[i+5]=f;
                 self.mem[i+6]=g; self.mem[i+7]=h;
-                true
-            };
+            }
         }
 
         self.isaac();
@@ -794,7 +792,7 @@ impl IsaacRng {
         });
         macro_rules! rngstep(
             ($j:expr, $shift:expr) => {{
-                let base = base + $j;
+                let base = $j;
                 let mix = if $shift < 0 {
                     a >> -$shift as uint
                 } else {
@@ -813,13 +811,12 @@ impl IsaacRng {
 
         let r = [(0, MIDPOINT), (MIDPOINT, 0)];
         for &(mr_offset, m2_offset) in r.iter() {
-            do uint::range_step(0, MIDPOINT, 4) |base| {
-                rngstep!(0, 13);
-                rngstep!(1, -6);
-                rngstep!(2, 2);
-                rngstep!(3, -16);
-                true
-            };
+            for i in range_step(0u, MIDPOINT, 4) {
+                rngstep!(i + 0, 13);
+                rngstep!(i + 1, -6);
+                rngstep!(i + 2, 2);
+                rngstep!(i + 3, -16);
+            }
         }
 
         self.a = a;
diff --git a/src/libstd/trie.rs b/src/libstd/trie.rs
index 32797216376..88a953a1601 100644
--- a/src/libstd/trie.rs
+++ b/src/libstd/trie.rs
@@ -520,6 +520,7 @@ pub fn check_integrity<T>(trie: &TrieNode<T>) {
 mod test_map {
     use super::*;
     use prelude::*;
+    use iter::range_step;
     use uint;
 
     #[test]
@@ -538,21 +539,19 @@ mod test_map {
     #[test]
     fn test_step() {
         let mut trie = TrieMap::new();
-        let n = 300;
+        let n = 300u;
 
-        do uint::range_step(1, n, 2) |x| {
+        for x in range_step(1u, n, 2) {
             assert!(trie.insert(x, x + 1));
             assert!(trie.contains_key(&x));
             check_integrity(&trie.root);
-            true
-        };
+        }
 
-        do uint::range_step(0, n, 2) |x| {
+        for x in range_step(0u, n, 2) {
             assert!(!trie.contains_key(&x));
             assert!(trie.insert(x, x + 1));
             check_integrity(&trie.root);
-            true
-        };
+        }
 
         for x in range(0u, n) {
             assert!(trie.contains_key(&x));
@@ -560,19 +559,17 @@ mod test_map {
             check_integrity(&trie.root);
         }
 
-        do uint::range_step(1, n, 2) |x| {
+        for x in range_step(1u, n, 2) {
             assert!(trie.remove(&x));
             assert!(!trie.contains_key(&x));
             check_integrity(&trie.root);
-            true
-        };
+        }
 
-        do uint::range_step(0, n, 2) |x| {
+        for x in range_step(0u, n, 2) {
             assert!(trie.contains_key(&x));
             assert!(!trie.insert(x, x + 1));
             check_integrity(&trie.root);
-            true
-        };
+        }
     }
 
     #[test]
@@ -715,11 +712,10 @@ mod test_map {
         let value = 42u;
 
         let mut map : TrieMap<uint> = TrieMap::new();
-        do uint::range_step(0u, last, step as int) |x| {
+        for x in range_step(0u, last, step) {
             assert!(x % step == 0);
             map.insert(x, value);
-            true
-        };
+        }
 
         for i in range(0u, last - step) {
             let mut lb = map.lower_bound_iter(i);