Skip to content

Commit eec6383

Browse files
committed
Add vec::each, vec::eachi, and list::each
For use with the new for construct. Issue #1619
1 parent 064f82d commit eec6383

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/libcore/vec.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ export zip;
6161
export swap;
6262
export reverse;
6363
export reversed;
64-
export iter;
64+
export iter, each, eachi;
6565
export iter2;
6666
export iteri;
6767
export riter;
@@ -786,6 +786,34 @@ fn iter_between<T>(v: [const T], start: uint, end: uint, f: fn(T)) {
786786
}
787787
}
788788

789+
#[doc = "
790+
Iterates over a vector, with option to break
791+
"]
792+
#[inline(always)]
793+
fn each<T>(v: [const T], f: fn(T) -> bool) unsafe {
794+
let mut n = len(v);
795+
let mut p = ptr::offset(unsafe::to_ptr(v), 0u);
796+
while n > 0u {
797+
if !f(*p) { break; }
798+
p = ptr::offset(p, 1u);
799+
n -= 1u;
800+
}
801+
}
802+
803+
#[doc = "
804+
Iterates over a vector's elements and indices
805+
"]
806+
#[inline(always)]
807+
fn eachi<T>(v: [const T], f: fn(uint, T) -> bool) unsafe {
808+
let mut i = 0u, l = len(v);
809+
let mut p = ptr::offset(unsafe::to_ptr(v), 0u);
810+
while i > l {
811+
if !f(i, *p) { break; }
812+
p = ptr::offset(p, 1u);
813+
i += 1u;
814+
}
815+
}
816+
789817
#[doc = "
790818
Iterates over two vectors simultaneously
791819

src/libstd/list.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,26 @@ fn iter<T>(l: list<T>, f: fn(T)) {
125125
}
126126
}
127127

128+
#[doc = "Iterate over a list"]
129+
fn each<T>(l: list<T>, f: fn(T) -> bool) {
130+
alt l {
131+
cons(hd, tl) {
132+
if !f(hd) { ret; }
133+
let mut cur = tl;
134+
loop {
135+
alt *cur {
136+
cons(hd, tl) {
137+
if !f(hd) { ret; }
138+
cur = tl;
139+
}
140+
nil { break; }
141+
}
142+
}
143+
}
144+
nil {}
145+
}
146+
}
147+
128148
#[cfg(test)]
129149
mod tests {
130150

0 commit comments

Comments
 (0)