vortex_array/
arcref.rs
1use std::cmp::Ordering;
2use std::fmt::{Debug, Display};
3use std::hash::Hash;
4use std::ops::Deref;
5use std::sync::Arc;
6
7pub struct ArcRef<T: ?Sized + 'static>(Inner<T>);
9
10enum Inner<T: ?Sized + 'static> {
11 Arc(Arc<T>),
12 Ref(&'static T),
13}
14
15impl<T: ?Sized> ArcRef<T> {
16 pub fn new_arc(t: Arc<T>) -> Self
17 where
18 T: 'static,
19 {
20 ArcRef(Inner::Arc(t))
21 }
22
23 pub const fn new_ref(t: &'static T) -> Self {
24 ArcRef(Inner::Ref(t))
25 }
26}
27
28impl<T: ?Sized> Clone for ArcRef<T> {
29 fn clone(&self) -> Self {
30 match &self.0 {
31 Inner::Arc(arc) => ArcRef(Inner::Arc(Arc::clone(arc))),
32 Inner::Ref(r) => ArcRef(Inner::Ref(*r)),
33 }
34 }
35}
36
37impl<T: ?Sized> From<&'static T> for ArcRef<T> {
38 fn from(r: &'static T) -> Self {
39 ArcRef(Inner::Ref(r))
40 }
41}
42
43impl<T: 'static> From<T> for ArcRef<T> {
44 fn from(t: T) -> Self {
45 ArcRef(Inner::Arc(Arc::new(t)))
46 }
47}
48
49impl<T: ?Sized + 'static> From<Arc<T>> for ArcRef<T> {
50 fn from(arc: Arc<T>) -> Self {
51 ArcRef(Inner::Arc(arc))
52 }
53}
54
55impl<T: ?Sized> Deref for ArcRef<T> {
56 type Target = T;
57
58 fn deref(&self) -> &Self::Target {
59 match &self.0 {
60 Inner::Arc(arc) => arc,
61 Inner::Ref(r) => r,
62 }
63 }
64}
65
66impl<S, T> PartialEq<ArcRef<S>> for ArcRef<T>
67where
68 S: ?Sized + 'static,
69 T: ?Sized + 'static + PartialEq<S>,
70{
71 fn eq(&self, other: &ArcRef<S>) -> bool {
72 self.deref() == other.deref()
73 }
74}
75
76impl<T> Eq for ArcRef<T> where T: ?Sized + 'static + Eq {}
77
78impl<S, T> PartialOrd<ArcRef<S>> for ArcRef<T>
79where
80 S: ?Sized + 'static,
81 T: ?Sized + 'static + PartialOrd<S>,
82{
83 fn partial_cmp(&self, other: &ArcRef<S>) -> Option<Ordering> {
84 self.deref().partial_cmp(other.deref())
85 }
86}
87
88impl<T> Ord for ArcRef<T>
89where
90 T: ?Sized + 'static + Ord,
91{
92 fn cmp(&self, other: &Self) -> Ordering {
93 self.deref().cmp(other.deref())
94 }
95}
96
97impl<T> Hash for ArcRef<T>
98where
99 T: ?Sized + 'static + Hash,
100{
101 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
102 self.deref().hash(state)
103 }
104}
105
106impl<T> Debug for ArcRef<T>
107where
108 T: ?Sized + 'static + Debug,
109{
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 self.deref().fmt(f)
112 }
113}
114
115impl<T> Display for ArcRef<T>
116where
117 T: ?Sized + 'static + Display,
118{
119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120 self.deref().fmt(f)
121 }
122}
123
124impl<T: ?Sized + 'static> AsRef<T> for ArcRef<T> {
125 fn as_ref(&self) -> &T {
126 self
127 }
128}