zino_core/state/
data.rs

1use parking_lot::RwLock;
2use std::mem;
3
4/// Data wrapper.
5#[derive(Clone, Debug, Default)]
6pub struct Data<T>(T);
7
8impl<T> Data<T> {
9    /// Creates a new instance.
10    #[inline]
11    pub const fn new(value: T) -> Self {
12        Self(value)
13    }
14
15    /// Unwraps to the contained value.
16    #[inline]
17    pub fn into_inner(self) -> T {
18        self.0
19    }
20}
21
22impl<T: Clone> Data<T> {
23    /// Returns a copy of the contained value.
24    #[inline]
25    pub fn get(&self) -> T {
26        self.0.clone()
27    }
28}
29
30/// Shared data wrapper.
31#[derive(Debug, Default)]
32pub struct SharedData<T>(RwLock<T>);
33
34impl<T> SharedData<T> {
35    /// Creates a new instance.
36    #[inline]
37    pub const fn new(value: T) -> Self {
38        Self(RwLock::new(value))
39    }
40
41    /// Sets the contained value.
42    #[inline]
43    pub fn set(&self, value: T) {
44        *self.0.write() = value;
45    }
46
47    /// Replaces the contained value with `value`, and returns the old contained value.
48    #[inline]
49    pub fn replace(&self, value: T) -> T {
50        mem::replace(&mut self.0.write(), value)
51    }
52
53    /// Unwraps to the contained value.
54    #[inline]
55    pub fn into_inner(self) -> T {
56        self.0.into_inner()
57    }
58}
59
60impl<T: Clone> SharedData<T> {
61    /// Returns a copy of the contained value.
62    #[inline]
63    pub fn get(&self) -> T {
64        self.0.read().clone()
65    }
66}