Skip to content

Commit 83e3c82

Browse files
huonwcatamorphism
authored andcommitted
libcore: Add range_step and range_rev functions.
Closes #1817
1 parent e4e5d98 commit 83e3c82

File tree

2 files changed

+53
-10
lines changed

2 files changed

+53
-10
lines changed

src/libcore/int-template.rs

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,14 +109,36 @@ pub pure fn is_nonnegative(x: T) -> bool { x >= 0 as T }
109109
* ~~~
110110
*/
111111
#[inline(always)]
112-
pub pure fn range(lo: T, hi: T, it: fn(T) -> bool) {
113-
let mut i = lo;
114-
while i < hi {
115-
if !it(i) { break }
116-
i += 1 as T;
112+
/// Iterate over the range [`start`,`start`+`step`..`stop`)
113+
pub pure fn range_step(start: T, stop: T, step: T, it: fn(T) -> bool) {
114+
let mut i = start;
115+
if step == 0 {
116+
fail ~"range_step called with step == 0";
117+
} else if step > 0 { // ascending
118+
while i < stop {
119+
if !it(i) { break }
120+
i += step;
121+
}
122+
} else { // descending
123+
while i > stop {
124+
if !it(i) { break }
125+
i += step;
126+
}
117127
}
118128
}
119129

130+
#[inline(always)]
131+
/// Iterate over the range [`lo`..`hi`)
132+
pub pure fn range(lo: T, hi: T, it: fn(T) -> bool) {
133+
range_step(lo, hi, 1 as T, it);
134+
}
135+
136+
#[inline(always)]
137+
/// Iterate over the range [`hi`..`lo`)
138+
pub pure fn range_rev(hi: T, lo: T, it: fn(T) -> bool) {
139+
range_step(hi, lo, -1 as T, it);
140+
}
141+
120142
/// Computes the bitwise complement
121143
#[inline(always)]
122144
pub pure fn compl(i: T) -> T {

src/libcore/uint-template.rs

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,14 +68,35 @@ pub pure fn is_nonpositive(x: T) -> bool { x <= 0 as T }
6868
#[inline(always)]
6969
pub pure fn is_nonnegative(x: T) -> bool { x >= 0 as T }
7070

71+
#[inline(always)]
72+
/// Iterate over the range [`start`,`start`+`step`..`stop`)
73+
pub pure fn range_step(start: T, stop: T, step: T, it: fn(T) -> bool) {
74+
let mut i = start;
75+
if step == 0 {
76+
fail ~"range_step called with step == 0";
77+
} else if step > 0 { // ascending
78+
while i < stop {
79+
if !it(i) { break }
80+
i += step;
81+
}
82+
} else { // descending
83+
while i > stop {
84+
if !it(i) { break }
85+
i += step;
86+
}
87+
}
88+
}
89+
7190
#[inline(always)]
7291
/// Iterate over the range [`lo`..`hi`)
7392
pub pure fn range(lo: T, hi: T, it: fn(T) -> bool) {
74-
let mut i = lo;
75-
while i < hi {
76-
if !it(i) { break }
77-
i += 1 as T;
78-
}
93+
range_step(lo, hi, 1 as T, it);
94+
}
95+
96+
#[inline(always)]
97+
/// Iterate over the range [`hi`..`lo`)
98+
pub pure fn range_rev(hi: T, lo: T, it: fn(T) -> bool) {
99+
range_step(hi, lo, -1 as T, it);
79100
}
80101

81102
/// Computes the bitwise complement

0 commit comments

Comments
 (0)