Use LazyLock for std environments and OnceBox for no_std

This commit is contained in:
Falk Woldmann Lu authored and Erich Gubler committed 2026-01-26 13:21:46 -05:00
1 parent 4d11f5f8de
commit 171617d00a
1 file changed
+32 -2
+32 -2
View File
@@ -1,15 +1,34 @@
#[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
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 {
@@ -19,6 +38,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;