atomic_swapping 0.1.0

An arbitrary type atomic storage with swap operations
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
//! A concurrent data structure that allows for [`AtomicSwapOption::swap`], [`AtomicSwapOption::take`], [`AtomicSwapOption::set`], and [`AtomicSwapOption::clone_inner`] operations to be run on any type `T`.
//! ```
//! use atomic_swapping::option::AtomicSwapOption;
//!
//! let swap = AtomicSwapOption::new(Some(100usize));
//! assert_eq!(swap.clone_inner(), Some(100usize));
//! assert_eq!(swap.take(), Some(100usize));
//! assert_eq!(swap.take(), None);
//! swap.set(Some(200usize));
//! assert_eq!(swap.swap(Some(300usize)), Some(200usize));
//! assert!(swap.contains_value());
//! assert_eq!(swap.clone_inner(), Some(300usize));
//! ```
//! This is guaranteed lock-free where atomics will be guaranteed lock-free, however it is not guaranteed wait free. Some operations may spin for a short time.
//! All values will be properly dropped.

use core::cell::UnsafeCell;
use core::hint::spin_loop;
#[cfg(not(debug_assertions))]
use core::hint::unreachable_unchecked;
use core::mem::{swap, MaybeUninit};
use core::sync::atomic::{AtomicUsize, Ordering};

/// Allows shared access to `T` by only swap related operations. Acts like it stores an [`Option<T>`].
/// This is more efficient than an [`AtomicSwap<Option<T>>`](crate::AtomicSwap) and more methods.
/// ```
/// use atomic_swapping::option::AtomicSwapOption;
///
/// let swap = AtomicSwapOption::new(Some(100usize));
/// assert_eq!(swap.clone_inner(), Some(100usize));
/// assert_eq!(swap.take(), Some(100usize));
/// assert_eq!(swap.take(), None);
/// swap.set(Some(200usize));
/// assert_eq!(swap.swap(Some(300usize)), Some(200usize));
/// assert!(swap.contains_value());
/// assert_eq!(swap.clone_inner(), Some(300usize));
/// ```
#[derive(Debug)]
pub struct AtomicSwapOption<T> {
    state: AtomicUsize,
    data: UnsafeCell<MaybeUninit<T>>,
}
impl<T> AtomicSwapOption<T> {
    /// Creates a new [`AtomicSwapOption`] from an optional value.
    /// If `const` is needed then look to [`AtomicSwapOption::from_value`] or [`AtomicSwapOption::from_none`].
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let some_swap = AtomicSwapOption::new(Some(100usize));
    /// assert_eq!(some_swap.take(), Some(100usize));
    ///
    /// let none_swap = AtomicSwapOption::<usize>::new(None);
    /// assert_eq!(none_swap.take(), None);
    /// ```
    pub fn new(value: Option<T>) -> Self {
        match value {
            None => Self::from_none(),
            Some(value) => Self::from_value(value),
        }
    }
    /// Creates a new [`AtomicSwapOption`] from a value, assigning [`Some`] to the swap.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let swap = AtomicSwapOption::from_value(100usize);
    /// assert_eq!(swap.take(), Some(100usize));
    /// ```
    pub const fn from_value(value: T) -> Self {
        Self {
            state: AtomicUsize::new(AtomicSwapState::Assigned(0).into_usize()),
            data: UnsafeCell::new(MaybeUninit::new(value)),
        }
    }
    /// Creates a new [`AtomicSwapOption`] with [`None`] assigned.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let swap = AtomicSwapOption::<usize>::from_none();
    /// assert_eq!(swap.take(), None);
    /// ```
    pub const fn from_none() -> Self {
        Self {
            state: AtomicUsize::new(AtomicSwapState::Unassigned.into_usize()),
            data: UnsafeCell::new(MaybeUninit::uninit()),
        }
    }

