stdlib: Implement interior vector map

This commit is contained in:
Patrick Walton 2011-07-04 22:48:42 -07:00
parent d3a4102bc1
commit f71c8dd918
2 changed files with 37 additions and 0 deletions

View file

@ -158,6 +158,20 @@ fn grow_set[T](&mutable T[mutable] v, uint index, &T initval, &T val) {
v.(index) = val;
}
// Functional utilities
fn map[T,U](fn(&T)->U f, &mutable T[mutable?] v) -> U[] {
auto result = ~[];
reserve(result, len(v));
for (T elem in v) {
auto elem2 = elem; // satisfies alias checker
result += ~[f(elem2)];
}
ret result;
}
mod unsafe {
fn copy_from_buf[T](&mutable T[] v, *T ptr, uint count) {
ret rustrt::ivec_copy_from_buf(v, ptr, count);

View file

@ -164,6 +164,26 @@ fn test_grow_set() {
assert (v.(4) == 5);
}
fn test_map() {
// Test on-stack map.
auto v = ~[ 1u, 2u, 3u ];
auto w = ivec::map(square, v);
assert (ivec::len(w) == 3u);
assert (w.(0) == 1u);
assert (w.(1) == 4u);
assert (w.(2) == 9u);
// Test on-heap map.
v = ~[ 1u, 2u, 3u, 4u, 5u ];
w = ivec::map(square, v);
assert (ivec::len(w) == 5u);
assert (w.(0) == 1u);
assert (w.(1) == 4u);
assert (w.(2) == 9u);
assert (w.(3) == 16u);
assert (w.(4) == 25u);
}
fn main() {
test_reserve_and_on_heap();
test_unsafe_ptrs();
@ -181,5 +201,8 @@ fn main() {
test_grow();
test_grow_fn();
test_grow_set();
// Functional utilities
test_map();
}