Skip to content

Commit

Permalink
rust: make UnsafeCell the outer type in Opaque
Browse files Browse the repository at this point in the history
[ Upstream commit 35cad61 ]

When combining `UnsafeCell` with `MaybeUninit`, it is idiomatic to use
`UnsafeCell` as the outer type. Intuitively, this is because a
`MaybeUninit<T>` might not contain a `T`, but we always want the effect
of the `UnsafeCell`, even if the inner value is uninitialized.

Now, strictly speaking, this doesn't really make a difference. The
compiler will always apply the `UnsafeCell` effect even if the inner
value is uninitialized. But I think we should follow the convention
here.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Gary Guo <gary@garyguo.net>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Link: https://lore.kernel.org/r/20230614115328.2825961-1-aliceryhl@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
Stable-dep-of: 0b4e3b6 ("rust: types: make `Opaque` be `!Unpin`")
Signed-off-by: Sasha Levin <sashal@kernel.org>
  • Loading branch information
Darksonn authored and gregkh committed Nov 8, 2023
1 parent 07256dc commit 7fba725
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions rust/kernel/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,17 +206,17 @@ impl<T, F: FnOnce(T)> Drop for ScopeGuard<T, F> {
///
/// This is meant to be used with FFI objects that are never interpreted by Rust code.
#[repr(transparent)]
pub struct Opaque<T>(MaybeUninit<UnsafeCell<T>>);
pub struct Opaque<T>(UnsafeCell<MaybeUninit<T>>);

impl<T> Opaque<T> {
/// Creates a new opaque value.
pub const fn new(value: T) -> Self {
Self(MaybeUninit::new(UnsafeCell::new(value)))
Self(UnsafeCell::new(MaybeUninit::new(value)))
}

/// Creates an uninitialised value.
pub const fn uninit() -> Self {
Self(MaybeUninit::uninit())
Self(UnsafeCell::new(MaybeUninit::uninit()))
}

/// Creates a pin-initializer from the given initializer closure.
Expand All @@ -240,15 +240,15 @@ impl<T> Opaque<T> {

/// Returns a raw pointer to the opaque data.
pub fn get(&self) -> *mut T {
UnsafeCell::raw_get(self.0.as_ptr())
UnsafeCell::get(&self.0).cast::<T>()
}

/// Gets the value behind `this`.
///
/// This function is useful to get access to the value without creating intermediate
/// references.
pub const fn raw_get(this: *const Self) -> *mut T {
UnsafeCell::raw_get(this.cast::<UnsafeCell<T>>())
UnsafeCell::raw_get(this.cast::<UnsafeCell<MaybeUninit<T>>>()).cast::<T>()
}
}

Expand Down

0 comments on commit 7fba725

Please sign in to comment.