Re: [PATCH v4 1/3] rust: ptr: add `KnownSize` trait to support DST size info extraction
From: Benno Lossin
Date: Mon Mar 02 2026 - 13:57:56 EST
On Mon Mar 2, 2026 at 5:42 PM CET, Gary Guo wrote:
> From: Gary Guo <gary@xxxxxxxxxxx>
>
> Add a `KnownSize` trait which is used obtain a size from a raw pointer's
> metadata. This makes it possible to obtain size information on a raw slice
> pointer. This is similar to Rust `core::mem::size_of_val_raw` which is not
> yet stable.
>
> Signed-off-by: Gary Guo <gary@xxxxxxxxxxx>
Reviewed-by: Benno Lossin <lossin@xxxxxxxxxx>
Found a typo below.
> ---
> rust/kernel/lib.rs | 1 +
> rust/kernel/ptr.rs | 27 ++++++++++++++++++++++++++-
> 2 files changed, 27 insertions(+), 1 deletion(-)
>
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index 3da92f18f4ee..510cc7fe4961 100644
> --- a/rust/kernel/lib.rs
> +++ b/rust/kernel/lib.rs
> @@ -20,6 +20,7 @@
> #![feature(generic_nonzero)]
> #![feature(inline_const)]
> #![feature(pointer_is_aligned)]
> +#![feature(slice_ptr_len)]
> //
> // Stable since Rust 1.80.0.
> #![feature(slice_flatten)]
> diff --git a/rust/kernel/ptr.rs b/rust/kernel/ptr.rs
> index 5b6a382637fe..cf980a103acf 100644
> --- a/rust/kernel/ptr.rs
> +++ b/rust/kernel/ptr.rs
> @@ -2,7 +2,10 @@
>
> //! Types and functions to work with pointers and addresses.
>
> -use core::mem::align_of;
> +use core::mem::{
> + align_of,
> + size_of, //
> +};
> use core::num::NonZero;
>
> /// Type representing an alignment, which is always a power of two.
> @@ -225,3 +228,25 @@ fn align_up(self, alignment: Alignment) -> Option<Self> {
> }
>
> impl_alignable_uint!(u8, u16, u32, u64, usize);
> +
> +/// Trait to represent compile-time known size information.
> +///
> +/// This is a generalization of what [`size_of`] which works for dynamically sized types.
s/what//
Cheers,
Benno
> +pub trait KnownSize {
> + /// Get the size of an object of this type in bytes, with the metadata of the given pointer.
> + fn size(p: *const Self) -> usize;
> +}
> +
> +impl<T> KnownSize for T {
> + #[inline(always)]
> + fn size(_: *const Self) -> usize {
> + size_of::<T>()
> + }
> +}
> +
> +impl<T> KnownSize for [T] {
> + #[inline(always)]
> + fn size(p: *const Self) -> usize {
> + p.len() * size_of::<T>()
> + }
> +}