Skip to content
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

try_len method #723

Merged
merged 5 commits into from
Aug 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3840,6 +3840,30 @@ pub trait Itertools : Iterator {
{
MultiUnzip::multiunzip(self)
}

/// Returns the length of the iterator if one exists.
/// Otherwise return `self.size_hint()`.
///
/// Fallible [`ExactSizeIterator::len`].
///
/// Inherits guarantees and restrictions from [`Iterator::size_hint`].
///
/// ```
/// use itertools::Itertools;
///
/// 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) -> Result<usize, size_hint::SizeHint> {
let sh = self.size_hint();
match sh {
(lo, Some(hi)) if lo == hi => Ok(lo),
_ => Err(sh),
}
}
}

impl<T: ?Sized> Itertools for T where T: Iterator { }
Expand Down