diff --git a/src/lib/vec.rs b/src/lib/vec.rs index ba6040738564d..f3f06a1dc85db 100644 --- a/src/lib/vec.rs +++ b/src/lib/vec.rs @@ -322,6 +322,45 @@ fn freeze[T](vec[mutable T] v) -> vec[T] { ret result; } +// Swaps two elements in a vector +fn swap[T](&vec[T] v, uint a, uint b) { + let T t = v.(a); + v.(a) = v.(b); + v.(b) = t; +} + +// In place vector reversal +fn reverse[T](&vec[T] v) -> () { + let uint i = 0u; + auto ln = len[T](v); + + while(i < ln / 2u) { + swap(v, i, ln - i - 1u); + i += 1u; + } +} + +// Functional vector reversal. Returns a reversed copy of v. +fn reversed[T](vec[T] v) -> vec[T] { + let vec[T] res = []; + + auto i = len[T](v); + if (i == 0u) { + ret res; + } + else { + i -= 1u; + } + + while(i != 0u) { + push[T](res, v.(i)); + i -= 1u; + } + push[T](res, v.(0)); + + ret res; +} + // Local Variables: // mode: rust; // fill-column: 78; diff --git a/src/test/run-pass/vec-reverse.rs b/src/test/run-pass/vec-reverse.rs new file mode 100644 index 0000000000000..5cc9b8a363b78 --- /dev/null +++ b/src/test/run-pass/vec-reverse.rs @@ -0,0 +1,29 @@ +use std; +import std::vec; + +fn main() { + let vec[int] v = [10, 20]; + + assert v.(0) == 10; + assert v.(1) == 20; + + vec::reverse[int](v); + + assert v.(0) == 20; + assert v.(1) == 10; + + auto v2 = vec::reversed[int](v); + + assert v2.(0) == 10; + assert v2.(1) == 20; + + v.(0) = 30; + + assert v2.(0) == 10; + + // Make sure they work with 0-length vectors too. + let vec[int] v3 = []; + auto v4 = vec::reversed[int](v3); + + vec::reverse[int](v3); +}