Tracking Issue for sub_ptr
(feature ptr_sub_ptr
) #95892
Description
Feature gate: #![feature(ptr_sub_ptr)]
& #![feature(const_ptr_sub_ptr)]
This is a tracking issue for the <*const _>::sub_ptr
& <*mut _>::sub_ptr
methods.
This is the produces-usize
version of offset_from
, the same way that add
and sub
are the takes-usize
versions of offset
.
It turns out that people almost always actually know which pointer is greater than which when doing this operation, and would rather a usize
instead of an isize
-- every use of offset_from
in the library was followed with as usize
in practice. So like how .add(d)
greatly improved code compared to needing .offset(d as isize)
, being able to use ptr.sub_ptr(origin)
instead of ptr.offset_from(origin) as usize
is also a major improvement. And Miri can check the unsafety better, too, since if you get the order wrong it'll detect that, unlike happens with the as usize
approach.
This also tracks the const
ness of operations, though with #92980 stabilizing offset_from
being const
, this being const
is likely uncontroversial.
Public API
impl<T> *const T {
pub const unsafe fn sub_ptr(self, origin: *const T) -> usize;
pub const unsafe fn byte_sub_ptr<U>(self, origin: *const U) -> usize;
}
impl<T> *mut T {
pub const unsafe fn sub_ptr(self, origin: *const T) -> usize;
pub const unsafe fn byte_sub_ptr<U>(self, origin: *const U) -> usize;
}
impl <T> NonNull<T> {
pub const unsafe fn sub_ptr(self, subtracted: NonNull<T>) -> usize;
pub const unsafe fn byte_sub_ptr<U>(self, origin: NonNull<U>) -> usize;
}
Steps / History
- Implementation: Add
sub_ptr
on pointers (theusize
version ofoffset_from
) #95837 - Move the
NonNull
method to this gate Stabilizenon_null_convenience
#124498 - Final comment period (FCP)
- Stabilization PR
Unresolved Questions
- This uses the terminology of subtraction to match the existing
add
andsub
methods, but there might be another name that would be more evocative for people Addsub_ptr
on pointers (theusize
version ofoffset_from
) #95837 (comment)
Activity