    /// Swaps the current value in the swap with `value`, returning the currently contained value.
    /// Same as [`AtomicSwapOption::swap_hint`] with [`spin_loop`] as `spin_loop_hint`.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let swap = AtomicSwapOption::from_value(100usize);
    /// assert_eq!(swap.swap(Some(200usize)), Some(100usize));
    /// assert_eq!(swap.swap(None), Some(200usize));
    /// assert_eq!(swap.swap(None), None);
    /// ```
    #[inline]
    pub fn swap(&self, value: Option<T>) -> Option<T> {
        self.swap_hint(value, spin_loop)
    }
    /// Swaps the current value in the swap with `value`, returning the currently contained value.
    /// Same as [`AtomicSwapOption::swap`] but with a custom spin loop hint function.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let swap = AtomicSwapOption::from_value(100usize);
    /// let spin_hint = ||println!("I'm spinning! Probably should yield here.");
    /// assert_eq!(swap.swap_hint(Some(200usize), spin_hint), Some(100usize));
    /// assert_eq!(swap.swap_hint(None, spin_hint), Some(200usize));
    /// assert_eq!(swap.swap_hint(None, spin_hint), None);
    /// ```
    pub fn swap_hint(&self, value: Option<T>, mut spin_loop_hint: impl FnMut()) -> Option<T> {
        let mut state = self.state.load(Ordering::Acquire);
        loop {
            let state_enum = AtomicSwapState::from_usize(state);
            match &state_enum {
                AtomicSwapState::Unassigned | AtomicSwapState::Assigned(0) => {
                    match self.state.compare_exchange_weak(
                        state,
                        AtomicSwapState::Assigning.into_usize(),
                        Ordering::AcqRel,
                        Ordering::Acquire,
                    ) {
                        Ok(_) => {
                            let value_is_some = value.is_some();
                            let out = match (value, state_enum) {
                                (None, AtomicSwapState::Unassigned) => None,
                                (None, AtomicSwapState::Assigned(_)) => unsafe {
                                    Some(self.data.get().read().assume_init())
                                },
                                (Some(value), AtomicSwapState::Unassigned) => unsafe {
                                    *self.data.get() = MaybeUninit::new(value);
                                    None
                                },
                                (Some(value), AtomicSwapState::Assigned(_)) => unsafe {
                                    let mut out = MaybeUninit::new(value);
                                    swap(&mut out, &mut *self.data.get());
                                    Some(out.assume_init())
                                },
                                (_, _) => {
                                    #[cfg(debug_assertions)]
                                    unreachable!();
                                    #[cfg(not(debug_assertions))]
                                    unsafe {
                                        unreachable_unchecked()
                                    }
                                }
                            };
                            self.state
                                .compare_exchange(
                                    AtomicSwapState::Assigning.into_usize(),
                                    if value_is_some {
                                        AtomicSwapState::Assigned(0).into_usize()
                                    } else {
                                        AtomicSwapState::Unassigned.into_usize()
                                    },
                                    Ordering::AcqRel,
                                    Ordering::Acquire,
                                )
                                .expect("Assigning was changed improperly!");
                            return out;
                        }
                        Err(new_state) => state = new_state,
                    }
                }
                AtomicSwapState::Assigned(_) | AtomicSwapState::Assigning => {
                    spin_loop_hint();
                    state = self.state.load(Ordering::Acquire);
                }
            }
        }
    }

