From c568cf6099b94d50ff7ca28e60d376ebe2cc9255 Mon Sep 17 00:00:00 2001 From: Eric Holk Date: Fri, 18 May 2012 16:55:22 -0700 Subject: [PATCH] Added vec::view, for creating subslices. --- src/libcore/vec.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/libcore/vec.rs b/src/libcore/vec.rs index 37f0ecb2115..d78063f8450 100644 --- a/src/libcore/vec.rs +++ b/src/libcore/vec.rs @@ -22,6 +22,7 @@ export init; export last; export last_opt; export slice; +export view; export split; export splitn; export rsplit; @@ -254,6 +255,18 @@ fn slice(v: [const T], start: uint, end: uint) -> [T] { ret result; } +#[doc = "Return a slice that points into another slice."] +fn view(v: [const T]/&, start: uint, end: uint) -> [T]/&a { + assert (start <= end); + assert (end <= len(v)); + unpack_slice(v) {|p, _len| + unsafe { + ::unsafe::reinterpret_cast( + (ptr::offset(p, start), (end - start) * sys::size_of::())) + } + } +} + #[doc = " Split the vector `v` by applying each element against the predicate `f`. "] @@ -2029,6 +2042,15 @@ mod tests { reserve(v, 10u); assert capacity(v) == 10u; } + + #[test] + fn test_view() { + let v = [1, 2, 3, 4, 5]; + let v = view(v, 1u, 3u); + assert(len(v) == 2u); + assert(v[0] == 2); + assert(v[1] == 3); + } } // Local Variables: