Skip to content

Commit

Permalink
get(s..=usize::MAX) should be fine when s != 0
Browse files Browse the repository at this point in the history
Test for coverage
  • Loading branch information
Philippe-Cholet authored and jswrenn committed May 14, 2024
1 parent 3c16f14 commit 05cc0ee
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
12 changes: 9 additions & 3 deletions src/iter_index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,17 @@ impl<I> IteratorIndex<I> for RangeInclusive<usize>
where
I: Iterator,
{
type Output = Skip<Take<I>>;
type Output = Take<Skip<I>>;

fn index(self, iter: I) -> Self::Output {
assert_ne!(*self.end(), usize::MAX);
iter.take(self.end() + 1).skip(*self.start())
// end - start + 1 without overflowing if possible
let length = if *self.end() == usize::MAX {
assert_ne!(*self.start(), 0);
self.end() - self.start() + 1
} else {
(self.end() + 1).saturating_sub(*self.start())
};
iter.skip(*self.start()).take(length)
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ pub trait Itertools: Iterator {
///
/// Works similarly to [`slice::get`](https://doc.rust-lang.org/std/primitive.slice.html#method.get).
///
/// **Panics** if the range includes `usize::MAX`.
/// **Panics** for ranges `..=usize::MAX` and `0..=usize::MAX`.
///
/// It's a generalisation of [`Iterator::take`] and [`Iterator::skip`],
/// and uses these under the hood.
Expand Down
13 changes: 13 additions & 0 deletions tests/test_core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,19 @@ fn get_dei_esi_then_dei_esi<I: DoubleEndedIterator + ExactSizeIterator + Clone>(
is_dei_esi(it.get(..));
}

#[test]
fn get_1_max() {
let mut it = (0..5).get(1..=usize::MAX);
assert_eq!(it.next(), Some(1));
assert_eq!(it.next_back(), Some(4));
}

#[test]
#[should_panic]
fn get_full_range_inclusive() {
let _it = (0..5).get(0..=usize::MAX);
}

#[test]
fn product0() {
let mut prod = iproduct!();
Expand Down

0 comments on commit 05cc0ee

Please sign in to comment.