    /// Takes the current value and returns it leaving [`None`] in its place.
    /// Same as [`AtomicSwapOption::take_hint`] with [`spin_loop`] as `spin_loop_hint`.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let swap = AtomicSwapOption::from_value(100usize);
    /// assert_eq!(swap.take(), Some(100usize));
    /// assert_eq!(swap.take(), None);
    /// ```
    #[inline]
    pub fn take(&self) -> Option<T> {
        self.take_hint(spin_loop)
    }
    /// Takes the current value and returns it leaving [`None`] in its place.
    /// Same as [`AtomicSwapOption::take`] but with a custom spin loop hint function.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let swap = AtomicSwapOption::from_value(100usize);
    /// let spin_hint = ||println!("I'm spinning! Probably should yield here.");
    /// assert_eq!(swap.take_hint(spin_hint), Some(100usize));
    /// assert_eq!(swap.take_hint(spin_hint), None);
    /// ```
    pub fn take_hint(&self, mut spin_loop_hint: impl FnMut()) -> Option<T> {
        let mut state = self.state.load(Ordering::Acquire);
        loop {
            match AtomicSwapState::from_usize(state) {
                AtomicSwapState::Unassigned => return None,
                AtomicSwapState::Assigned(0) => match self.state.compare_exchange_weak(
                    state,
                    AtomicSwapState::Assigning.into_usize(),
                    Ordering::AcqRel,
                    Ordering::Acquire,
                ) {
                    Ok(_) => unsafe {
                        let out = self.data.get().read().assume_init();
                        self.state
                            .compare_exchange(
                                AtomicSwapState::Assigning.into_usize(),
                                AtomicSwapState::Unassigned.into_usize(),
                                Ordering::AcqRel,
                                Ordering::Acquire,
                            )
                            .expect("Assigning was changed improperly!");
                        return Some(out);
                    },
                    Err(new_state) => state = new_state,
                },
                AtomicSwapState::Assigned(_) | AtomicSwapState::Assigning => {
                    spin_loop_hint();
                    state = self.state.load(Ordering::Acquire);
                }
            }
        }
    }

    /// Sets the current value in the swap to `value`, dropping the held value if contained.
    /// Same as [`AtomicSwapOption::set_hint`] with [`spin_loop`] as `spin_loop_hint`.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// # use std::sync::atomic::{AtomicUsize, Ordering};
    /// # use std::sync::Arc;
    /// # struct DropCount<T>(Arc<AtomicUsize>, T);
    /// # impl<T> Drop for DropCount<T>{
    /// #     fn drop(&mut self) {
    /// #         self.0.fetch_add(1, Ordering::SeqCst);
    /// #     }
    /// # }
    /// // drop_count is incremented every time a DropCount is dropped
    /// let drop_count = Arc::new(AtomicUsize::new(0));
    /// let swap = AtomicSwapOption::from_value(DropCount(drop_count.clone(), 100usize));
    ///
    /// // Setting the swap to None should drop 100
    /// swap.set(None);
    /// assert_eq!(1, drop_count.load(Ordering::SeqCst));
    /// // Setting the swap to 200 should drop nothing as contains None
    /// swap.set(Some(DropCount(drop_count.clone(), 200usize)));
    /// assert_eq!(1, drop_count.load(Ordering::SeqCst));
    /// // Setting the swap to 300 should drop 200
    /// swap.set(Some(DropCount(drop_count.clone(), 300usize)));
    /// assert_eq!(2, drop_count.load(Ordering::SeqCst));
    /// // Dropping the swap should drop 300
    /// drop(swap);
    /// assert_eq!(3, drop_count.load(Ordering::SeqCst));
    /// ```
    #[inline]
    pub fn set(&self, value: Option<T>) {
        self.set_hint(value, spin_loop)
    }
    /// Sets the current value in the swap to `value`, dropping the held value if contained.
    /// Same as [`AtomicSwapOption::set`] but with a custom spin loop hint function.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// # use std::sync::atomic::{AtomicUsize, Ordering};
    /// # use std::sync::Arc;
    /// # struct DropCount<T>(Arc<AtomicUsize>, T);
    /// # impl<T> Drop for DropCount<T>{
    /// #     fn drop(&mut self) {
    /// #         self.0.fetch_add(1, Ordering::SeqCst);
    /// #     }
    /// # }
    /// // drop_count is incremented every time a DropCount is dropped
    /// let drop_count = Arc::new(AtomicUsize::new(0));
    /// let swap = AtomicSwapOption::from_value(DropCount(drop_count.clone(), 100usize));
    /// let spin_hint = ||println!("I'm spinning! Probably should yield here.");
    ///
    /// // Setting the swap to None should drop 100
    /// swap.set_hint(None, spin_hint);
    /// assert_eq!(1, drop_count.load(Ordering::SeqCst));
    /// // Setting the swap to 200 should drop nothing as contains None
    /// swap.set_hint(Some(DropCount(drop_count.clone(), 200usize)), spin_hint);
    /// assert_eq!(1, drop_count.load(Ordering::SeqCst));
    /// // Setting the swap to 300 should drop 200
    /// swap.set_hint(Some(DropCount(drop_count.clone(), 300usize)), spin_hint);
    /// assert_eq!(2, drop_count.load(Ordering::SeqCst));
    /// // Dropping the swap should drop 300
    /// drop(swap);
    /// assert_eq!(3, drop_count.load(Ordering::SeqCst));
    /// ```
    pub fn set_hint(&self, value: Option<T>, mut spin_loop_hint: impl FnMut()) {
        let mut state = self.state.load(Ordering::Acquire);
        loop {
            let state_enum = AtomicSwapState::from_usize(state);
            match &state_enum {
                AtomicSwapState::Unassigned | AtomicSwapState::Assigned(0) => {
                    match self.state.compare_exchange_weak(
                        state,
                        AtomicSwapState::Assigning.into_usize(),
                        Ordering::AcqRel,
                        Ordering::Acquire,
                    ) {
                        Ok(_) => {
                            if let AtomicSwapState::Assigned(_) = state_enum {
                                unsafe { drop(self.data.get().read().assume_init()) }
                            }
                            let value_is_some = value.is_some();
                            if let Some(value) = value {
                                unsafe {
                                    *self.data.get() = MaybeUninit::new(value);
                                }
                            }
                            self.state
                                .compare_exchange(
                                    AtomicSwapState::Assigning.into_usize(),
                                    if value_is_some {
                                        AtomicSwapState::Assigned(0).into_usize()
                                    } else {
                                        AtomicSwapState::Unassigned.into_usize()
                                    },
                                    Ordering::AcqRel,
                                    Ordering::Acquire,
                                )
                                .expect("Assigning was changed improperly!");
                            return;
                        }
                        Err(new_state) => state = new_state,
                    }
                }
                AtomicSwapState::Assigned(_) | AtomicSwapState::Assigning => {
                    spin_loop_hint();
                    state = self.state.load(Ordering::Acquire);
                }
            }
        }
    }

