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
use core::cell::UnsafeCell;
use core::fmt::{self, Debug, Formatter};
use core::mem::{ManuallyDrop, MaybeUninit};
use core::ptr::drop_in_place;
use core::sync::atomic::{spin_loop_hint, AtomicU8, Ordering};

const SOME: u8 = 0x1;
const FREE: u8 = 0x2;
const AVAILABLE: u8 = FREE | SOME;

/// A read/write lock around an `Option` value.
pub struct OptionLock<T> {
    data: UnsafeCell<MaybeUninit<T>>,
    state: AtomicU8,
}

impl<T> Default for OptionLock<T> {
    fn default() -> Self {
        Self::empty()
    }
}

unsafe impl<T: Send> Send for OptionLock<T> {}
unsafe impl<T: Send> Sync for OptionLock<T> {}

impl<T> OptionLock<T> {
    /// Create a new, empty instance.
    pub const fn empty() -> Self {
        Self {
            data: UnsafeCell::new(MaybeUninit::uninit()),
            state: AtomicU8::new(FREE),
        }
    }

    /// Create a new populated instance.
    pub const fn new(value: T) -> Self {
        Self {
            data: UnsafeCell::new(MaybeUninit::new(value)),
            state: AtomicU8::new(AVAILABLE),
        }
    }

    #[inline]
    pub(crate) unsafe fn as_mut_ptr(&self) -> *mut T {
        (&mut *self.data.get()).as_mut_ptr()
    }

    #[inline]
    pub(crate) fn state(&self) -> u8 {
        self.state.load(Ordering::Relaxed)
    }

    /// Check if there is a stored value and no guard held.
    #[inline]
    pub fn is_some_unlocked(&self) -> bool {
        self.state() == AVAILABLE
    }

    /// Check if there is no stored value and no guard held.
    #[inline]
    pub fn is_none_unlocked(&self) -> bool {
        self.state() == FREE
    }

    /// Check if a guard is held.
    #[inline]
    pub fn is_locked(&self) -> bool {
        self.state() & FREE == 0
    }

    /// Get a mutable reference to the contained value, if any.
    pub fn get_mut(&mut self) -> Option<&mut T> {
        if self.is_some_unlocked() {
            Some(unsafe { &mut *self.as_mut_ptr() })
        } else {
            None
        }
    }

    /// Unwrap an owned lock instance.
    pub fn into_inner(self) -> Option<T> {
        if self.state() & SOME != 0 {
            let slf = ManuallyDrop::new(self);
            Some(unsafe { slf.as_mut_ptr().read() })
        } else {
            None
        }
    }

    /// In a spin loop, wait to acquire the lock.
    pub fn spin_lock(&self) -> OptionGuard<'_, T> {
        loop {
            if let Some(guard) = self.try_lock() {
                break guard;
            }
            // use a relaxed check in spin loop
            while self.state() & FREE == 0 {
                spin_loop_hint();
            }
        }
    }

    /// In a spin loop, wait to acquire the lock with a value of None.
    pub fn spin_lock_none(&self) -> OptionGuard<'_, T> {
        loop {
            if let Some(guard) = self.try_lock_none() {
                break guard;
            }
            // use a relaxed check in spin loop
            while self.state() != FREE {
                spin_loop_hint();
            }
        }
    }

    /// In a spin loop, wait to take a value from the lock.
    pub fn spin_take(&self) -> T {
        loop {
            if let Some(result) = self.try_take() {
                break result;
            }
            // use a relaxed check in spin loop
            while self.state() != AVAILABLE {
                spin_loop_hint();
            }
        }
    }

    /// Try to acquire an exclusive lock.
    ///
    /// On successful acquisition `Some(OptionGuard<'_, T>)` is returned, representing
    /// an exclusive read/write lock.
    pub fn try_lock(&self) -> Option<OptionGuard<'_, T>> {
        let state = self.state.fetch_and(!FREE, Ordering::Release);
        if state & FREE != 0 {
            Some(OptionGuard {
                lock: self,
                filled: state & SOME != 0,
            })
        } else {
            None
        }
    }

    /// Try to acquire an exclusive lock, but only if the value is currently None.
    ///
    /// On successful acquisition `Some(OptionGuard<'_, T>)` is returned, representing
    /// an exclusive read/write lock.
    pub fn try_lock_none(&self) -> Option<OptionGuard<'_, T>> {
        loop {
            match self
                .state
                .compare_exchange_weak(FREE, 0, Ordering::AcqRel, Ordering::Relaxed)
            {
                Ok(_) => {
                    break Some(OptionGuard {
                        lock: self,
                        filled: false,
                    })
                }
                Err(FREE) => {
                    // retry
                }
                Err(_) => break None,
            }
        }
    }

    /// Try to take a stored value from the lock.
    ///
    /// On successful acquisition `Some(T)` is returned.
    ///
    /// On failure, `None` is returned. Acquisition can fail either because
    /// there is no contained value, or because the lock is held by a guard.
    pub fn try_take(&self) -> Option<T> {
        loop {
            match self.state.compare_exchange_weak(
                AVAILABLE,
                SOME,
                Ordering::AcqRel,
                Ordering::Relaxed,
            ) {
                Ok(_) => {
                    break Some(
                        OptionGuard {
                            lock: self,
                            filled: true,
                        }
                        .take()
                        .unwrap(),
                    )
                }
                Err(AVAILABLE) => {
                    // retry
                }
                Err(_) => break None,
            }
        }
    }

    /// Replace the value in an owned `OptionLock`.
    pub fn replace(&mut self, value: T) -> Option<T> {
        let result = if self.state() & SOME != 0 {
            Some(unsafe { self.as_mut_ptr().read() })
        } else {
            self.state.fetch_or(SOME, Ordering::Relaxed);
            None
        };
        unsafe { self.as_mut_ptr().write(value) };
        result
    }

    /// Take the value (if any) from an owned `OptionLock`.
    pub fn take(&mut self) -> Option<T> {
        if self.state() & SOME != 0 {
            self.state.fetch_and(!SOME, Ordering::Relaxed);
            Some(unsafe { self.as_mut_ptr().read() })
        } else {
            None
        }
    }
}

