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
use parking_lot::RwLock;
use std::mem;

/// Data wrapper.
#[derive(Debug, Default)]
pub struct Data<T>(T);

impl<T> Data<T> {
    /// Creates a new instance.
    #[inline]
    pub fn new(value: T) -> Self {
        Self(value)
    }

    /// Unwraps to the contained value.
    #[inline]
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T: Clone> Data<T> {
    /// Returns a copy of the contained value.
    #[inline]
    pub fn get(&self) -> T {
        self.0.clone()
    }
}

/// Shared data wrapper.
#[derive(Debug, Default)]
pub struct SharedData<T>(RwLock<T>);

impl<T> SharedData<T> {
    /// Creates a new instance.
    #[inline]
    pub fn new(value: T) -> Self {
        Self(RwLock::new(value))
    }

    /// Sets the contained value.
    #[inline]
    pub fn set(&self, value: T) {
        *self.0.write() = value;
    }

    /// Replaces the contained value with `value`, and returns the old contained value.
    #[inline]
    pub fn replace(&self, value: T) -> T {
        mem::replace(&mut self.0.write(), value)
    }

    /// Unwraps to the contained value.
    #[inline]
    pub fn into_inner(self) -> T {
        self.0.into_inner()
    }
}

impl<T: Clone> SharedData<T> {
    /// Returns a copy of the contained value.
    #[inline]
    pub fn get(&self) -> T {
        self.0.read().clone()
    }
}