rust: ptr: add KnownSize trait to support DST size info extraction

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@garyguo.net>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Acked-by: Miguel Ojeda <ojeda@kernel.org>
Link: https://patch.msgid.link/20260302164239.284084-2-gary@kernel.org
[ Fix wording in doc-comment. - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
This commit is contained in:
Gary Guo
2026-03-02 16:42:34 +00:00
committed by Danilo Krummrich
parent 11439c4635
commit 08da98f18f
2 changed files with 27 additions and 1 deletions

View File

@@ -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 @@ macro_rules! impl_alignable_uint {
}
impl_alignable_uint!(u8, u16, u32, u64, usize);
/// Trait to represent compile-time known size information.
///
/// This is a generalization of [`size_of`] that works for dynamically sized types.
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>()
}
}