conch_runtime_pshaw/
ref_counted.rs

1use std::ops::Deref;
2use std::rc::Rc;
3use std::sync::Arc;
4
5/// A convenience trait to abstract over Arc<T> and Rc<T> APIs.
6pub trait RefCounted<T>: Sized + Clone + Deref<Target = T> + From<T> {
7    /// Returns a mutable reference to the contained value if the wrapper
8    /// has a single, unique, reference.
9    ///
10    /// Returns `None` if this is not the only reference to the data.
11    fn get_mut(&mut self) -> Option<&mut T>;
12
13    /// Make a mutable reference into the given implementation. If the
14    /// implementation has more than one strong reference, or any weak
15    /// references, the inner data is cloned.
16    ///
17    /// This is also referred to as a copy-on-write.
18    fn make_mut(&mut self) -> &mut T
19    where
20        T: Clone;
21}
22
23impl<T> RefCounted<T> for Rc<T> {
24    fn get_mut(&mut self) -> Option<&mut T> {
25        Rc::get_mut(self)
26    }
27
28    fn make_mut(&mut self) -> &mut T
29    where
30        T: Clone,
31    {
32        Rc::make_mut(self)
33    }
34}
35
36impl<T> RefCounted<T> for Arc<T> {
37    fn get_mut(&mut self) -> Option<&mut T> {
38        Arc::get_mut(self)
39    }
40
41    fn make_mut(&mut self) -> &mut T
42    where
43        T: Clone,
44    {
45        Arc::make_mut(self)
46    }
47}