Stdlib proposal: AsPtr, IntoRawPtr, FromRawPtr #75846
Labels
C-feature-request
Category: A feature request, i.e: not implemented / a PR.
T-libs-api
Relevant to the library API team, which will review and decide on the PR/issue.
I'd like to propose some new conversion traits for
core::convert
:AsPtr
,IntoRawPtr
,FromRawPtr
. These would be defined like so:These traits would be implemented for raw pointer types, as well as for smart pointer types like
Box
,Arc
,Weak
, etc.The purpose of these traits would, obviously, be to facilitate conversion of a type into and back out of a pointer. The motivating practical use case is to make it easier to create
RawWaker
s and associated implementations, especially through intermediate Handle types. Consider this example:This would be relatively easy to create a RawWaker for, since we can directly convert the
state
Arc
into and out of the requisite*const()
, and write the vtable methods to convert it back into anArc
. However, now consider this example:This would be impossible to create a
RawWaker
for, without:Unparker
(adds an unnecessary level of indirection)Unparker
to and from*const()
(unsafe, since it now depends on the private implementation details ofUnparker
).However, with the proposed traits, if
Unparker
wanted to opt-in to being used in this way, it could:This would allow the
Unparker
to declare its "pointer-ness" as part of its public API (without actually exposing any implementation details), enabling its use inRawWaker
(and other raw pointer APIs, such as C FFI).Alternatives:
Third party
These traits could, of course, be provided as a 3rd party crate, but I believe these traits are sufficiently "fundamental" (similar to
Into
/From
,AsRef
, etc) to warrant inclusion directly into the standard library. This would also help different, independent libraries to coordinate with each other through this trait, which is possible but more difficult (due to potential ecosystem fragmentation) with a third party crate. It's also the sort of thing that seems "too simple" to require an entire dependency crate.Existing traits
While we could use
Into
/From
, I don't think that those provide a strong enough contract to ensure the correct use of these, especiallyIntoRawPtr
andFromRawPtr
. Additionally, a type should only be able to be converted through a single pointer type, so having a dedicated trait with an associated type makes the most sense.The text was updated successfully, but these errors were encountered: