diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index fca4583f049d..b2bd12199979 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -833,9 +833,7 @@ macro_rules! iterator { #[inline] fn size_hint(&self) -> (usize, Option) { - let diff = (self.end as usize).wrapping_sub(self.ptr as usize); - let size = mem::size_of::(); - let exact = diff / (if size == 0 {1} else {size}); + let exact = ptrdistance(self.ptr, self.end); (exact, Some(exact)) } @@ -1127,6 +1125,15 @@ impl<'a, T> FusedIterator for IterMut<'a, T> {} unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {} +// Return the number of elements of `T` from `start` to `end`. +// Return the arithmetic difference if `T` is zero size. +#[inline(always)] +fn ptrdistance(start: *const T, end: *const T) -> usize { + let diff = (end as usize).wrapping_sub(start as usize); + let size = mem::size_of::(); + diff / (if size == 0 { 1 } else { size }) +} + // Extension methods for raw pointers, used by the iterators trait PointerExt : Copy { unsafe fn slice_offset(self, i: isize) -> Self;