Skip to content

Commit e944171

Browse files
wedsonafojeda
authored andcommitted
rust: add container_of! macro
This macro is used to obtain a pointer to an entire struct when given a pointer to a field in that struct. Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Tested-by: Alice Ryhl <aliceryhl@google.com> Signed-off-by: Matt Gilbride <mattgilbride@google.com> Link: https://lore.kernel.org/r/20240219-b4-rbtree-v2-1-0b113aab330d@google.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
1 parent 4951ddd commit e944171

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

rust/kernel/lib.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,35 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
101101
// SAFETY: FFI call.
102102
unsafe { bindings::BUG() };
103103
}
104+
105+
/// Produces a pointer to an object from a pointer to one of its fields.
106+
///
107+
/// # Safety
108+
///
109+
/// The pointer passed to this macro, and the pointer returned by this macro, must both be in
110+
/// bounds of the same allocation.
111+
///
112+
/// # Examples
113+
///
114+
/// ```
115+
/// # use kernel::container_of;
116+
/// struct Test {
117+
/// a: u64,
118+
/// b: u32,
119+
/// }
120+
///
121+
/// let test = Test { a: 10, b: 20 };
122+
/// let b_ptr = &test.b;
123+
/// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
124+
/// // in-bounds of the same allocation as `b_ptr`.
125+
/// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
126+
/// assert!(core::ptr::eq(&test, test_alias));
127+
/// ```
128+
#[macro_export]
129+
macro_rules! container_of {
130+
($ptr:expr, $type:ty, $($f:tt)*) => {{
131+
let ptr = $ptr as *const _ as *const u8;
132+
let offset: usize = ::core::mem::offset_of!($type, $($f)*);
133+
ptr.sub(offset) as *const $type
134+
}}
135+
}

0 commit comments

Comments
 (0)