Skip to content

Commit b9ecf9b

Browse files
wedsonafojeda
authored andcommitted
rust: types: add Opaque type
Add the `Opaque` type, which is meant to be used with FFI objects that are never interpreted by Rust code, e.g.: struct Waiter { completion: Opaque<bindings::completion>, next: *mut Waiter, } It has the advantage that the objects don't have to be zero-initialised before calling their init functions, making the code performance closer to C. Signed-off-by: Wedson Almeida Filho <[email protected]> [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda <[email protected]>
1 parent ba20915 commit b9ecf9b

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

rust/kernel/types.rs

+25
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,31 @@
22

33
//! Kernel types.
44
5+
use core::{cell::UnsafeCell, mem::MaybeUninit};
6+
7+
/// Stores an opaque value.
8+
///
9+
/// This is meant to be used with FFI objects that are never interpreted by Rust code.
10+
#[repr(transparent)]
11+
pub struct Opaque<T>(MaybeUninit<UnsafeCell<T>>);
12+
13+
impl<T> Opaque<T> {
14+
/// Creates a new opaque value.
15+
pub const fn new(value: T) -> Self {
16+
Self(MaybeUninit::new(UnsafeCell::new(value)))
17+
}
18+
19+
/// Creates an uninitialised value.
20+
pub const fn uninit() -> Self {
21+
Self(MaybeUninit::uninit())
22+
}
23+
24+
/// Returns a raw pointer to the opaque data.
25+
pub fn get(&self) -> *mut T {
26+
UnsafeCell::raw_get(self.0.as_ptr())
27+
}
28+
}
29+
530
/// A sum type that always holds either a value of type `L` or `R`.
631
pub enum Either<L, R> {
732
/// Constructs an instance of [`Either`] containing a value of type `L`.

0 commit comments

Comments
 (0)