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
use core::cell::RefCell;

/// Tiny wrapper over RefCell that:
/// - allow for uninitialized values (by storing Option)
/// - allow static usage (by implementing Sync and providing const constructor)
///
/// Because WASM is single threaded, we don't need to worry much about inter-thread communication
pub struct OptionalCell<T> {
    pub cell: RefCell<Option<T>>,
}

impl<T> OptionalCell<T> {
    pub const fn empty() -> OptionalCell<T> {
        OptionalCell {
            cell: RefCell::new(None),
        }
    }
    pub fn is_empty(&self) -> bool {
        self.cell.borrow().is_none()
    }
}

// Add clone_content to OptionalCell only if T is known to implement Clone.
// In particular to to use is_empty on OptionalCell trait Clone is not required on T.
pub trait CloneContents<T: Clone> {
    fn clone_contents(&self) -> T;
}

impl<T: Clone> CloneContents<T> for OptionalCell<T> {
    fn clone_contents(&self) -> T {
        self.cell.borrow().as_ref().unwrap().clone()
    }
}

unsafe impl<T> Sync for OptionalCell<T> {}