diff --git a/src/lib/ivec.rs b/src/lib/ivec.rs index a33c04977bbc..b97f2593a8c9 100644 --- a/src/lib/ivec.rs +++ b/src/lib/ivec.rs @@ -33,6 +33,16 @@ fn len[T](&T[] v) -> uint { ret rusti::ivec_len(v); } +type init_op[T] = fn(uint) -> T; + +fn init_fn[T](&init_op[T] op, uint n_elts) -> T[] { + auto v = ~[]; + reserve(v, n_elts); + let uint i = 0u; + while (i < n_elts) { v += ~[op(i)]; i += 1u; } + ret v; +} + mod unsafe { fn copy_from_buf[T](&mutable T[] v, *T ptr, uint count) { ret rustrt::ivec_copy_from_buf(v, ptr, count); diff --git a/src/test/run-pass/lib-ivec.rs b/src/test/run-pass/lib-ivec.rs index 884f86198e75..aa9a44999dae 100644 --- a/src/test/run-pass/lib-ivec.rs +++ b/src/test/run-pass/lib-ivec.rs @@ -34,8 +34,18 @@ fn test_unsafe_ptrs() { assert (d.(4) == 5); } +fn test_init_fn() { + fn square(uint n) -> uint { ret n * n; } + auto v = ivec::init_fn(square, 3u); + assert (ivec::len(v) == 3u); + assert (v.(0) == 1u); + assert (v.(1) == 4u); + assert (v.(2) == 9u); +} + fn main() { test_reserve_and_on_heap(); //test_unsafe_ptrs(); + //test_init_fn(); }