diff options
| author | Ariel Ben-Yehuda <arielb1@mail.tau.ac.il> | 2017-04-05 23:01:08 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2017-04-05 23:01:08 +0000 |
| commit | 9d074473da5fef4b1d9ebbbb7f181edcb7a365a0 (patch) | |
| tree | 4c1ecbe25d9034e8a32979bf577c0de93e64da50 /src/libcollections | |
| parent | fc5ff66b04af18b42a5278f1f74875311c957555 (diff) | |
| parent | 1f70247446914a8b58bd088f32bcca792d30d75f (diff) | |
| download | rust-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.rs | 1 | ||||
| -rw-r--r-- | src/libcollections/vec.rs | 12 |
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)) } |