    /// Clones the contained value if [`Some`] and returns it. `T` must be [`Clone`] and [`Sync`] because multiple threads could clone this simultaneously.
    /// Same as [`AtomicSwapOption::clone_inner_hint`] with [`spin_loop`] as `spin_loop_hint`.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let swap = AtomicSwapOption::from_value(100usize);
    /// assert_eq!(swap.clone_inner(), Some(100usize));
    /// assert_eq!(swap.take(), Some(100usize));
    /// assert_eq!(swap.clone_inner(), None);
    /// assert_eq!(swap.take(), None);
    /// ```
    #[inline]
    pub fn clone_inner(&self) -> Option<T>
    where
        T: Clone + Sync,
    {
        self.clone_inner_hint(spin_loop)
    }
    /// Clones the contained value if [`Some`] and returns it. `T` must be [`Clone`] and [`Sync`] because multiple threads could clone this simultaneously.
    /// Same as [`AtomicSwapOption::clone_inner`] but with a custom spin loop hint function.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let swap = AtomicSwapOption::from_value(100usize);
    /// let spin_hint = ||println!("I'm spinning! Probably should yield here.");
    /// assert_eq!(swap.clone_inner_hint(spin_hint), Some(100usize));
    /// assert_eq!(swap.take_hint(spin_hint), Some(100usize));
    /// assert_eq!(swap.clone_inner_hint(spin_hint), None);
    /// assert_eq!(swap.take_hint(spin_hint), None);
    /// ```
    pub fn clone_inner_hint(&self, mut spin_loop_hint: impl FnMut()) -> Option<T>
    where
        T: Clone + Sync,
    {
        let mut state = self.state.load(Ordering::Acquire);
        loop {
            match AtomicSwapState::from_usize(state) {
                AtomicSwapState::Unassigned => return None,
                AtomicSwapState::Assigned(readers) => match self.state.compare_exchange_weak(
                    state,
                    AtomicSwapState::Assigned(readers + 1).into_usize(),
                    Ordering::AcqRel,
                    Ordering::Acquire,
                ) {
                    Ok(_) => unsafe {
                        // safe because MaybeUninit<T> is transparent to T while init
                        let out = (&*(self.data.get() as *mut T)).clone();
                        let result = self.state.fetch_sub(1, Ordering::AcqRel);
                        debug_assert_ne!(result, 0);
                        return Some(out);
                    },
                    Err(new_state) => state = new_state,
                },
                AtomicSwapState::Assigning => {
                    spin_loop_hint();
                    state = self.state.load(Ordering::Acquire);
                }
            }
        }
    }

