Skip to content

Commit b2088ae

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 7378bd5 commit b2088ae

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

0 commit comments

Comments
 (0)