once_cell_no_std 0.2.1

Sync single assignment cells for `no_std`
Documentation
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
// Forked from `once_cell v1.21.3` crate by @matklad
// Original code available at https://github.com/matklad/once_cell/tree/v1.21.3

#![doc = include_str!("../README.md")]
//!
//! # Implementation details
//!
//! The implementation is heavily based on the
//! [`once_cell`](https://github.com/matklad/once_cell) crate by @matklad, especially the
//! [implementation for parking-lot](https://github.com/matklad/once_cell/blob/master/src/imp_pl.rs).
#![no_std]
#![deny(missing_docs)]
#![warn(clippy::undocumented_unsafe_blocks)]
// This crate must not panic: a single reachable panic pulls `core::panicking` and the formatting
// machinery into every binary that links it, and breaks users who forbid panics outright. These
// lints catch the ways a panic is usually introduced; `ci/no-panic.sh` checks the compiled output
// for the ways they cannot see, such as `assert!`.
#![warn(
    clippy::panic,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::unreachable,
    clippy::todo,
    clippy::unimplemented,
    clippy::indexing_slicing,
    clippy::arithmetic_side_effects
)]

use core::{fmt, mem};

/// Defines a function that is `const` everywhere except in loom test builds, whose atomics cannot
/// be constructed in a const context. The body is written once.
macro_rules! const_fn {
    ($(#[$attr:meta])* $vis:vis const fn $($rest:tt)*) => {
        $(#[$attr])*
        #[cfg(not(all(test, loom)))]
        $vis const fn $($rest)*

        $(#[$attr])*
        #[cfg(all(test, loom))]
        $vis fn $($rest)*
    };
}

mod imp;
mod loom;
pub mod error;

#[cfg(no_panic_check)]
mod no_panic_check;

#[cfg(all(test, loom))]
mod loom_tests;

use imp::OnceCell as Imp;

use crate::error::{ConcurrentInitialization, InitError, InsertError, SetError};

/// The outcome of a successful [`OnceCell::get_or_insert`] call.
///
/// Either variant means the cell holds a value and that [`stored`](Self::stored) hands out a
/// reference to it. They differ only in _whose_ value that is: the one passed to `get_or_insert`,
/// or one that an earlier caller had already put there.
///
/// # Example
///
/// ```
/// use once_cell_no_std::{Insertion, OnceCell};
///
/// let cell = OnceCell::new();
///
/// // the cell was empty, so the value went in
/// let insertion = cell.get_or_insert(92).unwrap();
/// assert_eq!(insertion, Insertion::Inserted(&92));
/// assert!(insertion.was_inserted());
///
/// // the cell was full, so the value is handed back instead of being dropped
/// let insertion = cell.get_or_insert(62).unwrap();
/// assert_eq!(insertion, Insertion::AlreadyInitialized { stored: &92, rejected: 62 });
/// assert_eq!(insertion.into_rejected_value(), Some(62));
///
/// // either way, `stored` is the value that is in the cell
/// assert_eq!(cell.get_or_insert(17).unwrap().stored(), &92);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Insertion<'a, T> {
    /// The cell was empty, so the value was inserted into it.
    Inserted(&'a T),
    /// The cell already held a value, which was left untouched.
    AlreadyInitialized {
        /// A reference to the value that is stored in the cell.
        stored: &'a T,
        /// The value that was not inserted.
        rejected: T,
    },
}

impl<'a, T> Insertion<'a, T> {
    /// Returns a reference to the value that is stored in the cell.
    ///
    /// This is the value passed to [`get_or_insert`](OnceCell::get_or_insert) for
    /// [`Inserted`](Self::Inserted), and the value an earlier caller stored for
    /// [`AlreadyInitialized`](Self::AlreadyInitialized). In both cases it is the value that
    /// [`OnceCell::get`] returns from now on, since an initialized cell keeps its value.
    #[inline]
    #[must_use]
    pub fn stored(&self) -> &'a T {
        match self {
            Insertion::Inserted(stored) | Insertion::AlreadyInitialized { stored, .. } => stored,
        }
    }

    /// Returns whether the value was inserted into the cell.
    #[inline]
    #[must_use]
    pub fn was_inserted(&self) -> bool {
        matches!(self, Insertion::Inserted(_))
    }

    /// Returns the value that was not inserted, or `None` if it was.
    #[inline]
    #[must_use]
    pub fn into_rejected_value(self) -> Option<T> {
        match self {
            Insertion::Inserted(_) => None,
            Insertion::AlreadyInitialized { rejected, .. } => Some(rejected),
        }
    }
}

/// A thread-safe cell which can be written to only once.
///
/// `OnceCell` provides `&` references to the contents without RAII guards.
///
/// Reading a non-`None` value out of `OnceCell` establishes a
/// happens-before relationship with a corresponding write. For example, if
/// thread A initializes the cell with `get_or_init(f)`, and thread B
/// subsequently reads the result of this call, B also observes all the side
/// effects of `f`.
///
/// `OnceCell` guarantees that at most one initialization function will be called to compute the
/// value. If two threads of execution call [`get_or_init`](Self::get_or_init) (or similar) concurrently, one of them
/// will return a [ConcurrentInitialization] error. It's up to the caller to decide how to handle
/// this error (e.g. wait and retry until the value is initialized by the other thread or panic if
/// this situation is unexpected).
///
/// The alternative to returning the [ConcurrentInitialization] error would be to let one of the
/// threads wait. If this is what you prefer, check out the original
/// [`once_cell::OnceCell`](https://docs.rs/once_cell/1.21.3/once_cell/sync/struct.OnceCell.html)
/// type that this crate is forked from. Note that waiting requires some form of OS support, but
/// also supports `no_std` use cases through its `critical-section` feature.
///
/// # Example
/// ```
/// use once_cell_no_std::OnceCell;
///
/// static CELL: OnceCell<String> = OnceCell::new();
/// assert!(CELL.get().is_none());
///
/// std::thread::spawn(|| {
///     let value: &String = CELL.get_or_init(|| {
///         "Hello, World!".to_string()
///     }).unwrap();
///     assert_eq!(value, "Hello, World!");
/// }).join().unwrap();
///
/// let value: Option<&String> = CELL.get();
/// assert!(value.is_some());
/// assert_eq!(value.unwrap().as_str(), "Hello, World!");
/// ```
///
/// # Handling concurrent initialization
///
/// Since this type never blocks, it is up to the caller to decide what to do when it runs into a
/// concurrent initialization. Every method that can run into it reports it as an explicit error,
/// so a caller that wants to wait can simply retry. See
/// [Waiting for a concurrent initialization](crate#waiting-for-a-concurrent-initialization) for a
/// spin-retry helper, how it compares to `spin::Once` and `lazy_static`, and when spinning is the
/// wrong choice.
///
/// If the value already exists instead of being computed by an init function, use
/// [`set`](Self::set) or [`get_or_insert`](Self::get_or_insert) in the same way: their errors hand
/// the value back, so the retry does not need to clone it.
pub struct OnceCell<T>(Imp<T>);

impl<T> Default for OnceCell<T> {
    fn default() -> OnceCell<T> {
        OnceCell::new()
    }
}

impl<T: fmt::Debug> fmt::Debug for OnceCell<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.get_or_reason() {
            Ok(value) => f.debug_tuple("OnceCell").field(value).finish(),
            Err(CellState::Initializing) => f.write_str("OnceCell(Initializing)"),
            Err(_) => f.write_str("OnceCell(Uninit)"),
        }
    }
}

