@@ -770,6 +770,13 @@ impl<T> Option<T> {
770
770
}
771
771
}
772
772
773
+ #[ inline]
774
+ const fn len ( & self ) -> usize {
775
+ // Using the intrinsic avoids emitting a branch to get the 0 or 1.
776
+ let discriminant: isize = crate :: intrinsics:: discriminant_value ( self ) ;
777
+ discriminant as usize
778
+ }
779
+
773
780
/// Returns a slice of the contained value, if any. If this is `None`, an
774
781
/// empty slice is returned. This can be useful to have a single type of
775
782
/// iterator over an `Option` or slice.
@@ -812,7 +819,7 @@ impl<T> Option<T> {
812
819
unsafe {
813
820
slice:: from_raw_parts (
814
821
( self as * const Self ) . byte_add ( core:: mem:: offset_of!( Self , Some . 0 ) ) . cast ( ) ,
815
- self . is_some ( ) as usize ,
822
+ self . len ( ) ,
816
823
)
817
824
}
818
825
}
@@ -869,7 +876,7 @@ impl<T> Option<T> {
869
876
unsafe {
870
877
slice:: from_raw_parts_mut (
871
878
( self as * mut Self ) . byte_add ( core:: mem:: offset_of!( Self , Some . 0 ) ) . cast ( ) ,
872
- self . is_some ( ) as usize ,
879
+ self . len ( ) ,
873
880
)
874
881
}
875
882
}
@@ -2242,10 +2249,8 @@ impl<A> Iterator for Item<A> {
2242
2249
2243
2250
#[ inline]
2244
2251
fn size_hint ( & self ) -> ( usize , Option < usize > ) {
2245
- match self . opt {
2246
- Some ( _) => ( 1 , Some ( 1 ) ) ,
2247
- None => ( 0 , Some ( 0 ) ) ,
2248
- }
2252
+ let len = self . len ( ) ;
2253
+ ( len, Some ( len) )
2249
2254
}
2250
2255
}
2251
2256
@@ -2256,7 +2261,12 @@ impl<A> DoubleEndedIterator for Item<A> {
2256
2261
}
2257
2262
}
2258
2263
2259
- impl < A > ExactSizeIterator for Item < A > { }
2264
+ impl < A > ExactSizeIterator for Item < A > {
2265
+ #[ inline]
2266
+ fn len ( & self ) -> usize {
2267
+ self . opt . len ( )
2268
+ }
2269
+ }
2260
2270
impl < A > FusedIterator for Item < A > { }
2261
2271
unsafe impl < A > TrustedLen for Item < A > { }
2262
2272
0 commit comments