Skip to content

Commit 21723d5

Browse files
committed
libcore: vec::windowed iterates, not allocates.
1 parent 76e77af commit 21723d5

File tree

1 file changed

+41
-16
lines changed

1 file changed

+41
-16
lines changed

src/libcore/vec.rs

+41-16
Original file line numberDiff line numberDiff line change
@@ -1495,16 +1495,35 @@ pub fn each_permutation<T:Copy>(v: &[T], put: &fn(ts: &[T]) -> bool) {
14951495
}
14961496
}
14971497
1498-
pub fn windowed<TT:Copy>(nn: uint, xx: &[TT]) -> ~[~[TT]] {
1499-
let mut ww = ~[];
1500-
assert!(1u <= nn);
1501-
for vec::eachi (xx) |ii, _x| {
1502-
let len = xx.len();
1503-
if ii+nn <= len {
1504-
ww.push(slice(xx, ii, ii+nn).to_vec());
1505-
}
1498+
/**
1499+
* Iterate over all contiguous windows of length `n` of the vector `v`.
1500+
*
1501+
* # Example
1502+
*
1503+
* Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`, `[3,4]`)
1504+
*
1505+
* ~~~
1506+
* for windowed(2, &[1,2,3,4]) |v| {
1507+
* io::println(fmt!("%?", v));
1508+
* }
1509+
* ~~~
1510+
*
1511+
*/
1512+
#[cfg(stage0)] // XXX: lifetimes!
1513+
pub fn windowed<T>(n: uint, v: &[T], it: &fn(&[T]) -> bool) {
1514+
assert!(1u <= n);
1515+
for uint::range(0, v.len() - n + 1) |i| {
1516+
if !it(v.slice(i, i+n)) { return }
1517+
}
1518+
}
1519+
#[cfg(stage1)]
1520+
#[cfg(stage2)]
1521+
#[cfg(stage3)]
1522+
pub fn windowed<'r, T>(n: uint, v: &'r [T], it: &fn(&'r [T]) -> bool) {
1523+
assert!(1u <= n);
1524+
for uint::range(0, v.len() - n + 1) |i| {
1525+
if !it(v.slice(i, i + n)) { return }
15061526
}
1507-
ww
15081527
}
15091528

15101529
/**
@@ -3761,20 +3780,26 @@ mod tests {
37613780

37623781
#[test]
37633782
fn test_windowed () {
3764-
assert!(~[~[1u,2u,3u],~[2u,3u,4u],~[3u,4u,5u],~[4u,5u,6u]]
3765-
== windowed (3u, ~[1u,2u,3u,4u,5u,6u]));
3766-
3767-
assert!(~[~[1u,2u,3u,4u],~[2u,3u,4u,5u],~[3u,4u,5u,6u]]
3768-
== windowed (4u, ~[1u,2u,3u,4u,5u,6u]));
3783+
fn t(n: uint, expected: &[&[int]]) {
3784+
let mut i = 0;
3785+
for windowed(n, ~[1,2,3,4,5,6]) |v| {
3786+
assert_eq!(v, expected[i]);
3787+
i += 1;
3788+
}
37693789

3770-
assert!(~[] == windowed (7u, ~[1u,2u,3u,4u,5u,6u]));
3790+
// check that we actually iterated the right number of times
3791+
assert_eq!(i, expected.len());
3792+
}
3793+
t(3, &[&[1,2,3],&[2,3,4],&[3,4,5],&[4,5,6]]);
3794+
t(4, &[&[1,2,3,4],&[2,3,4,5],&[3,4,5,6]]);
3795+
t(7, &[]);
37713796
}
37723797

37733798
#[test]
37743799
#[should_fail]
37753800
#[ignore(cfg(windows))]
37763801
fn test_windowed_() {
3777-
let _x = windowed (0u, ~[1u,2u,3u,4u,5u,6u]);
3802+
for windowed (0u, ~[1u,2u,3u,4u,5u,6u]) |_v| {}
37783803
}
37793804

37803805
#[test]

0 commit comments

Comments
 (0)