Skip to content

Commit 30f13e6

Browse files
committed
Add slice_from and slice_to methods for vec, like the
methods of the same names that already exist for strs.
1 parent c4b6216 commit 30f13e6

File tree

1 file changed

+47
-3
lines changed

1 file changed

+47
-3
lines changed

src/libstd/vec.rs

+47-3
Original file line numberDiff line numberDiff line change
@@ -702,6 +702,8 @@ impl<'self,T:Clone> CopyableVector<T> for &'self [T] {
702702
#[allow(missing_doc)]
703703
pub trait ImmutableVector<'self, T> {
704704
fn slice(&self, start: uint, end: uint) -> &'self [T];
705+
fn slice_from(&self, start: uint) -> &'self [T];
706+
fn slice_to(&self, end: uint) -> &'self [T];
705707
fn iter(self) -> VecIterator<'self, T>;
706708
fn rev_iter(self) -> VecRevIterator<'self, T>;
707709
fn split_iter(self, pred: &'self fn(&T) -> bool) -> VecSplitIterator<'self, T>;
@@ -733,11 +735,17 @@ pub trait ImmutableVector<'self, T> {
733735

734736
/// Extension methods for vectors
735737
impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
736-
/// Return a slice that points into another slice.
738+
739+
/**
740+
* Returns a slice of self between `start` and `end`.
741+
*
742+
* Fails when `start` or `end` point outside the bounds of self,
743+
* or when `start` > `end`.
744+
*/
737745
#[inline]
738746
fn slice(&self, start: uint, end: uint) -> &'self [T] {
739-
assert!(start <= end);
740-
assert!(end <= self.len());
747+
assert!(start <= end);
748+
assert!(end <= self.len());
741749
do self.as_imm_buf |p, _len| {
742750
unsafe {
743751
transmute((ptr::offset(p, start),
@@ -746,6 +754,26 @@ impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
746754
}
747755
}
748756

757+
/**
758+
* Returns a slice of self from `start` to the end of the vec.
759+
*
760+
* Fails when `start` points outside the bounds of self.
761+
*/
762+
#[inline]
763+
fn slice_from(&self, start: uint) -> &'self [T] {
764+
self.slice(start, self.len())
765+
}
766+
767+
/**
768+
* Returns a slice of self from the start of the vec to `end`.
769+
*
770+
* Fails when `end` points outside the bounds of self.
771+
*/
772+
#[inline]
773+
fn slice_to(&self, end: uint) -> &'self [T] {
774+
self.slice(0, end)
775+
}
776+
749777
#[inline]
750778
fn iter(self) -> VecIterator<'self, T> {
751779
unsafe {
@@ -2570,6 +2598,22 @@ mod tests {
25702598
assert_eq!(v_d[4], 6);
25712599
}
25722600

2601+
#[test]
2602+
fn test_slice_from() {
2603+
let vec = &[1, 2, 3, 4];
2604+
assert_eq!(vec.slice_from(0), vec);
2605+
assert_eq!(vec.slice_from(2), &[3, 4]);
2606+
assert_eq!(vec.slice_from(4), &[]);
2607+
}
2608+
2609+
#[test]
2610+
fn test_slice_to() {
2611+
let vec = &[1, 2, 3, 4];
2612+
assert_eq!(vec.slice_to(4), vec);
2613+
assert_eq!(vec.slice_to(2), &[1, 2]);
2614+
assert_eq!(vec.slice_to(0), &[]);
2615+
}
2616+
25732617
#[test]
25742618
fn test_pop() {
25752619
// Test on-heap pop.

0 commit comments

Comments
 (0)