Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions naga/src/racy_lock.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,35 @@
#[cfg(no_std)]
use alloc::boxed::Box;
#[cfg(no_std)]
use once_cell::race::OnceBox;
#[cfg(std)]
use std::sync::LazyLock;

/// An alternative to [`LazyLock`] based on [`OnceBox`].
#[cfg(std)]
type Inner<T> = LazyLock<T, fn() -> T>;
#[cfg(no_std)]
type Inner<T> = OnceBox<T>;

/// Lazy static helper that uses [`LazyLock`] with `std` and [`OnceBox`] otherwise.
///
/// [`LazyLock`]: https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html
/// [`OnceBox`]: https://docs.rs/once_cell/latest/once_cell/race/struct.OnceBox.html
pub struct RacyLock<T: 'static> {
inner: OnceBox<T>,
inner: Inner<T>,
#[cfg(no_std)]
init: fn() -> T,
}

impl<T: 'static> RacyLock<T> {
#[cfg(std)]
/// Creates a new [`RacyLock`], which will initialize using the provided `init` function.
pub const fn new(init: fn() -> T) -> Self {
Self {
inner: LazyLock::new(init),
}
}

#[cfg(no_std)]
/// Creates a new [`RacyLock`], which will initialize using the provided `init` function.
pub const fn new(init: fn() -> T) -> Self {
Self {
Expand All @@ -19,6 +39,17 @@ impl<T: 'static> RacyLock<T> {
}
}

#[cfg(std)]
impl<T: 'static> core::ops::Deref for RacyLock<T> {
type Target = T;

/// Loads the internal value, initializing it if required.
fn deref(&self) -> &Self::Target {
&self.inner
}
}

#[cfg(no_std)]
impl<T: 'static> core::ops::Deref for RacyLock<T> {
type Target = T;

Expand Down