atomicow/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
//! <style>
//! .rustdoc-hidden { display: none; }
//! </style>
#![doc = include_str!("../README.md")]

use std::{
    borrow::Borrow,
    fmt::{Debug, Display},
    hash::Hash,
    ops::Deref,
    path::{Path, PathBuf},
    sync::Arc,
};

/// Much like a [`Cow`](std::borrow::Cow), but owned values are [`Arc`]-ed to make clones cheap.
/// This should be used for values that are cloned for use across threads and change rarely (if
/// ever).
///
/// This also makes an opinionated tradeoff by adding a [`CowArc::Static`] and implementing
/// `From<&'static T>` instead of `From<'a T>`. This preserves the static context and prevents
/// conversion to [`CowArc::Owned`] in cases where a reference is known to be static. This is an
/// optimization that prevents allocations and atomic ref-counting.
///
/// This means that static references should prefer [`CowArc::from`] or [`CowArc::Static`] and
/// non-static references must use [`CowArc::Borrowed`].
pub enum CowArc<'a, T: ?Sized + 'static> {
    /// A borrowed value.
    Borrowed(&'a T),
    /// A static value reference.
    ///
    /// This exists to avoid conversion to [`CowArc::Owned`] in cases where a reference is
    /// known to be static. This is an optimization that prevents allocations and atomic
    /// ref-counting.
    Static(&'static T),
    /// An owned [`Arc`]-ed value.
    Owned(Arc<T>),
}

impl<T: ?Sized + 'static> CowArc<'static, T> {
    /// Creates a new [`CowArc::Owned`] from a value.
    ///
    /// This is simply a convenience method;
    /// the value will be wrapped in an [`Arc`].
    ///
    /// Note that `T` must be [`Sized`]: use the enum constructor directly if `T` is unsized.
    pub fn new_owned(value: T) -> Self
    where
        T: Sized,
    {
        CowArc::Owned(Arc::new(value))
    }

    /// Creates a new [`CowArc::Owned`] from an [`Arc`]-like value.
    ///
    /// The [`Arc`] will be moved into the [`CowArc`].
    pub fn new_owned_from_arc(value: impl Into<Arc<T>>) -> Self {
        CowArc::Owned(value.into())
    }
}

impl<T: ?Sized> CowArc<'static, T> {
    /// Indicates this [`CowArc`] should have a static lifetime.
    ///
    /// This ensures if this was created with a value `Borrowed(&'static T)`, it is replaced with
    /// `Static(&'static T)`. It is only possible to call this method if `'a` is `'static`.
    /// This has no effect if this is `Owned(Arc<T>)`.
    #[inline]
    pub fn as_static(self) -> Self {
        match self {
            Self::Borrowed(value) | Self::Static(value) => Self::Static(value),
            Self::Owned(value) => Self::Owned(value),
        }
    }
}

impl<'a, T: ?Sized> Deref for CowArc<'a, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        match self {
            CowArc::Borrowed(v) | CowArc::Static(v) => v,
            CowArc::Owned(v) => v,
        }
    }
}

impl<'a, T: ?Sized> Borrow<T> for CowArc<'a, T> {
    #[inline]
    fn borrow(&self) -> &T {
        self
    }
}

impl<'a, T: ?Sized> AsRef<T> for CowArc<'a, T> {
    #[inline]
    fn as_ref(&self) -> &T {
        self
    }
}

impl<'a, T: ?Sized> CowArc<'a, T>
where
    &'a T: Into<Arc<T>>,
{
    /// Converts this into an "owned" value.
    ///
    /// If internally a value is borrowed, it will be cloned into an "owned [`Arc`]".
    /// If it is already a [`CowArc::Owned`] or a [`CowArc::Static`], it will remain unchanged.
    #[inline]
    pub fn into_owned(self) -> CowArc<'static, T> {
        match self {
            CowArc::Borrowed(value) => CowArc::Owned(value.into()),
            CowArc::Static(value) => CowArc::Static(value),
            CowArc::Owned(value) => CowArc::Owned(value),
        }
    }

    /// Clones into an owned [`CowArc<'static>`].
    ///
    /// If internally a value is borrowed, it will be cloned into an "owned [`Arc`]".
    /// If it is already a [`CowArc::Owned`] or [`CowArc::Static`], the value will be cloned.
    /// This is equivalent to `.clone().into_owned()`.
    #[inline]
    pub fn clone_owned(&self) -> CowArc<'static, T> {
        self.clone().into_owned()
    }
}

impl<'a, T: ?Sized> Clone for CowArc<'a, T> {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Borrowed(value) => Self::Borrowed(value),
            Self::Static(value) => Self::Static(value),
            Self::Owned(value) => Self::Owned(value.clone()),
        }
    }
}

impl<'a, T: PartialEq + ?Sized> PartialEq for CowArc<'a, T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.deref().eq(other.deref())
    }
}

impl<'a, T: PartialEq + ?Sized> Eq for CowArc<'a, T> {}

impl<'a, T: Hash + ?Sized> Hash for CowArc<'a, T> {
    #[inline]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.deref().hash(state);
    }
}

impl<'a, T: Debug + ?Sized> Debug for CowArc<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(self.deref(), f)
    }
}

impl<'a, T: Display + ?Sized> Display for CowArc<'a, T> {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(self.deref(), f)
    }
}

impl<'a, T: PartialOrd + ?Sized> PartialOrd for CowArc<'a, T> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.deref().partial_cmp(other.deref())
    }
}

impl Default for CowArc<'static, str> {
    fn default() -> Self {
        CowArc::Static(Default::default())
    }
}

// A shortcut, since `Path` does not implement `Default`.
impl Default for CowArc<'static, Path> {
    /// Returns an empty [`Path`], wrapped in [`CowArc::Static`].
    ///
    /// This is equivalent to `CowArc::Static(Path::new(""))`.
    fn default() -> Self {
        CowArc::Static(Path::new(""))
    }
}

impl<'a, T: Ord + ?Sized> Ord for CowArc<'a, T> {
    #[inline]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.deref().cmp(other.deref())
    }
}

impl From<PathBuf> for CowArc<'static, Path> {
    #[inline]
    fn from(value: PathBuf) -> Self {
        CowArc::Owned(value.into())
    }
}

impl From<&'static str> for CowArc<'static, Path> {
    #[inline]
    fn from(value: &'static str) -> Self {
        CowArc::Static(Path::new(value))
    }
}

impl From<String> for CowArc<'static, str> {
    #[inline]
    fn from(value: String) -> Self {
        CowArc::Owned(value.into())
    }
}

impl<'a> From<&'a String> for CowArc<'a, str> {
    #[inline]
    fn from(value: &'a String) -> Self {
        CowArc::Borrowed(value)
    }
}

impl<T: ?Sized> From<&'static T> for CowArc<'static, T> {
    #[inline]
    fn from(value: &'static T) -> Self {
        CowArc::Static(value)
    }
}

impl<T> From<Arc<T>> for CowArc<'static, T> {
    #[inline]
    fn from(value: Arc<T>) -> Self {
        CowArc::Owned(value)
    }
}