    /// Returns true if the swap contains a value. Will return `true` if [`Some`], `false` if [`None`], or will spin if being assigned by other thread.
    /// Same as [`AtomicSwapOption::contains_value_hint`] with [`spin_loop`] as `spin_loop_hint`.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let swap = AtomicSwapOption::from_value(100usize);
    /// assert!(swap.contains_value());
    /// assert_eq!(swap.take(), Some(100usize));
    /// assert!(!swap.contains_value());
    /// assert_eq!(swap.take(), None);
    /// ```
    #[inline]
    pub fn contains_value(&self) -> bool {
        self.contains_value_hint(spin_loop)
    }
    /// Returns true if the swap contains a value. Will return `true` if [`Some`], `false` if [`None`], or will spin if being assigned by other thread.
    /// Same as [`AtomicSwapOption::contains_value`] but with a custom spin loop hint function.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let swap = AtomicSwapOption::from_value(100usize);
    /// let spin_hint = ||println!("I'm spinning! Probably should yield here.");
    /// assert!(swap.contains_value_hint(spin_hint));
    /// assert_eq!(swap.take_hint(spin_hint), Some(100usize));
    /// assert!(!swap.contains_value_hint(spin_hint));
    /// assert_eq!(swap.take_hint(spin_hint), None);
    /// ```
    pub fn contains_value_hint(&self, mut spin_loop_hint: impl FnMut()) -> bool {
        loop {
            match AtomicSwapState::from_usize(self.state.load(Ordering::Acquire)) {
                AtomicSwapState::Unassigned => return false,
                AtomicSwapState::Assigning => spin_loop_hint(),
                AtomicSwapState::Assigned(_) => return true,
            }
        }
    }

