Skip to content

Commit 08da98f

Browse files
nbdd0121Danilo Krummrich
authored andcommitted
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>
1 parent 11439c4 commit 08da98f

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#![feature(generic_nonzero)]
2121
#![feature(inline_const)]
2222
#![feature(pointer_is_aligned)]
23+
#![feature(slice_ptr_len)]
2324
//
2425
// Stable since Rust 1.80.0.
2526
#![feature(slice_flatten)]

rust/kernel/ptr.rs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22

33
//! Types and functions to work with pointers and addresses.
44
5-
use core::mem::align_of;
5+
use core::mem::{
6+
align_of,
7+
size_of, //
8+
};
69
use core::num::NonZero;
710

811
/// Type representing an alignment, which is always a power of two.
@@ -225,3 +228,25 @@ macro_rules! impl_alignable_uint {
225228
}
226229

227230
impl_alignable_uint!(u8, u16, u32, u64, usize);
231+
232+
/// Trait to represent compile-time known size information.
233+
///
234+
/// This is a generalization of [`size_of`] that works for dynamically sized types.
235+
pub trait KnownSize {
236+
/// Get the size of an object of this type in bytes, with the metadata of the given pointer.
237+
fn size(p: *const Self) -> usize;
238+
}
239+
240+
impl<T> KnownSize for T {
241+
#[inline(always)]
242+
fn size(_: *const Self) -> usize {
243+
size_of::<T>()
244+
}
245+
}
246+
247+
impl<T> KnownSize for [T] {
248+
#[inline(always)]
249+
fn size(p: *const Self) -> usize {
250+
p.len() * size_of::<T>()
251+
}
252+
}

0 commit comments

Comments
 (0)