/// Clones the cell, and the value it holds if there is one.
///
/// A cell that another caller is currently initializing counts as empty, because this type never
/// blocks: the clone is empty, and initializing it later has no effect on the original. Cloning a
/// cell that is being written to concurrently is therefore racy by nature — whether the value is
/// carried over depends on the timing.
impl<T: Clone> Clone for OnceCell<T> {
    fn clone(&self) -> OnceCell<T> {
        match self.get() {
            Some(value) => Self::with_value(value.clone()),
            None => Self::new(),
        }
    }

    fn clone_from(&mut self, source: &Self) {
        match (self.get_mut(), source.get()) {
            (Some(this), Some(source)) => this.clone_from(source),
            _ => *self = source.clone(),
        }
    }
}

impl<T> From<T> for OnceCell<T> {
    fn from(value: T) -> Self {
        Self::with_value(value)
    }
}

/// Compares the values the two cells hold, if any.
///
/// Two empty cells are equal, and an empty cell differs from a full one. A cell that another
/// caller is currently initializing counts as empty, so it compares equal to an empty cell and
/// unequal to a full one — including to the value it is about to hold. Comparing a cell that is
/// being written to concurrently is therefore racy by nature, and the result can change from one
/// call to the next.
impl<T: PartialEq> PartialEq for OnceCell<T> {
    fn eq(&self, other: &OnceCell<T>) -> bool {
        self.get() == other.get()
    }
}