    /// Gets the internal value exclusively if contains a value. Use [`AtomicSwapOption::get_mut_or`], [`AtomicSwapOption::get_mut_or_else`], or [`AtomicSwapOption::get_mut_default`] if wanting to guarantee a value is held.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let mut swap = AtomicSwapOption::from_value(100);
    /// assert_eq!(swap.get_mut(), Some(&mut 100usize));
    /// *swap.get_mut().unwrap() = 200usize;
    /// assert_eq!(swap.take(), Some(200usize));
    /// assert_eq!(swap.get_mut(), None);
    /// ```
    pub fn get_mut(&mut self) -> Option<&mut T> {
        match AtomicSwapState::from_usize(self.state.load(Ordering::Acquire)) {
            AtomicSwapState::Unassigned => None,
            // Safe because MaybeUninit<T> is transparent to T
            AtomicSwapState::Assigned(0) => Some(unsafe { &mut *(self.data.get() as *mut T) }),
            AtomicSwapState::Assigning | AtomicSwapState::Assigned(_) => {
                #[cfg(debug_assertions)]
                unreachable!("We should have exclusive access and therefore nothing should be assigning/reading");
                #[cfg(not(debug_assertions))]
                unsafe {
                    unreachable_unchecked()
                }
            }
        }
    }
    /// Gets a mutable reference to the current value if contains a value or fills with `value` then returns mutable reference to that.
    /// Alias to [`AtomicSwapOption::get_mut_or_else`]`(||value)`
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let mut swap = AtomicSwapOption::from_none();
    /// assert_eq!(swap.get_mut_or(100usize), &mut 100usize);
    /// assert_eq!(swap.get_mut_or(300usize), &mut 100usize);
    /// *swap.get_mut_or(400usize) = 200usize;
    /// assert_eq!(swap.take(), Some(200usize));
    /// ```
    #[inline]
    pub fn get_mut_or(&mut self, value: T) -> &mut T {
        self.get_mut_or_else(|| value)
    }
    /// Gets a mutable reference to the current value if contains a value or fills with `value()` then returns mutable reference to that.
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let mut swap = AtomicSwapOption::from_none();
    /// assert_eq!(swap.get_mut_or_else(||100usize), &mut 100usize);
    /// assert_eq!(swap.get_mut_or_else(||300usize), &mut 100usize);
    /// *swap.get_mut_or_else(||400usize) = 200usize;
    /// assert_eq!(swap.take(), Some(200usize));
    /// ```
    pub fn get_mut_or_else(&mut self, value: impl FnOnce() -> T) -> &mut T {
        match AtomicSwapState::from_usize(self.state.load(Ordering::Acquire)) {
            AtomicSwapState::Unassigned => {
                *self.data.get_mut() = MaybeUninit::new(value());
                self.state
                    .store(AtomicSwapState::Assigned(0).into_usize(), Ordering::Release);
            }
            AtomicSwapState::Assigned(0) => {}
            AtomicSwapState::Assigning | AtomicSwapState::Assigned(_) => {
                #[cfg(debug_assertions)]
                unreachable!("We should have exclusive access and therefore nothing should be assigning/reading");
                #[cfg(not(debug_assertions))]
                unsafe {
                    unreachable_unchecked()
                }
            }
        }
        // Safe because MaybeUninit<T> is transparent to T
        unsafe { &mut *(self.data.get() as *mut T) }
    }
    /// Gets a mutable reference to the current value if contains a value or fills with [`Default::default`] then returns mutable reference to that.
    /// Alias to [`AtomicSwapOption::get_mut_or_else`]`(T::default)`
    /// ```
    /// # use atomic_swapping::option::AtomicSwapOption;
    /// let mut swap = AtomicSwapOption::from_none();
    /// assert_eq!(swap.get_mut_default(), &mut usize::default());
    /// *swap.get_mut_or_else(||400usize) = 200usize;
    /// assert_eq!(swap.get_mut_default(), &mut 200usize);
    /// assert_eq!(swap.take(), Some(200usize));
    /// ```
    #[inline]
    pub fn get_mut_default(&mut self) -> &mut T
    where
        T: Default,
    {
        self.get_mut_or_else(T::default)
    }
}
impl<T> Drop for AtomicSwapOption<T> {
    fn drop(&mut self) {
        match AtomicSwapState::from_usize(self.state.load(Ordering::Acquire)) {
            AtomicSwapState::Unassigned => {}
            AtomicSwapState::Assigning => {
                #[cfg(debug_assertions)]
                unreachable!("Should not have dropped while assigning!");
                #[cfg(not(debug_assertions))]
                unsafe {
                    unreachable_unchecked()
                }
            }
            AtomicSwapState::Assigned(0) => unsafe { drop(self.data.get().read().assume_init()) },
            AtomicSwapState::Assigned(_) => {
                #[cfg(debug_assertions)]
                unreachable!("Should not drop while has readers!");
                #[cfg(not(debug_assertions))]
                unsafe {
                    unreachable_unchecked()
                }
            }
        }
    }
}
impl<T> EnsureSend for AtomicSwapOption<T> where T: Send {}
unsafe impl<T> Sync for AtomicSwapOption<T> where T: Send {}
impl<T> Default for AtomicSwapOption<T> {
    #[inline]
    fn default() -> Self {
        Self::from_none()
    }
}

trait EnsureSend: Send {}

/// Does not implement [`From`] for [`usize`] to allow for const from functions
#[derive(Copy, Clone, Debug)]
enum AtomicSwapState {
    /// No current value
    Unassigned,
    /// Exclusive access
    Assigning,
    /// Num Readers
    Assigned(usize),
}
impl AtomicSwapState {
    pub const fn into_usize(self) -> usize {
        match self {
            AtomicSwapState::Unassigned => 0,
            AtomicSwapState::Assigning => 1,
            AtomicSwapState::Assigned(readers) => 2 + readers,
        }
    }

