1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
//! Provides `Once`, `OnceState`, `OnceLock`
pub use implementation::{Once, OnceLock, OnceState};
#[cfg(feature = "std")]
use std::sync as implementation;
#[cfg(not(feature = "std"))]
mod implementation {
use core::{
fmt,
panic::{RefUnwindSafe, UnwindSafe},
};
/// Fallback implementation of `OnceLock` from the standard library.
pub struct OnceLock<T> {
inner: spin::Once<T>,
}
impl<T> OnceLock<T> {
/// Creates a new empty cell.
///
/// See the standard library for further details.
#[must_use]
pub const fn new() -> Self {
Self {
inner: spin::Once::new(),
}
}
/// Gets the reference to the underlying value.
///
/// See the standard library for further details.
pub fn get(&self) -> Option<&T> {
self.inner.get()
}
/// Gets the mutable reference to the underlying value.
///
/// See the standard library for further details.
pub fn get_mut(&mut self) -> Option<&mut T> {
self.inner.get_mut()
}
/// Sets the contents of this cell to `value`.
///
/// See the standard library for further details.
pub fn set(&self, value: T) -> Result<(), T> {
let mut value = Some(value);
self.inner.call_once(|| value.take().unwrap());
match value {
Some(value) => Err(value),
None => Ok(()),
}
}
/// Gets the contents of the cell, initializing it with `f` if the cell
/// was empty.
///
/// See the standard library for further details.
pub fn get_or_init<F>(&self, f: F) -> &T
where
F: FnOnce() -> T,
{
self.inner.call_once(f)
}
/// Consumes the `OnceLock`, returning the wrapped value. Returns
/// `None` if the cell was empty.
///
/// See the standard library for further details.
pub fn into_inner(mut self) -> Option<T> {
self.take()
}
/// Takes the value out of this `OnceLock`, moving it back to an uninitialized state.
///
/// See the standard library for further details.
pub fn take(&mut self) -> Option<T> {
if self.inner.is_completed() {
let mut inner = spin::Once::new();
core::mem::swap(&mut self.inner, &mut inner);
inner.try_into_inner()
} else {
None
}
}
}
impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceLock<T> {}
impl<T: UnwindSafe> UnwindSafe for OnceLock<T> {}
impl<T> Default for OnceLock<T> {
fn default() -> OnceLock<T> {
OnceLock::new()
}
}
impl<T: fmt::Debug> fmt::Debug for OnceLock<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_tuple("OnceLock");
match self.get() {
Some(v) => d.field(v),
None => d.field(&format_args!("<uninit>")),
};
d.finish()
}
}
impl<T: Clone> Clone for OnceLock<T> {
fn clone(&self) -> OnceLock<T> {
let cell = Self::new();
if let Some(value) = self.get() {
cell.set(value.clone()).ok().unwrap();
}
cell
}
}
impl<T> From<T> for OnceLock<T> {
fn from(value: T) -> Self {
let cell = Self::new();
cell.set(value).map(move |_| cell).ok().unwrap()
}
}
impl<T: PartialEq> PartialEq for OnceLock<T> {
fn eq(&self, other: &OnceLock<T>) -> bool {
self.get() == other.get()
}
}
impl<T: Eq> Eq for OnceLock<T> {}
/// Fallback implementation of `Once` from the standard library.
pub struct Once {
inner: OnceLock<()>,
}
impl Once {
/// Creates a new `Once` value.
///
/// See the standard library for further details.
#[expect(clippy::new_without_default, reason = "matching std::sync::Once")]
pub const fn new() -> Self {
Self {
inner: OnceLock::new(),
}
}
/// Performs an initialization routine once and only once. The given closure
/// will be executed if this is the first time `call_once` has been called,
/// and otherwise the routine will *not* be invoked.
///
/// See the standard library for further details.
pub fn call_once<F: FnOnce()>(&self, f: F) {
self.inner.get_or_init(f);
}
/// Performs the same function as [`call_once()`] except ignores poisoning.
///
/// See the standard library for further details.
pub fn call_once_force<F: FnOnce(&OnceState)>(&self, f: F) {
const STATE: OnceState = OnceState { _private: () };
self.call_once(move || f(&STATE));
}
/// Returns `true` if some [`call_once()`] call has completed
/// successfully. Specifically, `is_completed` will return false in
/// the following situations:
/// * [`call_once()`] was not called at all,
/// * [`call_once()`] was called, but has not yet completed,
/// * the [`Once`] instance is poisoned
///
/// See the standard library for further details.
pub fn is_completed(&self) -> bool {
self.inner.get().is_some()
}
}
impl RefUnwindSafe for Once {}
impl UnwindSafe for Once {}
impl fmt::Debug for Once {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Once").finish_non_exhaustive()
}
}
/// Fallback implementation of `OnceState` from the standard library.
pub struct OnceState {
_private: (),
}
impl OnceState {
/// Returns `true` if the associated [`Once`] was poisoned prior to the
/// invocation of the closure passed to [`Once::call_once_force()`].
///
/// See the standard library for further details.
pub fn is_poisoned(&self) -> bool {
false
}
}
impl fmt::Debug for OnceState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OnceState")
.field("poisoned", &self.is_poisoned())
.finish()
}
}
}