naga/racy_lock.rs
1use alloc::boxed::Box;
2use once_cell::race::OnceBox;
3
4/// An alternative to [`LazyLock`] based on [`OnceBox`].
5///
6/// [`LazyLock`]: https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html
7pub struct RacyLock<T: 'static> {
8 inner: OnceBox<T>,
9 init: fn() -> T,
10}
11
12impl<T: 'static> RacyLock<T> {
13 /// Creates a new [`RacyLock`], which will initialize using the provided `init` function.
14 pub const fn new(init: fn() -> T) -> Self {
15 Self {
16 inner: OnceBox::new(),
17 init,
18 }
19 }
20}
21
22impl<T: 'static> core::ops::Deref for RacyLock<T> {
23 type Target = T;
24
25 /// Loads the internal value, initializing it if required.
26 fn deref(&self) -> &Self::Target {
27 self.inner.get_or_init(|| Box::new((self.init)()))
28 }
29}