zr/opaque.rs
1// Copyright 2026 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use core::cell::UnsafeCell;
6use core::mem::MaybeUninit;
7
8/// A wrapper for types that are opaque to Rust.
9///
10/// This is used to wrap C++ objects that Rust should not access directly.
11/// It provides a raw pointer to the inner data for use in FFI.
12#[repr(transparent)]
13pub struct Opaque<T>(MaybeUninit<UnsafeCell<T>>);
14
15impl<T> Opaque<T> {
16 /// Creates a new `Opaque` value.
17 pub const fn new(value: T) -> Self {
18 Self(MaybeUninit::new(UnsafeCell::new(value)))
19 }
20
21 /// Creates an uninitialized `Opaque` value.
22 pub const fn uninit() -> Self {
23 Self(MaybeUninit::uninit())
24 }
25
26 /// Returns a raw pointer to the opaque data.
27 pub fn get(&self) -> *mut T {
28 let ptr = self.0.as_ptr();
29 UnsafeCell::raw_get(ptr)
30 }
31}