Skip to content

Add a split_at method to slice::ImmutableVector #16188

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions src/libcore/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ pub trait ImmutableVector<'a, T> {
* Fails when `end` points outside the bounds of self.
*/
fn slice_to(&self, end: uint) -> &'a [T];

/// Divides one slice into two at an index.
///
/// The first will contain all indices from `[0, mid)` (excluding
/// the index `mid` itself) and the second will contain all
/// indices from `[mid, len)` (excluding the index `len` itself).
///
/// Fails if `mid > len`.
fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]);

/// Returns an iterator over the vector
fn iter(self) -> Items<'a, T>;
/// Returns an iterator over the subslices of the vector which are
Expand Down Expand Up @@ -247,6 +257,11 @@ impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
self.slice(0, end)
}

#[inline]
fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]) {
(self.slice(0, mid), self.slice(mid, self.len()))
}

#[inline]
fn iter(self) -> Items<'a, T> {
unsafe {
Expand Down Expand Up @@ -1192,8 +1207,7 @@ impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
None
} else {
let chunksz = cmp::min(self.v.len(), self.size);
let (fst, snd) = (self.v.slice_to(chunksz),
self.v.slice_from(chunksz));
let (fst, snd) = self.v.split_at(chunksz);
self.v = snd;
Some(fst)
}
Expand All @@ -1219,8 +1233,7 @@ impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
} else {
let remainder = self.v.len() % self.size;
let chunksz = if remainder != 0 { remainder } else { self.size };
let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz),
self.v.slice_from(self.v.len() - chunksz));
let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
self.v = fst;
Some(snd)
}
Expand Down