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
//! # Rw Cell
//!
//! rw_cell provides the ability to securely write data from one location of application
//! and read it from another even if Writer and Reader located in different
//! threads without copying/cloning and blocking access to data.
//!

use std::sync::atomic::{AtomicPtr, Ordering};

/// M - multiple W - writer S - Single R - Reader
pub mod mwsr;

/// S - Single W - writer M - multiple R - Reader
pub mod swmr;

pub(crate) struct UnionCell<T> {
    inner: AtomicPtr<Option<T>>
}

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

    pub(crate) fn write(&self, val: T) {
        let val_ptr = Box::into_raw(Box::new(Some(val)));
        let old_val_ptr = self.inner.swap(val_ptr, Ordering::SeqCst);
        let _ = unsafe { Box::from_raw(old_val_ptr) };
    }

    pub(crate) fn remove(&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)))
}