Skip to content

Commit 9ed82fb

Browse files
committed
auto merge of #7943 : Dretch/rust/vec-slice-from-to, r=huonw
2 parents 2f7d86f + 30f13e6 commit 9ed82fb

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
@@ -689,6 +689,8 @@ impl<'self,T:Clone> CopyableVector<T> for &'self [T] {
689689
#[allow(missing_doc)]
690690
pub trait ImmutableVector<'self, T> {
691691
fn slice(&self, start: uint, end: uint) -> &'self [T];
692+
fn slice_from(&self, start: uint) -> &'self [T];
693+
fn slice_to(&self, end: uint) -> &'self [T];
692694
fn iter(self) -> VecIterator<'self, T>;
693695
fn rev_iter(self) -> VecRevIterator<'self, T>;
694696
fn split_iter(self, pred: &'self fn(&T) -> bool) -> VecSplitIterator<'self, T>;
@@ -720,11 +722,17 @@ pub trait ImmutableVector<'self, T> {
720722

721723
/// Extension methods for vectors
722724
impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
723-
/// Return a slice that points into another slice.
725+
726+
/**
727+
* Returns a slice of self between `start` and `end`.
728+
*
729+
* Fails when `start` or `end` point outside the bounds of self,
730+
* or when `start` > `end`.
731+
*/
724732
#[inline]
725733
fn slice(&self, start: uint, end: uint) -> &'self [T] {
726-
assert!(start <= end);
727-
assert!(end <= self.len());
734+
assert!(start <= end);
735+
assert!(end <= self.len());
728736
do self.as_imm_buf |p, _len| {
729737
unsafe {
730738
transmute((ptr::offset(p, start),
@@ -733,6 +741,26 @@ impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
733741
}
734742
}
735743

744+
/**
745+
* Returns a slice of self from `start` to the end of the vec.
746+
*
747+
* Fails when `start` points outside the bounds of self.
748+
*/
749+
#[inline]
750+
fn slice_from(&self, start: uint) -> &'self [T] {
751+
self.slice(start, self.len())
752+
}
753+
754+
/**
755+
* Returns a slice of self from the start of the vec to `end`.
756+
*
757+
* Fails when `end` points outside the bounds of self.
758+
*/
759+
#[inline]
760+
fn slice_to(&self, end: uint) -> &'self [T] {
761+
self.slice(0, end)
762+
}
763+
736764
#[inline]
737765
fn iter(self) -> VecIterator<'self, T> {
738766
unsafe {
@@ -2453,6 +2481,22 @@ mod tests {
24532481
assert_eq!(v_d[4], 6);
24542482
}
24552483

2484+
#[test]
2485+
fn test_slice_from() {
2486+
let vec = &[1, 2, 3, 4];
2487+
assert_eq!(vec.slice_from(0), vec);
2488+
assert_eq!(vec.slice_from(2), &[3, 4]);
2489+
assert_eq!(vec.slice_from(4), &[]);
2490+
}
2491+
2492+
#[test]
2493+
fn test_slice_to() {
2494+
let vec = &[1, 2, 3, 4];
2495+
assert_eq!(vec.slice_to(4), vec);
2496+
assert_eq!(vec.slice_to(2), &[1, 2]);
2497+
assert_eq!(vec.slice_to(0), &[]);
2498+
}
2499+
24562500
#[test]
24572501
fn test_pop() {
24582502
// Test on-heap pop.

0 commit comments

Comments
 (0)