From 35cad617df2eeef8440a38e82bb2d81ae32ca50d Mon Sep 17 00:00:00 2001 From: Alice Ryhl Date: Wed, 14 Jun 2023 11:53:28 +0000 Subject: [PATCH] rust: make `UnsafeCell` the outer type in `Opaque` When combining `UnsafeCell` with `MaybeUninit`, it is idiomatic to use `UnsafeCell` as the outer type. Intuitively, this is because a `MaybeUninit` 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 Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Reviewed-by: Martin Rodriguez Reboredo Link: https://lore.kernel.org/r/20230614115328.2825961-1-aliceryhl@google.com Signed-off-by: Miguel Ojeda --- rust/kernel/types.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index d479f8da8f38..c0b8bb1a7539 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -206,17 +206,17 @@ impl Drop for ScopeGuard { /// /// This is meant to be used with FFI objects that are never interpreted by Rust code. #[repr(transparent)] -pub struct Opaque(MaybeUninit>); +pub struct Opaque(UnsafeCell>); impl Opaque { /// 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. @@ -240,7 +240,7 @@ impl Opaque { /// 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::() } /// Gets the value behind `this`. @@ -248,7 +248,7 @@ impl Opaque { /// 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::raw_get(this.cast::>>()).cast::() } }