rust: types: add Opaque::cast_from
Since commit b20fbbc08a ("rust: check type of `$ptr` in
`container_of!`") we have enforced that the field pointer passed to
container_of! must match the declared field. This caused mismatches when
using a pointer to bindings::x for fields of type Opaque<bindings::x>.
This situation encourages the user to simply pass field.cast() to the
container_of! macro, but this is not great because you might
accidentally pass a *mut bindings::y when the field type is
Opaque<bindings::x>, which would be wrong.
To help catch this kind of mistake, add a new Opaque::cast_from that
wraps a raw pointer in Opaque without changing the inner type. Also
update the docs to reflect this as well as some existing users.
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Andreas Hindborg <a.hindborg@kernel.org>
Acked-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Danilo Krummrich <dakr@kernel.org>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250624-opaque-from-raw-v2-1-e4da40bdc59c@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
This commit is contained in:
@@ -413,6 +413,11 @@ impl<T> Opaque<T> {
|
||||
pub const fn raw_get(this: *const Self) -> *mut T {
|
||||
UnsafeCell::raw_get(this.cast::<UnsafeCell<MaybeUninit<T>>>()).cast::<T>()
|
||||
}
|
||||
|
||||
/// The opposite operation of [`Opaque::raw_get`].
|
||||
pub const fn cast_from(this: *const T) -> *const Self {
|
||||
this.cast()
|
||||
}
|
||||
}
|
||||
|
||||
/// Types that are _always_ reference counted.
|
||||
|
||||
Reference in New Issue
Block a user