Skip to content

Commit

Permalink
try_len method
Browse files Browse the repository at this point in the history
  • Loading branch information
Easyoakland committed Aug 7, 2023
1 parent 79bfebb commit 5721f37
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3840,6 +3840,22 @@ pub trait Itertools : Iterator {
{
MultiUnzip::multiunzip(self)
}

/// Returns the length of the iterator if one exists.
///
/// ```
/// 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);
/// ```
fn try_len(self) -> Option<usize>
where Self: Sized
{
size_hint::try_len(self)
}
}

impl<T: ?Sized> Itertools for T where T: Iterator { }
Expand Down
9 changes: 9 additions & 0 deletions src/size_hint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,12 @@ pub fn min(a: SizeHint, b: SizeHint) -> SizeHint {
};
(lower, upper)
}

/// Returns the length of the iterator if one exists.
#[inline]
pub fn try_len(it: impl Iterator) -> Option<usize> {
match it.size_hint() {
(lo, Some(hi)) if lo == hi => Some(lo),
_ => None
}
}

0 comments on commit 5721f37

Please sign in to comment.