impl<T: Eq> Eq for OnceCell<T> {}

impl<T> OnceCell<T> {
    const_fn! {
        /// Creates a new empty cell.
        #[inline]
        #[must_use]
        pub const fn new() -> OnceCell<T> {
            OnceCell(Imp::new())
        }
    }

    const_fn! {
        /// Creates a new initialized cell.
        #[inline]
        #[must_use]
        pub const fn with_value(value: T) -> OnceCell<T> {
            OnceCell(Imp::with_value(value))
        }
    }

    /// Returns whether the cell is initialized.
    ///
    /// This method never blocks. It only reports a snapshot of the cell state, which might have
    /// changed again by the time the returned value is used.
    ///
    /// Prefer [`get`](Self::get) if you need the value itself: it performs the same check, but
    /// hands out a reference in the same step. Use [`state`](Self::state) if you also need to know
    /// whether an initialization is currently in progress.
    ///
    /// # Example
    ///
    /// ```
    /// use once_cell_no_std::OnceCell;
    ///
    /// let cell = OnceCell::new();
    /// assert!(!cell.is_initialized());
    ///
    /// cell.set(92).unwrap();
    /// assert!(cell.is_initialized());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_initialized(&self) -> bool {
        self.0.is_initialized()
    }

    /// Gets the reference to the underlying value.
    ///
    /// Returns `None` if the cell is empty, or being initialized. This
    /// method never blocks.
    ///
    /// The two cases are not distinguished here, because neither one supports a decision: an empty
    /// cell might be initialized by the time the caller acts on the `None`, and an initialization
    /// in progress might fail and leave the cell empty again.
    ///
    /// Use [`get_or_init`](Self::get_or_init), [`set`](Self::set), or [`get_or_insert`](Self::get_or_insert)
    /// when the difference has to be acted upon. They resolve the race atomically and report
    /// contention as a [`ConcurrentInitialization`] error that describes the cell at the instant
    /// of the attempt, rather than at some earlier point in time. Use [`state`](Self::state) when
    /// the difference only needs to be reported, as in logging or a health check.
    ///
    /// # Example
    ///
    /// ```
    /// use once_cell_no_std::OnceCell;
    ///
    /// let cell = OnceCell::new();
    /// assert_eq!(cell.get(), None);
    ///
    /// cell.set(92).unwrap();
    /// assert_eq!(cell.get(), Some(&92));
    /// ```
    #[inline]
    #[must_use]
    pub fn get(&self) -> Option<&T> {
        self.get_or_reason().ok()
    }

    /// Gets the value, or the state that explains why it is not available.
    ///
    /// This is the primitive that [`get`](Self::get) and the [`Debug`](fmt::Debug) implementation
    /// are built from. It exists to keep the `unsafe` read behind a single safe interface, and to
    /// answer from one atomic load, so that the reported state and the value cannot disagree.
    ///
    /// The `Err` value is never [`CellState::Initialized`].
    ///
    /// This is deliberately not public: [`state`](Self::state) already exposes the state, and
    /// because `Initialized` is stable, `state` followed by `get` observes the same thing without
    /// needing a combined accessor.
    #[inline]
    fn get_or_reason(&self) -> Result<&T, CellState> {
        match self.0.state() {
            // SAFETY: the `Acquire` load in `state` reported the cell as initialized, which also
            // synchronizes the write of the value to this thread.
            CellState::Initialized => Ok(unsafe { self.get_unchecked() }),
            state => Err(state),
        }
    }

    /// Returns a snapshot of the cell state.
    ///
    /// Unlike [`is_initialized`](Self::is_initialized), this distinguishes an empty cell from one
    /// that another caller is currently initializing. This method never blocks.
    ///
    /// The result describes the cell at the moment of the call and is intended for reporting, not
    /// for deciding what to do next. See [`CellState`] for why, and for which of the three states
    /// can be relied upon afterwards.
    ///
    /// # Example
    ///
    /// ```
    /// use once_cell_no_std::{CellState, OnceCell};
    ///
    /// let cell = OnceCell::new();
    /// assert_eq!(cell.state(), CellState::Uninitialized);
    ///
    /// cell.set("hello").unwrap();
    /// assert_eq!(cell.state(), CellState::Initialized);
    /// assert_eq!(cell.get(), Some(&"hello"));
    /// ```
    #[inline]
    #[must_use]
    pub fn state(&self) -> CellState {
        self.0.state()
    }

    /// Gets the mutable reference to the underlying value.
    ///
    /// Returns `None` if the cell is empty.
    ///
    /// Unlike [`get`](Self::get), this is unambiguous: a `None` return value always means that
    /// the cell is empty, never that an initialization is in progress. Since this method requires
    /// `&mut` access, no other caller can hold the shared reference that a concurrent
    /// initialization needs, so the ambiguity cannot arise in the first place.
    ///
    /// This method is allowed to violate the invariant of writing to a `OnceCell`
    /// at most once because it requires `&mut` access to `self`. As with all
    /// interior mutability, `&mut` access permits arbitrary modification:
    ///
    /// ```
    /// use once_cell_no_std::OnceCell;
    ///
    /// let mut cell: OnceCell<u32> = OnceCell::new();
    /// cell.set(92).unwrap();
    /// cell = OnceCell::new();
    /// ```
    #[inline]
    #[must_use]
    pub fn get_mut(&mut self) -> Option<&mut T> {
        self.0.get_mut()
    }

    /// Get the reference to the underlying value, without checking if the
    /// cell is initialized.
    ///
    /// # Safety
    ///
    /// Caller must ensure that the cell is in initialized state, and that
    /// the contents are acquired by (synchronized to) this thread.
    #[inline]
    #[must_use]
    pub unsafe fn get_unchecked(&self) -> &T {
        // SAFETY: the caller guarantees that the cell is initialized and synchronized to this
        // thread, which is exactly what the inner method requires.
        unsafe { self.0.get_unchecked() }
    }

    /// Sets the contents of this cell to `value`.
    ///
    /// Returns `Ok(())` if the cell was empty. If the cell was already full, a
    /// [`SetError::AlreadyInitialized`] error is returned. If the cell is concurrently being
    /// initialized by another caller, a [`SetError::ConcurrentInitialization`] error is returned.
    ///
    /// Both error variants give `value` back to the caller, so that it can be reused, e.g. to
    /// retry after a concurrent initialization has finished.
    ///
    /// Use [`get_or_insert`](Self::get_or_insert) if you also need a reference to the value that ends up in the
    /// cell.
    ///
    /// # Example
    ///
    /// ```
    /// use once_cell_no_std::{OnceCell, error::SetError};
    ///
    /// static CELL: OnceCell<i32> = OnceCell::new();
    ///
    /// fn main() {
    ///     assert!(CELL.get().is_none());
    ///
    ///     std::thread::spawn(|| {
    ///         assert_eq!(CELL.set(92), Ok(()));
    ///     }).join().unwrap();
    ///
    ///     assert_eq!(CELL.set(62), Err(SetError::AlreadyInitialized(62)));
    ///     assert_eq!(CELL.get(), Some(&92));
    /// }
    /// ```
    pub fn set(&self, value: T) -> Result<(), SetError<T>> {
        match self.get_or_insert(value)? {
            Insertion::Inserted(_) => Ok(()),
            Insertion::AlreadyInitialized { rejected, .. } => {
                Err(SetError::AlreadyInitialized(rejected))
            }
        }
    }

    /// Gets the contents of the cell, initializing it with `value` if the cell was empty.
    ///
    /// This is [`get_or_init`](Self::get_or_init) for a value that already exists, instead of one
    /// computed by a closure. Whether or not `value` is the one that ends up in the cell, the
    /// returned [`Insertion`] hands out a reference to whatever is stored:
    ///
    /// ```
    /// # use once_cell_no_std::OnceCell;
    /// # let cell = OnceCell::new();
    /// # let value = 92;
    /// let stored: &i32 = cell.get_or_insert(value)?.stored();
    /// # Ok::<(), once_cell_no_std::error::InsertError<i32>>(())
    /// ```
    ///
    /// An already initialized cell is therefore not an error. The only failure is a concurrent
    /// initialization by another caller, which leaves no value to hand out at all. Its
    /// [`InsertError`] gives `value` back, so it can be reused for a retry rather than dropped.
    ///
    /// Use [`set`](Self::set) instead when being the caller that initializes the cell is the point,
    /// rather than obtaining the value: it reports an already initialized cell as an error, and its
    /// [`SetError`] does not borrow the cell, so it can be propagated independently.
    ///
    /// # Example
    ///
    /// ```
    /// use once_cell_no_std::{Insertion, OnceCell};
    ///
    /// let cell = OnceCell::new();
    /// assert!(cell.get().is_none());
    ///
    /// assert_eq!(cell.get_or_insert(92), Ok(Insertion::Inserted(&92)));
    /// assert_eq!(
    ///     cell.get_or_insert(62),
    ///     Ok(Insertion::AlreadyInitialized { stored: &92, rejected: 62 })
    /// );
    ///
    /// assert_eq!(cell.get(), Some(&92));
    /// ```
    pub fn get_or_insert(&self, value: T) -> Result<Insertion<'_, T>, InsertError<T>> {
        let mut value = Some(value);
        let stored = match self.get_or_init(|| {
            debug_assert!(value.is_some(), "init closure called twice");
            // SAFETY: `imp::try_initialize_inner` contains a single call to the init closure, in
            // the arm that won the `INCOMPLETE` -> `RUNNING` compare-exchange, and that arm
            // returns immediately afterwards. The closure therefore runs at most once, so `value`
            // has not been taken yet.
            unsafe { value.take().unwrap_unchecked() }
        }) {
            Ok(stored) => stored,
            Err(ConcurrentInitialization) => {
                debug_assert!(value.is_some(), "init closure ran despite a concurrent init");
                // SAFETY: `imp::try_initialize_inner` returns `ConcurrentInitialization` only from
                // the arm that observed the cell in the `RUNNING` state, which does not call the
                // init closure. The closure never ran, so `value` is still there.
                let value = unsafe { value.take().unwrap_unchecked() };
                return Err(InsertError(value));
            }
        };
        Ok(match value {
            None => Insertion::Inserted(stored),
            Some(rejected) => Insertion::AlreadyInitialized { stored, rejected },
        })
    }

    /// Gets the contents of the cell, initializing it with `f` if the cell
    /// was empty.
    ///
    /// Many callers may invoke `get_or_init` concurrently with different initializing functions,
    /// but it is guaranteed that at most one of them is executed. The other callers receive a
    /// [`ConcurrentInitialization`] error and their `f` is dropped without ever being called.
    ///
    /// # Panics
    ///
    /// If `f` panics, the panic is propagated to the caller, and the cell
    /// remains uninitialized.
    ///
    /// # Reentrancy
    ///
    /// Calling back into the same cell from `f` is safe and never deadlocks, because this type
    /// never blocks. The cell counts as concurrently initializing while `f` runs, so a nested
    /// [`get_or_init`](Self::get_or_init), [`set`](Self::set), or [`get_or_insert`](Self::get_or_insert) on the
    /// same cell returns a [`ConcurrentInitialization`] error.
    ///
    /// Note that such a nested call can never succeed, so `f` must be able to make progress
    /// without it. In particular, retrying in a loop like the one shown in the
    /// [type documentation](Self#handling-concurrent-initialization) does hang when used
    /// reentrantly, since the initialization it waits for is the one that is blocked on the loop.
    ///
    /// # Example
    /// ```
    /// use once_cell_no_std::OnceCell;
    ///
    /// let cell = OnceCell::new();
    /// let value = cell.get_or_init(|| 92).unwrap();
    /// assert_eq!(value, &92);
    /// let value = cell.get_or_init(|| unreachable!()).unwrap();
    /// assert_eq!(value, &92);
    /// ```
    pub fn get_or_init<F>(&self, f: F) -> Result<&T, ConcurrentInitialization>
    where
        F: FnOnce() -> T,
    {
        enum Void {}
        self.get_or_try_init(|| Ok::<T, Void>(f())).map_err(|error| match error {
            InitError::InitFunctionFailed(void) => match void {},
            InitError::ConcurrentInitialization => ConcurrentInitialization,
        })
    }

    /// Gets the contents of the cell, initializing it with `f` if
    /// the cell was empty. If the cell was empty and `f` failed, an
    /// [`InitError::InitFunctionFailed`] error is returned.
    ///
    /// If the cell is concurrently being initialized by another caller, an
    /// [`InitError::ConcurrentInitialization`] error is returned. In that case `f` was _not_
    /// executed.
    ///
    /// # Retrying after a concurrent initialization
    ///
    /// An `f` that is not executed is dropped, together with everything that it captured. If `f`
    /// owns a resource that is needed for a retry, keep the ownership in the surrounding scope and
    /// let `f` borrow it:
    ///
    /// ```
    /// use once_cell_no_std::{error::InitError, OnceCell};
    ///
    /// # struct Uart;
    /// # struct Driver;
    /// # impl Driver { fn new(_uart: Uart) -> Driver { Driver } }
    /// let cell = OnceCell::new();
    /// let mut uart = Some(Uart);
    ///
    /// let result = cell.get_or_try_init(|| -> Result<_, ()> {
    ///     // `f` is called at most once, so the `Option` is always `Some` here
    ///     Ok(Driver::new(uart.take().expect("init function called twice")))
    /// });
    ///
    /// match result {
    ///     // the cell is initialized now, either by `f` or by an earlier caller
    ///     Ok(_driver) => {}
    ///     // `f` never ran, so `uart` is still available for another attempt
    ///     Err(InitError::ConcurrentInitialization) => assert!(uart.is_some()),
    ///     // `f` never returns an error in this example
    ///     Err(InitError::InitFunctionFailed(())) => unreachable!(),
    /// }
    /// ```
    ///
    /// Note that this is only needed for resources that cannot be recreated. If the value itself
    /// already exists, prefer [`set`](Self::set) or [`get_or_insert`](Self::get_or_insert), whose errors
    /// hand it back directly.
    ///
    /// # Panics
    ///
    /// If `f` panics, the panic is propagated to the caller, and
    /// the cell remains uninitialized.
    ///
    /// # Reentrancy
    ///
    /// Calling back into the same cell from `f` is safe and never deadlocks, because this type
    /// never blocks. The cell counts as concurrently initializing while `f` runs, so a nested
    /// [`get_or_try_init`](Self::get_or_try_init), [`set`](Self::set), or
    /// [`get_or_insert`](Self::get_or_insert) on the same cell returns a
    /// [`InitError::ConcurrentInitialization`] error.
    ///
    /// Note that such a nested call can never succeed, so `f` must be able to make progress
    /// without it. In particular, retrying in a loop like the one shown in the
    /// [type documentation](Self#handling-concurrent-initialization) does hang when used
    /// reentrantly, since the initialization it waits for is the one that is blocked on the loop.
    ///
    /// # Example
    /// ```
    /// use once_cell_no_std::{OnceCell, error::InitError};
    ///
    /// let cell = OnceCell::new();
    /// assert_eq!(
    ///     cell.get_or_try_init(|| Err(())),
    ///     Err(InitError::InitFunctionFailed(()))
    /// );
    /// assert!(cell.get().is_none());
    /// let value = cell.get_or_try_init(|| -> Result<i32, ()> {
    ///     Ok(92)
    /// });
    /// assert_eq!(value, Ok(&92));
    /// assert_eq!(cell.get(), Some(&92))
    /// ```
    pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, InitError<E>>
    where
        F: FnOnce() -> Result<T, E>,
    {
        // Fast path check
        if let Some(value) = self.get() {
            return Ok(value);
        }

        self.0.try_initialize(f)?;

        debug_assert!(self.0.is_initialized());
        // SAFETY: `try_initialize` returned `Ok`, so the cell is initialized and the write is
        // synchronized to this thread, either because this call performed it or because the
        // `Acquire` load that observed `COMPLETE` did.
        Ok(unsafe { self.get_unchecked() })
    }

    /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state.
    ///
    /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized.
    ///
    /// # Examples
    ///
    /// ```
    /// use once_cell_no_std::OnceCell;
    ///
    /// let mut cell: OnceCell<String> = OnceCell::new();
    /// assert_eq!(cell.take(), None);
    ///
    /// let mut cell = OnceCell::new();
    /// cell.set("hello".to_string()).unwrap();
    /// assert_eq!(cell.take(), Some("hello".to_string()));
    /// assert_eq!(cell.get(), None);
    /// ```
    ///
    /// This method is allowed to violate the invariant of writing to a `OnceCell`
    /// at most once because it requires `&mut` access to `self`. As with all
    /// interior mutability, `&mut` access permits arbitrary modification:
    ///
    /// ```
    /// use once_cell_no_std::OnceCell;
    ///
    /// let mut cell: OnceCell<u32> = OnceCell::new();
    /// cell.set(92).unwrap();
    /// cell = OnceCell::new();
    /// ```
    #[inline]
    pub fn take(&mut self) -> Option<T> {
        mem::take(self).into_inner()
    }

    /// Consumes the `OnceCell`, returning the wrapped value. Returns
    /// `None` if the cell was empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use once_cell_no_std::OnceCell;
    ///
    /// let cell: OnceCell<String> = OnceCell::new();
    /// assert_eq!(cell.into_inner(), None);
    ///
    /// let cell = OnceCell::new();
    /// cell.set("hello".to_string()).unwrap();
    /// assert_eq!(cell.into_inner(), Some("hello".to_string()));
    /// ```
    #[inline]
    pub fn into_inner(self) -> Option<T> {
        self.0.into_inner()
    }
}