impl<T> Drop for OptionLock<T> {
    fn drop(&mut self) {
        if self.state() & SOME != 0 {
            unsafe {
                drop_in_place(self.as_mut_ptr());
            }
        }
    }
}

impl<T> From<T> for OptionLock<T> {
    fn from(data: T) -> Self {
        Self::new(data)
    }
}

impl<T> From<Option<T>> for OptionLock<T> {
    fn from(data: Option<T>) -> Self {
        if let Some(data) = data {
            Self::new(data)
        } else {
            Self::empty()
        }
    }
}

impl<T> Into<Option<T>> for OptionLock<T> {
    fn into(mut self) -> Option<T> {
        self.take()
    }
}

impl<T> Debug for OptionLock<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "OptionLock({})",
            match self.state() {
                FREE => "None",
                AVAILABLE => "Some",
                _ => "Locked",
            }
        )
    }
}

/// A write guard for the value of an [`OptionLock`]
pub struct OptionGuard<'a, T> {
    lock: &'a OptionLock<T>,
    filled: bool,
}

impl<T> OptionGuard<'_, T> {
    /// Obtain a shared reference to the contained value, if any.
    pub fn as_ref(&self) -> Option<&T> {
        if self.filled {
            Some(unsafe { &*self.lock.as_mut_ptr() })
        } else {
            None
        }
    }

    /// Obtain an exclusive reference to the contained value, if any.
    pub fn as_mut_ref(&mut self) -> Option<&mut T> {
        if self.filled {
            Some(unsafe { &mut *self.lock.as_mut_ptr() })
        } else {
            None
        }
    }

    /// Check if the lock contains `None`.
    #[inline]
    pub fn is_none(&self) -> bool {
        !self.filled
    }

    /// Check if the lock contains `Some(T)`.
    #[inline]
    pub fn is_some(&self) -> bool {
        self.filled
    }

    /// Replace the value in the lock, returning the previous value, if any.
    pub fn replace(&mut self, value: T) -> Option<T> {
        let ret = if self.filled {
            Some(unsafe { self.lock.as_mut_ptr().read() })
        } else {
            self.filled = true;
            None
        };
        unsafe {
            self.lock.as_mut_ptr().write(value);
        }
        ret
    }

    /// Take the current value from the lock, if any.
    pub fn take(&mut self) -> Option<T> {
        if self.filled {
            self.filled = false;
            Some(unsafe { self.lock.as_mut_ptr().read() })
        } else {
            None
        }
    }
}

impl<T: Debug> Debug for OptionGuard<'_, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_tuple("OptionGuard").field(&self.as_ref()).finish()
    }
}

impl<'a, T> Drop for OptionGuard<'a, T> {
    fn drop(&mut self) {
        self.lock.state.store(
            if self.filled { AVAILABLE } else { FREE },
            Ordering::Release,
        );
    }
}