rollup merge of #23951: alexcrichton/splitn

This commit is an implementation of [RFC 979][rfc] which changes the meaning of
the count parameter to the `splitn` function on strings and slices. The
parameter now means the number of items that are returned from the iterator, not
the number of splits that are made.

[rfc]: https://github.com/rust-lang/rfcs/pull/979

Closes #23911
[breaking-change]
This commit is contained in:
Alex Crichton
2015-04-01 13:30:08 -07:00
14 changed files with 88 additions and 69 deletions

View File

@@ -1126,18 +1126,20 @@ impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
#[inline]
fn next(&mut self) -> Option<T> {
if self.count == 0 {
self.iter.finish()
} else {
self.count -= 1;
if self.invert { self.iter.next_back() } else { self.iter.next() }
match self.count {
0 => None,
1 => { self.count -= 1; self.iter.finish() }
_ => {
self.count -= 1;
if self.invert {self.iter.next_back()} else {self.iter.next()}
}
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, upper_opt) = self.iter.size_hint();
(lower, upper_opt.map(|upper| cmp::min(self.count + 1, upper)))
(lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
}
}

View File

@@ -489,7 +489,7 @@ struct CharSplits<'a, P: Pattern<'a>> {
/// splitting at most `count` times.
struct CharSplitsN<'a, P: Pattern<'a>> {
iter: CharSplits<'a, P>,
/// The number of splits remaining
/// The number of items remaining
count: usize,
}
@@ -596,11 +596,10 @@ impl<'a, P: Pattern<'a>> Iterator for CharSplitsN<'a, P> {
#[inline]
fn next(&mut self) -> Option<&'a str> {
if self.count != 0 {
self.count -= 1;
self.iter.next()
} else {
self.iter.get_end()
match self.count {
0 => None,
1 => { self.count = 0; self.iter.get_end() }
_ => { self.count -= 1; self.iter.next() }
}
}
}
@@ -650,11 +649,10 @@ impl<'a, P: Pattern<'a>> Iterator for RCharSplitsN<'a, P>
#[inline]
fn next(&mut self) -> Option<&'a str> {
if self.count != 0 {
self.count -= 1;
self.iter.next()
} else {
self.iter.get_remainder()
match self.count {
0 => None,
1 => { self.count -= 1; self.iter.get_remainder() }
_ => { self.count -= 1; self.iter.next() }
}
}
}