Commit 08da98f1 authored by Gary Guo's avatar Gary Guo Committed by Danilo Krummrich
Browse files

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: default avatarGary Guo <gary@garyguo.net>
Reviewed-by: default avatarBenno Lossin <lossin@kernel.org>
Acked-by: default avatarMiguel Ojeda <ojeda@kernel.org>
Link: https://patch.msgid.link/20260302164239.284084-2-gary@kernel.org


[ Fix wording in doc-comment. - Danilo ]
Signed-off-by: default avatarDanilo Krummrich <dakr@kernel.org>
parent 11439c46
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -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)]
+26 −1
Original line number Diff line number Diff line
@@ -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 [`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>()
    }
}