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 constness 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 offset_from_unsigned(self, origin: *const T) -> usize;
pub const unsafe fn byte_offset_from_unsigned<U>(self, origin: *const U) -> usize;
}
impl<T> *mut T {
pub const unsafe fn offset_from_unsigned(self, origin: *const T) -> usize;
pub const unsafe fn byte_offset_from_unsigned<U>(self, origin: *const U) -> usize;
}
impl <T> NonNull<T> {
pub const unsafe fn offset_from_unsigned(self, subtracted: NonNull<T>) -> usize;
pub const unsafe fn byte_offset_from_unsigned<U>(self, origin: NonNull<U>) -> usize;
}
Steps / History
Unresolved Questions
Feature gate:
#![feature(ptr_sub_ptr)]&#![feature(const_ptr_sub_ptr)]This is a tracking issue for the
<*const _>::sub_ptr&<*mut _>::sub_ptrmethods.This is the produces-
usizeversion ofoffset_from, the same way thataddandsubare the takes-usizeversions ofoffset.It turns out that people almost always actually know which pointer is greater than which when doing this operation, and would rather a
usizeinstead of anisize-- every use ofoffset_fromin the library was followed withas usizein practice. So like how.add(d)greatly improved code compared to needing.offset(d as isize), being able to useptr.sub_ptr(origin)instead ofptr.offset_from(origin) as usizeis 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 theas usizeapproach.This also tracks the
constness of operations, though with #92980 stabilizingoffset_frombeingconst, this beingconstis likely uncontroversial.Public API
Steps / History
sub_ptron pointers (theusizeversion ofoffset_from) #95837NonNullmethod to this gate Stabilizenon_null_convenience#124498(const_)ptr_sub_ptr#137121Unresolved Questions
addandsubmethods, but there might be another name that would be more evocative for people Addsub_ptron pointers (theusizeversion ofoffset_from) #95837 (comment)