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
use core::convert::{TryFrom, TryInto};
use core::sync::atomic::{AtomicUsize, Ordering};

#[cfg(feature = "std")]
use crate::park::StackWaiter;
use crate::POISON_PANIC_MSG;

use self::OnceState::{Ready, Uninit, WouldBlock};

const WOULD_BLOCK: usize = 0;
const UNINIT: usize = 1;
const READY: usize = 2;
const POISONED: usize = 3;

////////////////////////////////////////////////////////////////////////////////////////////////////
// AtomicState (public but not exported)
////////////////////////////////////////////////////////////////////////////////////////////////////

/// The concurrently and atomically mutable internal state of a [`OnceCell`].
///
/// A `WOULD_BLOCK` value is also interpreted as a `null` pointer to an empty
/// [`WaiterQueue`] indicating that there is only a single blocked thread.
#[derive(Debug)]
pub struct AtomicOnceState(AtomicUsize);

/********** impl inherent *************************************************************************/

impl AtomicOnceState {
    /// Creates a new `UNINIT` state.
    #[inline]
    pub(crate) const fn new() -> Self {
        Self(AtomicUsize::new(UNINIT))
    }

    /// Creates a new `READY` state.
    #[inline]
    pub(crate) const fn ready() -> Self {
        Self(AtomicUsize::new(READY))
    }

    /// Loads the current state using `ordering`.
    ///
    /// A Poisoning of the state is returned as a [`PoisonError`].
    #[inline]
    pub(crate) fn load(&self, order: Ordering) -> Result<OnceState, PoisonError> {
        self.0.load(order).try_into()
    }

    /// Attempts to set the state to blocked and fails if the state is either
    /// already initialized or blocked.
    #[inline]
    pub(crate) fn try_block(&self, order: Ordering) -> Result<(), TryBlockError> {
        let prev = match self.0.compare_exchange(UNINIT, WOULD_BLOCK, order, Ordering::Relaxed) {
            Ok(prev) => prev,
            Err(prev) => prev,
        };

        match prev.try_into().expect(POISON_PANIC_MSG) {
            Uninit => Ok(()),
            Ready => Err(TryBlockError::AlreadyInit),
            WouldBlock(state) => Err(TryBlockError::WouldBlock(state)),
        }
    }

    /// Unblocks the state by replacing it with either `Ready` or `Poisoned`.
    ///
    /// # Safety
    ///
    /// Must not be called if unblocking might cause data races due to
    /// un-synchronized reads and/or writes.
    #[inline]
    pub(crate) unsafe fn unblock(&self, state: SwapState, order: Ordering) -> BlockedState {
        BlockedState(self.0.swap(state as usize, order))
    }

    #[cfg(feature = "std")]
    /// Attempts to compare-and-swap the head of the `current` [`WaiterQueue]`
    /// with the `next` queue.
    #[inline]
    pub(crate) unsafe fn try_swap_blocked(
        &self,
        current: BlockedState,
        new: BlockedState,
        success: Ordering,
    ) -> Result<(), OnceState> {
        let prev =
            match self.0.compare_exchange(current.into(), new.into(), success, Ordering::Relaxed) {
                Ok(prev) => prev,
                Err(prev) => prev,
            };

        match prev {
            prev if prev == current.into() => Ok(()),
            prev => Err(prev.try_into().expect(POISON_PANIC_MSG)),
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// OnceState
////////////////////////////////////////////////////////////////////////////////////////////////////

#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) enum OnceState {
    /// Initial (uninitialized) state.
    Uninit,
    /// Ready (initialized) state.
    Ready,
    /// Blocked state with queue of waiting threads.
    WouldBlock(BlockedState),
}

/********** impl TryFrom **************************************************************************/

impl TryFrom<usize> for OnceState {
    type Error = PoisonError;

    #[inline]
    fn try_from(value: usize) -> Result<Self, Self::Error> {
        match value {
            POISONED => Err(PoisonError),
            UNINIT => Ok(Uninit),
            READY => Ok(Ready),
            state => Ok(WouldBlock(BlockedState(state))),
        }
    }
}

/********** impl From (usize) *********************************************************************/

impl From<OnceState> for usize {
    #[inline]
    fn from(state: OnceState) -> Self {
        match state {
            OnceState::Ready => READY,
            OnceState::Uninit => UNINIT,
            OnceState::WouldBlock(BlockedState(state)) => state,
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// TryBlockError
////////////////////////////////////////////////////////////////////////////////////////////////////

#[derive(Debug)]
pub enum TryBlockError {
    AlreadyInit,
    WouldBlock(BlockedState),
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// PoisonError
////////////////////////////////////////////////////////////////////////////////////////////////////

/// An error type indicating a `OnceCell` has been poisoned.
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct PoisonError;

////////////////////////////////////////////////////////////////////////////////////////////////////
// BlockedState (public but not exported)
////////////////////////////////////////////////////////////////////////////////////////////////////

#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct BlockedState(usize);

/********** impl inherent *************************************************************************/

impl BlockedState {
    #[cfg(feature = "std")]
    pub(crate) fn as_ptr(self) -> *const () {
        self.0 as *const _
    }
}

/********** impl From (for usize) *****************************************************************/

impl From<BlockedState> for usize {
    #[inline]
    fn from(state: BlockedState) -> Self {
        state.0
    }
}

/********** impl From (*const StackWaiter) ********************************************************/

#[cfg(feature = "std")]
impl From<*const StackWaiter> for BlockedState {
    #[inline]
    fn from(waiter: *const StackWaiter) -> Self {
        Self(waiter as usize)
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// SwapState
////////////////////////////////////////////////////////////////////////////////////////////////////

#[repr(usize)]
pub(crate) enum SwapState {
    Ready = READY,
    Poisoned = POISONED,
}