Re: [PATCH 1/5] rust: ptr: add panicking index projection variant
From: Gary Guo
Date: Mon Apr 27 2026 - 08:45:26 EST
On Mon Apr 27, 2026 at 12:24 PM BST, Andreas Hindborg wrote:
>> +
>> + #[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?
Because the result of indexing is a slice, which is unsized.
Best,
Gary
>
>
> Reviewed-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
>
>
> Best regards,
> Andreas Hindborg