rust-lang / libs-team

The home of the library team
Apache License 2.0
116 stars 18 forks source link

Expose `add`/`sub`/`sub_ptr` on `NonNull` #251

Closed scottmcm closed 11 months ago

scottmcm commented 1 year ago

Proposal

Problem statement

NonNull is missing a bunch of the usual methods on pointers, resulting in code needing to extract the underlying pointer, do the operation, and put it back again

https://github.com/rust-lang/rust/blob/50dff955a9367a4efc72b831549e368992807beb/library/core/src/slice/iter/macros.rs#L81-L83

The safety requirements on add/sub prohibit the resulting pointer from ever being null -- no object can be located at null, nor can the past-the-end pointer be null -- so it would be nice not to have to re-prove that for the NonNull constructor every time they're used.

Motivating examples or use cases

As of https://github.com/rust-lang/rust/pull/114205/files#diff-430db13219f4c1ac4f4d35f685a45778572e039dab837c5ffeec9a810fc547b4 these are already marked unstable, but as std_internals, because they're useful for writing iterators outside of core.

Solution sketch

Thus this proposes just promoting these methods from doc(hidden) to stabilization-track nightly methods.

Alternatives

They're not necessary, of course, and people could continue doing the as_ptr-then-reconstruct dance.

Links and related work

The num::NonZero types similarly have the methods that work without the possibility of violating the non-zero invariant, so doing the same for NonNull sounds at least plausible.

What happens now?

This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

Second, if there's a concrete solution:

Amanieu commented 11 months ago

We discussed this in the libs-api meeting. This seems fine to add, but we would also like to have the offset and offset_from methods for consistency with raw pointers.