File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff 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+ }
You can’t perform that action at this time.
0 commit comments