Skip to content

Commit 8335dc8

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.
1 parent 7cb027a commit 8335dc8

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

0 commit comments

Comments
 (0)