1 | // Take a look at the license at the top of the repository in the LICENSE file. |
2 | |
3 | use std::{ |
4 | marker::PhantomData, |
5 | rc::{self, Rc}, |
6 | sync::{self, Arc}, |
7 | }; |
8 | |
9 | // rustdoc-stripper-ignore-next |
10 | /// Trait for generalizing downgrading a strong reference to a weak reference. |
11 | pub trait Downgrade |
12 | where |
13 | Self: Sized, |
14 | { |
15 | // rustdoc-stripper-ignore-next |
16 | /// Weak reference type. |
17 | type Weak; |
18 | |
19 | // rustdoc-stripper-ignore-next |
20 | /// Downgrade to a weak reference. |
21 | fn downgrade(&self) -> Self::Weak; |
22 | } |
23 | |
24 | // rustdoc-stripper-ignore-next |
25 | /// Trait for generalizing upgrading a weak reference to a strong reference. |
26 | pub trait Upgrade |
27 | where |
28 | Self: Sized, |
29 | { |
30 | // rustdoc-stripper-ignore-next |
31 | /// Strong reference type. |
32 | type Strong; |
33 | |
34 | // rustdoc-stripper-ignore-next |
35 | /// Try upgrading a weak reference to a strong reference. |
36 | fn upgrade(&self) -> Option<Self::Strong>; |
37 | } |
38 | |
39 | impl<T: Downgrade + crate::ObjectType> Upgrade for crate::WeakRef<T> { |
40 | type Strong = T; |
41 | |
42 | fn upgrade(&self) -> Option<Self::Strong> { |
43 | self.upgrade() |
44 | } |
45 | } |
46 | |
47 | impl<T> Downgrade for PhantomData<T> { |
48 | type Weak = PhantomData<T>; |
49 | |
50 | fn downgrade(&self) -> Self::Weak { |
51 | PhantomData |
52 | } |
53 | } |
54 | |
55 | impl<T: Downgrade> Downgrade for &T { |
56 | type Weak = T::Weak; |
57 | |
58 | fn downgrade(&self) -> Self::Weak { |
59 | T::downgrade(*self) |
60 | } |
61 | } |
62 | |
63 | impl<T> Downgrade for Arc<T> { |
64 | type Weak = sync::Weak<T>; |
65 | |
66 | fn downgrade(&self) -> Self::Weak { |
67 | Arc::downgrade(self) |
68 | } |
69 | } |
70 | |
71 | impl<T> Upgrade for PhantomData<T> { |
72 | type Strong = PhantomData<T>; |
73 | |
74 | fn upgrade(&self) -> Option<Self::Strong> { |
75 | Some(PhantomData) |
76 | } |
77 | } |
78 | |
79 | impl<T> Upgrade for sync::Weak<T> { |
80 | type Strong = Arc<T>; |
81 | |
82 | fn upgrade(&self) -> Option<Self::Strong> { |
83 | self.upgrade() |
84 | } |
85 | } |
86 | |
87 | impl<T> Downgrade for Rc<T> { |
88 | type Weak = rc::Weak<T>; |
89 | |
90 | fn downgrade(&self) -> Self::Weak { |
91 | Rc::downgrade(self) |
92 | } |
93 | } |
94 | |
95 | impl<T> Upgrade for rc::Weak<T> { |
96 | type Strong = Rc<T>; |
97 | |
98 | fn upgrade(&self) -> Option<Self::Strong> { |
99 | self.upgrade() |
100 | } |
101 | } |
102 | |