diff --git a/src/lib.rs b/src/lib.rs index 1244ab9a2..08bc2e059 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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 - where Self: Sized + #[inline] + fn try_len(&self) -> Result { size_hint::try_len(self.size_hint()) } diff --git a/src/size_hint.rs b/src/size_hint.rs index dfe69d1d9..dbd5624e6 100644 --- a/src/size_hint.rs +++ b/src/size_hint.rs @@ -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 { +pub fn try_len(sh: SizeHint) -> Result { match sh { - (lo, Some(hi)) if lo == hi => Some(lo), - _ => None + (lo, Some(hi)) if lo == hi => Ok(lo), + _ => Err(sh) } } \ No newline at end of file