    pub const fn from_usize(size: usize) -> Self {
        match size {
            0 => Self::Unassigned,
            1 => Self::Assigning,
            x => Self::Assigned(x - 2),
        }
    }
}

#[cfg(test)]
mod test {
    use crate::option::AtomicSwapOption;
    use crate::test::ComplexType;
    use rand::{thread_rng, Rng};
    use std::sync::Arc;
    use std::thread::spawn;
    use std::vec::Vec;

    #[test]
    fn slam_test() {
        const OPS_PER_THREAD: usize = 1 << 10;
        const NUM_THREADS: usize = 1 << 4;
        let mut rng = thread_rng();
        for round_num in 0..4 {
            let swap_value = match round_num {
                0 => Some(ComplexType::generate(&mut rng)),
                1 => None,
                _ => ComplexType::generate_option(&mut rng),
            };
            let swap = Arc::new(AtomicSwapOption::new(swap_value));
            let mut threads = Vec::with_capacity(NUM_THREADS);
            for _thread_num in 0..NUM_THREADS {
                let swap_clone = swap.clone();
                threads.push(spawn(move || {
                    let mut rng = thread_rng();
                    for _op_num in 0..OPS_PER_THREAD {
                        let operation = rng.gen_range(0..=3);
                        match operation {
                            0 => {
                                swap_clone.swap(ComplexType::generate_option(&mut rng));
                            }
                            1 => {
                                swap_clone.take();
                            }
                            2 => swap_clone.set(ComplexType::generate_option(&mut rng)),
                            3 => {
                                swap_clone.clone_inner();
                            }
                            _ => unreachable!(),
                        }
                    }
                }));
            }
            for thread in threads {
                thread.join().expect("Could not join");
            }
        }
    }

    #[test]
    fn value_test() {
        const NUM_OPS: usize = 1 << 10;
        let mut rng = thread_rng();
        for round_num in 0..4 {
            let mut last_value = match round_num {
                0 => Some(ComplexType::generate(&mut rng)),
                1 => None,
                _ => ComplexType::generate_option(&mut rng),
            };
            let mut swap = AtomicSwapOption::new(last_value.clone());
            let mut last_op = -1;
            for _op_num in 0..NUM_OPS {
                let operation = rng.gen_range(0..=6);
                match operation {
                    0 => {
                        let new_value = ComplexType::generate_option(&mut rng);
                        assert_eq!(
                            last_value,
                            swap.swap(new_value.clone()),
                            "Last op: {}",
                            last_op
                        );
                        last_value = new_value;
                    }
                    1 => {
                        assert_eq!(last_value, swap.take(), "Last op: {}", last_op);
                        last_value = None;
                    }
                    2 => {
                        last_value = ComplexType::generate_option(&mut rng);
                        swap.set(last_value.clone());
                    }
                    3 => {
                        assert_eq!(last_value, swap.clone_inner(), "Last op: {}", last_op);
                    }
                    4 => {
                        let swap_ref = swap.get_mut();
                        assert_eq!(swap_ref, last_value.as_mut(), "Last op: {}", last_op);
                        if let Some(swap_ref) = swap_ref {
                            *swap_ref = ComplexType::generate(&mut rng);
                            last_value = Some(swap_ref.clone());
                        }
                    }
                    5 => {
                        let possible_value = ComplexType::generate(&mut rng);
                        let swap_ref = swap.get_mut_or(possible_value.clone());
                        assert_eq!(
                            swap_ref,
                            &mut last_value.unwrap_or_else(|| possible_value.clone()),
                            "Last op: {}",
                            last_op
                        );
                        *swap_ref = possible_value.clone();
                        last_value = Some(possible_value);
                    }
                    6 => {
                        let swap_ref = swap.get_mut_default();
                        assert_eq!(
                            swap_ref,
                            &mut last_value.unwrap_or_default(),
                            "Last op: {}",
                            last_op
                        );
                        *swap_ref = ComplexType::generate(&mut rng);
                        last_value = Some(swap_ref.clone());
                    }
                    _ => unreachable!(),
                }
                last_op = operation;
            }
        }
    }
}