Skip to content

Commit

Permalink
Result not Option, inline, no Sized bound, improve docs
Browse files Browse the repository at this point in the history
  • Loading branch information
Easyoakland committed Aug 9, 2023
1 parent 952d8c4 commit 87ad574
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
19 changes: 12 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3842,18 +3842,23 @@ pub trait Itertools : Iterator {
}

/// Returns the length of the iterator if one exists.
/// Relies on the [`size_hint`] of the iterator being correct.
/// Otherwise return `self.size_hint()`.
///
/// Fallible [`ExactSizeIterator::len`].
///
/// Inherits guarantees and restrictions from [`Iterator::size_hint`].
///
/// ```
/// use itertools::Itertools;
///
/// assert_eq!([0; 10].into_iter().try_len(), Some(10));
/// assert_eq!((10..15).try_len(), Some(5));
/// assert_eq!((15..10).try_len(), Some(0));
/// assert_eq!((10..).try_len(), None);
/// assert_eq!([0; 10].iter().try_len(), Ok(10));
/// assert_eq!((10..15).try_len(), Ok(5));
/// assert_eq!((15..10).try_len(), Ok(0));
/// assert_eq!((10..).try_len(), Err((usize::MAX, None)));
/// assert_eq!((10..15).filter(|x| x % 2 == 0).try_len(), Err((0, Some(5))));
/// ```
fn try_len(&self) -> Option<usize>
where Self: Sized
#[inline]
fn try_len(&self) -> Result<usize, size_hint::SizeHint>
{
size_hint::try_len(self.size_hint())
}
Expand Down
6 changes: 3 additions & 3 deletions src/size_hint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,9 @@ pub fn min(a: SizeHint, b: SizeHint) -> SizeHint {

/// Returns the length of the iterator if one exists.
#[inline]
pub fn try_len(sh: SizeHint) -> Option<usize> {
pub fn try_len(sh: SizeHint) -> Result<usize, SizeHint> {
match sh {
(lo, Some(hi)) if lo == hi => Some(lo),
_ => None
(lo, Some(hi)) if lo == hi => Ok(lo),
_ => Err(sh)
}
}

0 comments on commit 87ad574

Please sign in to comment.