Re: [PATCH 1/5] rust: ptr: add panicking index projection variant
From: Andreas Hindborg
Date: Mon Apr 27 2026 - 07:32:14 EST
"Gary Guo" <gary@xxxxxxxxxxx> writes:
> There have been a few cases where the programmer knows that the indices are
> in bounds but compiler cannot deduce that. This is also
> compiler-version-dependent, so using build indexing here can be
> problematic. On the other hand, it is also not ideal to use the fallible
> variant, as it adds error handling path that is never hit.
>
> Add a new panicking index projection for this scenario. Like all panicking
> operations, this should be used carefully only in cases where the user
> knows the index is going to be in bounds, and panicking would indicate
> something is catastrophically wrong.
>
> To signify this, require users to explicitly denote the type of index being
> used. The existing two types of index projections also gain the keyworded
> version, which will be the recommended way going forward.
>
> The keyworded syntax also paves the way of perhaps adding more flavors in
> the future, e.g. `unsafe` index projection. However, unless the code is
> extremely performance sensitive and bounds checking cannot be tolerated,
> panicking variant is safer and should be preferred, so it will be left to
> future when demand arises.
>
> Signed-off-by: Gary Guo <gary@xxxxxxxxxxx>
> ---
> rust/kernel/dma.rs | 3 ++
> rust/kernel/ptr/projection.rs | 98 +++++++++++++++++++++++++++++++++++--------
> 2 files changed, 84 insertions(+), 17 deletions(-)
>
> diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs
> index 4995ee5dc689..3e4d44749aaf 100644
> --- a/rust/kernel/dma.rs
> +++ b/rust/kernel/dma.rs
> @@ -1207,6 +1207,9 @@ macro_rules! dma_write {
> (@parse [$dma:expr] [$($proj:tt)*] [.$field:tt $($rest:tt)*]) => {
> $crate::dma_write!(@parse [$dma] [$($proj)* .$field] [$($rest)*])
> };
> + (@parse [$dma:expr] [$($proj:tt)*] [[$flavor:ident: $index:expr] $($rest:tt)*]) => {
> + $crate::dma_write!(@parse [$dma] [$($proj)* [$flavor: $index]] [$($rest)*])
> + };
> (@parse [$dma:expr] [$($proj:tt)*] [[$index:expr]? $($rest:tt)*]) => {
> $crate::dma_write!(@parse [$dma] [$($proj)* [$index]?] [$($rest)*])
> };
> diff --git a/rust/kernel/ptr/projection.rs b/rust/kernel/ptr/projection.rs
> index 140ea8e21617..845811795393 100644
> --- a/rust/kernel/ptr/projection.rs
> +++ b/rust/kernel/ptr/projection.rs
> @@ -26,14 +26,14 @@ fn from(_: OutOfBound) -> Self {
> ///
> /// # Safety
> ///
> -/// The implementation of `index` and `get` (if [`Some`] is returned) must ensure that, if provided
> -/// input pointer `slice` and returned pointer `output`, then:
> +/// The implementation of `index`, `build_index` and `get` (if [`Some`] is returned) must ensure
> +/// that, if provided input pointer `slice` and returned pointer `output`, then:
Since you are changing these lines I would suggest to rephrase for
better parsing:
For return value `output`, the implementation of `index`, `build_index`
and `get` (if [`Some`] is returned) must ensure that:
> /// - `output` has the same provenance as `slice`;
> /// - `output.byte_offset_from(slice)` is between 0 to
> /// `KnownSize::size(slice) - KnownSize::size(output)`.
> ///
> -/// This means that if the input pointer is valid, then pointer returned by `get` or `index` is
> -/// also valid.
> +/// This means that if the input pointer is valid, then pointer returned by `get`, `index` or
> +/// `build_index` is also valid.
> #[diagnostic::on_unimplemented(message = "`{Self}` cannot be used to index `{T}`")]
> #[doc(hidden)]
> pub unsafe trait ProjectIndex<T: ?Sized>: Sized {
> @@ -42,9 +42,12 @@ pub unsafe trait ProjectIndex<T: ?Sized>: Sized {
> /// Returns an index-projected pointer, if in bounds.
> fn get(self, slice: *mut T) -> Option<*mut Self::Output>;
>
> + /// Returns an index-projected pointer; panic if out of bounds.
> + fn index(self, slice: *mut T) -> *mut Self::Output;
> +
> /// Returns an index-projected pointer; fail the build if it cannot be proved to be in bounds.
> #[inline(always)]
> - fn index(self, slice: *mut T) -> *mut Self::Output {
> + fn build_index(self, slice: *mut T) -> *mut Self::Output {
> Self::get(self, slice).unwrap_or_else(|| build_error!())
> }
> }
> @@ -67,6 +70,11 @@ fn index(self, slice: *mut T) -> *mut Self::Output {
> fn index(self, slice: *mut [T; N]) -> *mut Self::Output {
> <I as ProjectIndex<[T]>>::index(self, slice)
> }
> +
> + #[inline(always)]
> + fn build_index(self, slice: *mut [T; N]) -> *mut Self::Output {
> + <I as ProjectIndex<[T]>>::build_index(self, slice)
> + }
> }
>
> // SAFETY: `get`-returned pointer has the same provenance as `slice` and the offset is checked to
> @@ -82,6 +90,14 @@ fn get(self, slice: *mut [T]) -> Option<*mut T> {
> Some(slice.cast::<T>().wrapping_add(self))
> }
> }
> +
> + #[inline(always)]
> + fn index(self, slice: *mut [T]) -> *mut T {
> + // Leverage Rust built-in operators for bounds checking.
> + // SAFETY: All non-null and aligned pointers are valid for ZST read.
> + unsafe { core::slice::from_raw_parts::<()>(core::ptr::dangling(), slice.len())[self] };
I think this would be more readable if you move the indexing operation
out of the unsafe block:
// SAFETY: All non-null and aligned pointers are valid for ZST read.
let slice = unsafe { core::slice::from_raw_parts::<()>(core::ptr::dangling(), slice.len()) };
// Leverage Rust built-in operators for bounds checking.
slice[self];
> + slice.cast::<T>().wrapping_add(self)
> + }
> }
>
> // SAFETY: `get`-returned pointer has the same provenance as `slice` and the offset is checked to
> @@ -100,6 +116,18 @@ fn get(self, slice: *mut [T]) -> Option<*mut [T]> {
> new_len,
> ))
> }
> +
> + #[inline(always)]
> + fn index(self, slice: *mut [T]) -> *mut [T] {
> + // Leverage Rust built-in operators for bounds checking.
> + // SAFETY: All non-null and aligned pointers are valid for ZST read.
> + unsafe {
> + _ = core::slice::from_raw_parts::<()>(core::ptr::dangling(), slice.len())[self.clone()];
Same comment regarding moving indexing to next line.
Side question: Why do you need to explicitly discard the return value
here (`_ = ...`) and not above?
Reviewed-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
Best regards,
Andreas Hindborg