/// A snapshot of the state of a [`OnceCell`], returned by [`OnceCell::state`].
///
/// # This is an observation, not a decision
///
/// The returned state describes the cell at the moment of the call and may have changed again by
/// the time it is inspected. It is meant for reporting: logging, diagnostics, health checks, and
/// tests. Driving control flow from it is a mistake, because neither of the two "not available"
/// states supports the conclusion it seems to invite:
///
/// - [`Uninitialized`](Self::Uninitialized) does not mean an initialization will succeed. Another
///   caller may start one before you do.
/// - [`Initializing`](Self::Initializing) does not mean an initialization will complete. The init
///   function may fail or panic and return the cell to `Uninitialized`, so a caller that waits for
///   it to finish may wait forever.
///
/// Use [`get_or_init`](OnceCell::get_or_init), [`set`](OnceCell::set), or
/// [`get_or_insert`](OnceCell::get_or_insert) when the answer has to be acted upon: they resolve the race
/// atomically and report contention as of the instant of the attempt.
///
/// [`Initialized`](Self::Initialized) is the one state that is stable: a cell only leaves it
/// through `&mut` access, which no other caller can hold at the same time. Observing it therefore
/// does guarantee that a subsequent [`get`](OnceCell::get) returns `Some`.
///
/// # Example
///
/// ```
/// use once_cell_no_std::{CellState, OnceCell};
///
/// let cell = OnceCell::new();
/// assert_eq!(cell.state(), CellState::Uninitialized);
///
/// cell.set(92).unwrap();
/// assert_eq!(cell.state(), CellState::Initialized);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CellState {
    /// The cell is empty and no initialization function is currently running.
    ///
    /// Note that the cell also returns to this state when an initialization function fails or
    /// panics, so this state does not mean that no initialization was attempted yet.
    Uninitialized,
    /// Another caller is currently running an initialization function for this cell.
    Initializing,
    /// The cell holds a value.
    Initialized,
}