1use std::{
2 borrow::Cow,
3 fmt::{self, Debug},
4 hash::{Hash, Hasher},
5 sync::Arc,
6};
7
8pub enum ArcCow<'a, T: ?Sized> {
9 Borrowed(&'a T),
10 Owned(Arc<T>),
11}
12
13impl<'a, T: ?Sized + PartialEq> PartialEq for ArcCow<'a, T> {
14 fn eq(&self, other: &Self) -> bool {
15 let a = self.as_ref();
16 let b = other.as_ref();
17 a == b
18 }
19}
20
21impl<'a, T: ?Sized + Eq> Eq for ArcCow<'a, T> {}
22
23impl<'a, T: ?Sized + Hash> Hash for ArcCow<'a, T> {
24 fn hash<H: Hasher>(&self, state: &mut H) {
25 match self {
26 Self::Borrowed(borrowed) => Hash::hash(borrowed, state),
27 Self::Owned(owned) => Hash::hash(&**owned, state),
28 }
29 }
30}
31
32impl<'a, T: ?Sized> Clone for ArcCow<'a, T> {
33 fn clone(&self) -> Self {
34 match self {
35 Self::Borrowed(borrowed) => Self::Borrowed(borrowed),
36 Self::Owned(owned) => Self::Owned(owned.clone()),
37 }
38 }
39}
40
41impl<'a, T: ?Sized> From<&'a T> for ArcCow<'a, T> {
42 fn from(s: &'a T) -> Self {
43 Self::Borrowed(s)
44 }
45}
46
47impl<T> From<Arc<T>> for ArcCow<'_, T> {
48 fn from(s: Arc<T>) -> Self {
49 Self::Owned(s)
50 }
51}
52
53impl From<String> for ArcCow<'_, str> {
54 fn from(value: String) -> Self {
55 Self::Owned(value.into())
56 }
57}
58
59impl<'a> From<Cow<'a, str>> for ArcCow<'a, str> {
60 fn from(value: Cow<'a, str>) -> Self {
61 match value {
62 Cow::Borrowed(borrowed) => Self::Borrowed(borrowed),
63 Cow::Owned(owned) => Self::Owned(owned.into()),
64 }
65 }
66}
67
68impl<T> From<Vec<T>> for ArcCow<'_, [T]> {
69 fn from(vec: Vec<T>) -> Self {
70 ArcCow::Owned(Arc::from(vec))
71 }
72}
73
74impl<'a> From<&'a str> for ArcCow<'a, [u8]> {
75 fn from(s: &'a str) -> Self {
76 ArcCow::Borrowed(s.as_bytes())
77 }
78}
79
80impl<'a, T: ?Sized + ToOwned> std::borrow::Borrow<T> for ArcCow<'a, T> {
81 fn borrow(&self) -> &T {
82 match self {
83 ArcCow::Borrowed(borrowed) => borrowed,
84 ArcCow::Owned(owned) => owned.as_ref(),
85 }
86 }
87}
88
89impl<T: ?Sized> std::ops::Deref for ArcCow<'_, T> {
90 type Target = T;
91
92 fn deref(&self) -> &Self::Target {
93 match self {
94 ArcCow::Borrowed(s) => s,
95 ArcCow::Owned(s) => s.as_ref(),
96 }
97 }
98}
99
100impl<T: ?Sized> AsRef<T> for ArcCow<'_, T> {
101 fn as_ref(&self) -> &T {
102 match self {
103 ArcCow::Borrowed(borrowed) => borrowed,
104 ArcCow::Owned(owned) => owned.as_ref(),
105 }
106 }
107}
108
109impl<'a, T: ?Sized + Debug> Debug for ArcCow<'a, T> {
110 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
111 match self {
112 ArcCow::Borrowed(borrowed) => Debug::fmt(borrowed, f),
113 ArcCow::Owned(owned) => Debug::fmt(&**owned, f),
114 }
115 }
116}