]> git.lizzy.rs Git - rust.git/commitdiff
core: Add ptrdistance to slice module
authorUlrik Sverdrup <bluss@users.noreply.github.com>
Wed, 23 Nov 2016 22:02:30 +0000 (23:02 +0100)
committerUlrik Sverdrup <bluss@users.noreply.github.com>
Thu, 24 Nov 2016 15:55:46 +0000 (16:55 +0100)
src/libcore/slice.rs

index fca4583f049dd08c23ab667a4be8791c5f0f1f0f..b2bd121999791718878c1a8fe1d768a9eb04c2ae 100644 (file)
@@ -833,9 +833,7 @@ fn next(&mut self) -> Option<$elem> {
 
             #[inline]
             fn size_hint(&self) -> (usize, Option<usize>) {
-                let diff = (self.end as usize).wrapping_sub(self.ptr as usize);
-                let size = mem::size_of::<T>();
-                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<T>(start: *const T, end: *const T) -> usize {
+    let diff = (end as usize).wrapping_sub(start as usize);
+    let size = mem::size_of::<T>();
+    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;