rt_own/
viewer.rs

1use std::fmt::Debug;
2use std::fmt::Formatter;
3use std::hash::Hash;
4use std::hash::Hasher;
5use std::ops::Deref;
6
7use crate::Holder;
8use crate::Owner;
9use crate::State;
10use crate::ptr::Ptr;
11use crate::ptr::Role;
12
13pub struct Viewer<D: ?Sized> {
14    pub(crate) ptr: Ptr<D>,
15}
16
17impl<D: ?Sized> Viewer<D> {
18    pub fn new(d: D) -> Self
19    where D: Sized {
20        Viewer { ptr: Ptr::new(d, Role::Viewer) }
21    }
22
23    pub fn state(s: &Viewer<D>) -> State {
24        s.ptr.cell().state()
25    }
26}
27
28impl<D: ?Sized> Clone for Viewer<D> {
29    fn clone(&self) -> Self {
30        Viewer { ptr: Ptr::clone_to(&self.ptr, Role::Viewer).unwrap() }
31    }
32}
33
34impl<D: ?Sized> TryFrom<&Holder<D>> for Viewer<D> {
35    type Error = State;
36    fn try_from(value: &Holder<D>) -> Result<Self, Self::Error> {
37        Ok(Viewer { ptr: Ptr::clone_to(&value.ptr, Role::Viewer)? })
38    }
39}
40
41impl<D: ?Sized> TryFrom<Holder<D>> for Viewer<D> {
42    type Error = State;
43    fn try_from(value: Holder<D>) -> Result<Self, Self::Error> {
44        Ok(Viewer { ptr: Ptr::clone_to(&value.ptr, Role::Viewer)? })
45    }
46}
47
48impl<D: ?Sized> From<Owner<D>> for Viewer<D> {
49    fn from(value: Owner<D>) -> Self {
50        let h = Holder::from(value);
51        Viewer { ptr: Ptr::clone_to(&h.ptr, Role::Viewer).unwrap() }
52    }
53}
54
55impl<D: ?Sized> Deref for Viewer<D> {
56    type Target = D;
57    fn deref(&self) -> &Self::Target {
58        // SAFETY: when self is alive there is no owner and data hasn't been dropped
59        unsafe { self.ptr.cell().deref() }
60    }
61}
62
63impl<D: ?Sized> TryFrom<&Ptr<D>> for Viewer<D> {
64    type Error = State;
65    fn try_from(value: &Ptr<D>) -> Result<Self, Self::Error> {
66        Ok(Viewer { ptr: Ptr::clone_to(value, Role::Viewer)? })
67    }
68}
69
70impl<D: ?Sized> Drop for Viewer<D> {
71    fn drop(&mut self) {
72        self.ptr.drop_from(Role::Viewer);
73    }
74}
75
76impl<D: ?Sized> Debug for Viewer<D> {
77    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
78        f.debug_tuple("Viewer").field(&self.ptr).finish()
79    }
80}
81
82impl<D: Default> Default for Viewer<D> {
83    fn default() -> Self {
84        Viewer::new(D::default())
85    }
86}
87
88impl<D: ?Sized> PartialEq for Viewer<D> {
89    fn eq(&self, other: &Self) -> bool {
90        self.ptr == other.ptr
91    }
92}
93
94impl<D: ?Sized> Eq for Viewer<D> {}
95
96impl<D: ?Sized> Hash for Viewer<D> {
97    fn hash<H: Hasher>(&self, state: &mut H) {
98        self.ptr.hash(state);
99    }
100}