Skip to content

Commit 4051f2f

Browse files
author
Valentin Obst
committed
rust/kernel: add field_size macro
Add a macro to determine the size of a structure field at compile time. This is used by the CCA abstractions to ensure that the private data of every CCA will fit into the space that the kernel provides for it. Signed-off-by: Valentin Obst <kernel@valentinobst.de>
1 parent 021136b commit 4051f2f

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

rust/kernel/types.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,3 +398,36 @@ pub enum Either<L, R> {
398398
/// Constructs an instance of [`Either`] containing a value of type `R`.
399399
Right(R),
400400
}
401+
402+
/// Returns the size of a struct field in bytes.
403+
///
404+
/// This macro can be used in const contexts.
405+
///
406+
/// # Examples
407+
///
408+
/// ```
409+
/// use kernel::field_size;
410+
///
411+
/// struct Foo {
412+
/// bar: u64,
413+
/// baz: [i8; 100],
414+
/// }
415+
///
416+
/// assert_eq!(field_size!(Foo, bar), 8);
417+
/// assert_eq!(field_size!(Foo, baz), 100);
418+
/// ```
419+
// Link: https://stackoverflow.com/a/70222282
420+
#[macro_export]
421+
macro_rules! field_size {
422+
($t:ty, $field:ident) => {{
423+
let m = core::mem::MaybeUninit::<$t>::uninit();
424+
// SAFETY: It is OK to dereference invalid pointers inside of
425+
// `addr_of!`.
426+
let p = unsafe { core::ptr::addr_of!((*m.as_ptr()).$field) };
427+
428+
const fn size_of_raw<T>(_: *const T) -> usize {
429+
core::mem::size_of::<T>()
430+
}
431+
size_of_raw(p)
432+
}};
433+
}

0 commit comments

Comments
 (0)