Skip to content

Commit c568cf6

Browse files
committed
Added vec::view, for creating subslices.
1 parent 0eed37d commit c568cf6

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/libcore/vec.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ export init;
2222
export last;
2323
export last_opt;
2424
export slice;
25+
export view;
2526
export split;
2627
export splitn;
2728
export rsplit;
@@ -254,6 +255,18 @@ fn slice<T: copy>(v: [const T], start: uint, end: uint) -> [T] {
254255
ret result;
255256
}
256257

258+
#[doc = "Return a slice that points into another slice."]
259+
fn view<T: copy>(v: [const T]/&, start: uint, end: uint) -> [T]/&a {
260+
assert (start <= end);
261+
assert (end <= len(v));
262+
unpack_slice(v) {|p, _len|
263+
unsafe {
264+
::unsafe::reinterpret_cast(
265+
(ptr::offset(p, start), (end - start) * sys::size_of::<T>()))
266+
}
267+
}
268+
}
269+
257270
#[doc = "
258271
Split the vector `v` by applying each element against the predicate `f`.
259272
"]
@@ -2029,6 +2042,15 @@ mod tests {
20292042
reserve(v, 10u);
20302043
assert capacity(v) == 10u;
20312044
}
2045+
2046+
#[test]
2047+
fn test_view() {
2048+
let v = [1, 2, 3, 4, 5];
2049+
let v = view(v, 1u, 3u);
2050+
assert(len(v) == 2u);
2051+
assert(v[0] == 2);
2052+
assert(v[1] == 3);
2053+
}
20322054
}
20332055

20342056
// Local Variables:

0 commit comments

Comments
 (0)