about summary refs log tree commit diff
path: root/src/libcollections
diff options
context:
space:
mode:
authorAriel Ben-Yehuda <arielb1@mail.tau.ac.il>2017-04-05 23:01:08 +0000
committerGitHub <noreply@github.com>2017-04-05 23:01:08 +0000
commit9d074473da5fef4b1d9ebbbb7f181edcb7a365a0 (patch)
tree4c1ecbe25d9034e8a32979bf577c0de93e64da50 /src/libcollections
parentfc5ff66b04af18b42a5278f1f74875311c957555 (diff)
parent1f70247446914a8b58bd088f32bcca792d30d75f (diff)
downloadrust-9d074473da5fef4b1d9ebbbb7f181edcb7a365a0.tar.gz
rust-9d074473da5fef4b1d9ebbbb7f181edcb7a365a0.zip
Rollup merge of #40943 - Amanieu:offset_to, r=alexcrichton
Add ptr::offset_to

This PR adds a method to calculate the signed distance (in number of elements) between two pointers. The resulting value can then be passed to `offset` to get one pointer from the other. This is similar to pointer subtraction in C/C++.

There are 2 special cases:

- If the distance is not a multiple of the element size then the result is rounded towards zero. (in C/C++ this is UB)
-  ZST return `None`, while normal types return `Some(isize)`. This forces the user to handle the ZST case in unsafe code. (C/C++ doesn't have ZSTs)
Diffstat (limited to 'src/libcollections')
-rw-r--r--src/libcollections/lib.rs1
-rw-r--r--src/libcollections/vec.rs12
2 files changed, 5 insertions, 8 deletions
diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs
index 00448b6abb2..534d7cc7c7e 100644
--- a/src/libcollections/lib.rs
+++ b/src/libcollections/lib.rs
@@ -62,6 +62,7 @@
 #![feature(untagged_unions)]
 #![cfg_attr(not(test), feature(str_checked_slicing))]
 #![cfg_attr(test, feature(rand, test))]
+#![feature(offset_to)]
 
 #![no_std]
 
diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs
index 7924c482648..c258ac2bdea 100644
--- a/src/libcollections/vec.rs
+++ b/src/libcollections/vec.rs
@@ -2074,14 +2074,10 @@ impl<T> Iterator for IntoIter<T> {
 
     #[inline]
     fn size_hint(&self) -> (usize, Option<usize>) {
-        let diff = (self.end as usize) - (self.ptr as usize);
-        let size = mem::size_of::<T>();
-        let exact = diff /
-                    (if size == 0 {
-                         1
-                     } else {
-                         size
-                     });
+        let exact = match self.ptr.offset_to(self.end) {
+            Some(x) => x as usize,
+            None => (self.end as usize).wrapping_sub(self.ptr as usize),
+        };
         (exact, Some(exact))
     }