ptr::is_aligned_for::<U>
Summary
Introduce ptr::is_aligned_for<U>(self) -> bool
on raw pointers (*const
, *mut
) and NonNull
. This method checks whether the pointer is correctly aligned for a target type U
, streamlining safe pointer casts without intermediate steps.
Alternatively (preferably?), introduce ptr::try_cast_aligned<U>(self) -> Option<Ptr<U>>
on the same types. This method checks alignment and returns a casted pointer if it is correctly aligned.
Currently, users that want to perform aligned read/write must cast before checking alignment:
#[repr(C)] struct Complex { // ... } let ptr: *mut u8 = /* FFI pointer or any other provenance */ ; assert!(ptr.cast::<Complex>().is_aligned(), "not aligned"); let complex_ptr = ptr.cast::<Complex>();
clippy::cast_ptr_alignment
triggers even when alignment checks are valid.Alternatively, users can use ptr::is_aligned_to
, which is still unstable (see #96284) and less verbose.
Here, the problem of invalid alignments discussed in #96284 are not relevant as it would be provided by core::mem::align_of
.
impl<T: ?Sized> *const T { pub fn is_aligned_for<U: Sized>(self) -> bool; } impl<T: ?Sized> *mut T { /* same */ } impl<T: ?Sized> NonNull<T> { /* same */ }Alternative:
try_cast_aligned
As stated and suggested by @hanna-kruppe, it would be wise to combine alignment check and cast as follows:
impl<T: ?Sized> *const T { pub fn try_cast_aligned<U: Sized>(self) -> Option<*const U>; } impl<T: ?Sized> *mut T { /* same */ } impl<T: ?Sized> NonNull<T> { /* same */ }
mirroring <[T]>::align_to
but at a lower level.
This ensures the pointer is cast to the exact same type as the one used for alignment checks.
Rare cases (such as FFI) where the boolean value is needed, one could use ptr.try_cast_aligned::<SomeType>().is_some()
.
The implementation would be a combination of is_aligned_to
and cast
, so it would compile down to the exact same assembly as the hypothetical is_aligned_for
.
The only downside of this solution is that it loses the verbosity of is_aligned_for
in such cases.
ptr::is_aligned
's implementation
Tracking issue (is_aligned_for
): Tracking Issue for pointer_is_aligned_for
rust#140980
PR (is_aligned_for
): Implement ptr::is_aligned_for
and NonNull::is_aligned_for
. rust#140982
Tracking issue (try_cast_aligned
): Tracking Issue for #![feature(pointer_try_cast_aligned)]
rust#141221
PR (try_cast_aligned
): Implement ptr::try_cast_aligned
and NonNull::try_cast_aligned
. rust#141222
kennytm and MolotovCherry
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4