rw_cell/
option.rs

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
use std::sync::atomic::{AtomicPtr, Ordering};

pub struct OptionCell<T> {
    inner: AtomicPtr<Option<T>>
}

impl<T> OptionCell<T> {
    pub fn new(val: T) -> Self {
        Self {
            inner: AtomicPtr::new(some_raw_ptr(val)),
        }
    }

    pub fn replace(&self, val: T) -> Option<T> {
        let val_ptr = Box::into_raw(Box::new(Some(val)));
        let old_val_ptr = self.inner.swap(val_ptr, Ordering::SeqCst);
        *unsafe { Box::from_raw(old_val_ptr) }
    }

    pub fn take(&self) -> Option<T> {
        let curr_val = self.inner.swap(none_raw_ptr(), Ordering::SeqCst);
        *unsafe { Box::from_raw(curr_val) }
    }
}

#[inline]
pub(crate) fn none_raw_ptr<T>() -> *mut Option<T> {
    Box::into_raw(Box::new(None))
}

#[inline]
pub(crate) fn some_raw_ptr<T>(val: T) -> *mut Option<T> {
    Box::into_raw(Box::new(Some(val)))
}