mirror of
https://github.com/torvalds/linux.git
synced 2026-04-18 14:53:58 -04:00
rust: retain pointer mut-ness in container_of!
Avoid casting the input pointer to `*const _`, allowing the output pointer to be `*mut` if the input is `*mut`. This allows a number of `*const` to `*mut` conversions to be removed at the cost of slightly worse ergonomics when the macro is used with a reference rather than a pointer; the only example of this was in the macro's own doctest. Reviewed-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Signed-off-by: Tamir Duberstein <tamird@gmail.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Link: https://lore.kernel.org/r/20250409-container-of-mutness-v1-1-64f472b94534@gmail.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
This commit is contained in:
committed by
Miguel Ojeda
parent
a3b2347343
commit
74d6a606c2
@@ -205,7 +205,7 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
|
||||
/// }
|
||||
///
|
||||
/// let test = Test { a: 10, b: 20 };
|
||||
/// let b_ptr = &test.b;
|
||||
/// let b_ptr: *const _ = &test.b;
|
||||
/// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be
|
||||
/// // in-bounds of the same allocation as `b_ptr`.
|
||||
/// let test_alias = unsafe { container_of!(b_ptr, Test, b) };
|
||||
@@ -214,9 +214,8 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
|
||||
#[macro_export]
|
||||
macro_rules! container_of {
|
||||
($ptr:expr, $type:ty, $($f:tt)*) => {{
|
||||
let ptr = $ptr as *const _ as *const u8;
|
||||
let offset: usize = ::core::mem::offset_of!($type, $($f)*);
|
||||
ptr.sub(offset) as *const $type
|
||||
$ptr.byte_sub(offset).cast::<$type>()
|
||||
}}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user