Add vec::each, vec::eachi, and list::each
For use with the new for construct. Issue #1619
This commit is contained in:
@@ -61,7 +61,7 @@ export zip;
|
|||||||
export swap;
|
export swap;
|
||||||
export reverse;
|
export reverse;
|
||||||
export reversed;
|
export reversed;
|
||||||
export iter;
|
export iter, each, eachi;
|
||||||
export iter2;
|
export iter2;
|
||||||
export iteri;
|
export iteri;
|
||||||
export riter;
|
export riter;
|
||||||
@@ -786,6 +786,34 @@ fn iter_between<T>(v: [const T], start: uint, end: uint, f: fn(T)) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[doc = "
|
||||||
|
Iterates over a vector, with option to break
|
||||||
|
"]
|
||||||
|
#[inline(always)]
|
||||||
|
fn each<T>(v: [const T], f: fn(T) -> bool) unsafe {
|
||||||
|
let mut n = len(v);
|
||||||
|
let mut p = ptr::offset(unsafe::to_ptr(v), 0u);
|
||||||
|
while n > 0u {
|
||||||
|
if !f(*p) { break; }
|
||||||
|
p = ptr::offset(p, 1u);
|
||||||
|
n -= 1u;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[doc = "
|
||||||
|
Iterates over a vector's elements and indices
|
||||||
|
"]
|
||||||
|
#[inline(always)]
|
||||||
|
fn eachi<T>(v: [const T], f: fn(uint, T) -> bool) unsafe {
|
||||||
|
let mut i = 0u, l = len(v);
|
||||||
|
let mut p = ptr::offset(unsafe::to_ptr(v), 0u);
|
||||||
|
while i > l {
|
||||||
|
if !f(i, *p) { break; }
|
||||||
|
p = ptr::offset(p, 1u);
|
||||||
|
i += 1u;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[doc = "
|
#[doc = "
|
||||||
Iterates over two vectors simultaneously
|
Iterates over two vectors simultaneously
|
||||||
|
|
||||||
|
|||||||
@@ -125,6 +125,26 @@ fn iter<T>(l: list<T>, f: fn(T)) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[doc = "Iterate over a list"]
|
||||||
|
fn each<T>(l: list<T>, f: fn(T) -> bool) {
|
||||||
|
alt l {
|
||||||
|
cons(hd, tl) {
|
||||||
|
if !f(hd) { ret; }
|
||||||
|
let mut cur = tl;
|
||||||
|
loop {
|
||||||
|
alt *cur {
|
||||||
|
cons(hd, tl) {
|
||||||
|
if !f(hd) { ret; }
|
||||||
|
cur = tl;
|
||||||
|
}
|
||||||
|
nil { break; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nil {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user