Skip to content

Commit ade92c6

Browse files
committed
auto merge of #16188 : nham/rust/immut_slice_split_at, r=brson
This operation seems common enough that it would be convenient for it to be a standard method.
2 parents 4b54110 + 7e5440e commit ade92c6

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

src/libcore/slice.rs

+17-4
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,16 @@ pub trait ImmutableVector<'a, T> {
7676
* Fails when `end` points outside the bounds of self.
7777
*/
7878
fn slice_to(&self, end: uint) -> &'a [T];
79+
80+
/// Divides one slice into two at an index.
81+
///
82+
/// The first will contain all indices from `[0, mid)` (excluding
83+
/// the index `mid` itself) and the second will contain all
84+
/// indices from `[mid, len)` (excluding the index `len` itself).
85+
///
86+
/// Fails if `mid > len`.
87+
fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]);
88+
7989
/// Returns an iterator over the vector
8090
fn iter(self) -> Items<'a, T>;
8191
/// Returns an iterator over the subslices of the vector which are
@@ -247,6 +257,11 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
247257
self.slice(0, end)
248258
}
249259

260+
#[inline]
261+
fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]) {
262+
(self.slice(0, mid), self.slice(mid, self.len()))
263+
}
264+
250265
#[inline]
251266
fn iter(self) -> Items<'a, T> {
252267
unsafe {
@@ -1192,8 +1207,7 @@ impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
11921207
None
11931208
} else {
11941209
let chunksz = cmp::min(self.v.len(), self.size);
1195-
let (fst, snd) = (self.v.slice_to(chunksz),
1196-
self.v.slice_from(chunksz));
1210+
let (fst, snd) = self.v.split_at(chunksz);
11971211
self.v = snd;
11981212
Some(fst)
11991213
}
@@ -1219,8 +1233,7 @@ impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
12191233
} else {
12201234
let remainder = self.v.len() % self.size;
12211235
let chunksz = if remainder != 0 { remainder } else { self.size };
1222-
let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz),
1223-
self.v.slice_from(self.v.len() - chunksz));
1236+
let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
12241237
self.v = fst;
12251238
Some(snd)
12261239
}

0 commit comments

Comments
 (0)