Skip to main content

intuicio_data/
shared.rs

1//! Shared ownership wrappers with fallible, non-panicking access.
2//!
3//! [`Shared`] is single threaded, [`AsyncShared`] is the thread safe
4//! counterpart. Both return [`None`] instead of panicking when the value is
5//! already borrowed. A script runtime has to report such an error, not abort
6//! the host.
7use std::{
8    cell::{Ref, RefCell, RefMut},
9    rc::Rc,
10    sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard},
11};
12
13/// Single threaded shared value, a thin wrapper over `Rc<RefCell<T>>`.
14///
15/// Unlike [`RefCell`] directly, borrowing never panics: [`Shared::read`] and
16/// [`Shared::write`] return [`None`] when the value is already borrowed the
17/// other way.
18#[derive(Default)]
19pub struct Shared<T> {
20    data: Rc<RefCell<T>>,
21}
22
23impl<T> Clone for Shared<T> {
24    fn clone(&self) -> Self {
25        Self {
26            data: self.data.clone(),
27        }
28    }
29}
30
31impl<T> Shared<T> {
32    /// Wraps a value into a new shared cell with one reference.
33    pub fn new(data: T) -> Self {
34        Self {
35            data: Rc::new(RefCell::new(data)),
36        }
37    }
38
39    /// Unwraps the value when this is the last reference, otherwise gives the
40    /// handle back untouched.
41    pub fn try_consume(self) -> Result<T, Self> {
42        match Rc::try_unwrap(self.data) {
43            Ok(data) => Ok(data.into_inner()),
44            Err(data) => Err(Self { data }),
45        }
46    }
47
48    /// Borrows the value immutably, or returns [`None`] when it is already
49    /// borrowed mutably.
50    pub fn read(&'_ self) -> Option<Ref<'_, T>> {
51        self.data.try_borrow().ok()
52    }
53
54    /// Borrows the value mutably, or returns [`None`] when it is already
55    /// borrowed.
56    pub fn write(&'_ self) -> Option<RefMut<'_, T>> {
57        self.data.try_borrow_mut().ok()
58    }
59
60    /// Replaces the value and returns the old one, or [`None`] when it is
61    /// already borrowed.
62    pub fn swap(&self, data: T) -> Option<T> {
63        let mut value = self.data.try_borrow_mut().ok()?;
64        Some(std::mem::replace(&mut value, data))
65    }
66
67    /// Returns how many handles point at this value.
68    pub fn references_count(&self) -> usize {
69        Rc::strong_count(&self.data)
70    }
71
72    /// Returns `true` when both handles point at the same value.
73    pub fn does_share_reference(&self, other: &Self) -> bool {
74        Rc::ptr_eq(&self.data, &other.data)
75    }
76}
77
78/// Thread safe shared value, a thin wrapper over `Arc<RwLock<T>>`.
79///
80/// The [`Shared`] counterpart for values that cross threads. Access methods
81/// return [`None`] when the lock is poisoned or cannot be taken.
82#[derive(Default)]
83pub struct AsyncShared<T> {
84    data: Arc<RwLock<T>>,
85}
86
87impl<T> Clone for AsyncShared<T> {
88    fn clone(&self) -> Self {
89        Self {
90            data: self.data.clone(),
91        }
92    }
93}
94
95impl<T> AsyncShared<T> {
96    /// Wraps a value into a new shared cell with one reference.
97    pub fn new(data: T) -> Self {
98        Self {
99            data: Arc::new(RwLock::new(data)),
100        }
101    }
102
103    /// Unwraps the value when this is the last reference, otherwise gives the
104    /// handle back untouched.
105    pub fn try_consume(self) -> Result<T, Self> {
106        match Arc::try_unwrap(self.data) {
107            Ok(data) => Ok(data.into_inner().unwrap()),
108            Err(data) => Err(Self { data }),
109        }
110    }
111
112    /// Takes a read lock, blocking until it is free, or returns [`None`] when
113    /// the lock is poisoned.
114    pub fn read(&'_ self) -> Option<RwLockReadGuard<'_, T>> {
115        self.data.read().ok()
116    }
117
118    /// Takes a write lock, blocking until it is free, or returns [`None`] when
119    /// the lock is poisoned.
120    pub fn write(&'_ self) -> Option<RwLockWriteGuard<'_, T>> {
121        self.data.write().ok()
122    }
123
124    /// Replaces the value and returns the old one, or [`None`] when the lock is
125    /// poisoned.
126    pub fn swap(&self, data: T) -> Option<T> {
127        let mut value = self.data.write().ok()?;
128        Some(std::mem::replace(&mut value, data))
129    }
130
131    /// Returns how many handles point at this value.
132    pub fn references_count(&self) -> usize {
133        Arc::strong_count(&self.data)
134    }
135
136    /// Returns `true` when both handles point at the same value.
137    pub fn does_share_reference(&self, other: &Self) -> bool {
138        Arc::ptr_eq(&self.data, &other.data)
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::Shared;
145
146    #[test]
147    fn test_shared() {
148        let a = Shared::new(42);
149        assert_eq!(a.references_count(), 1);
150        assert_eq!(*a.read().unwrap(), 42);
151        let b = a.clone();
152        assert_eq!(a.references_count(), 2);
153        assert_eq!(b.references_count(), 2);
154        assert_eq!(*b.read().unwrap(), 42);
155        *b.write().unwrap() = 10;
156        assert_eq!(*a.read().unwrap(), 10);
157        assert_eq!(*b.read().unwrap(), 10);
158        assert!(b.try_consume().is_err());
159        assert_eq!(a.try_consume().ok().unwrap(), 10);
160    }
161}