shallowclone/
cows.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
//! [`Cow`][std::borrow::Cow] alternatives that work well with [`ShallowClone`][crate::ShallowClone].

// standard Cow doesn't work well with shallow clone, since it's invariant over T,
// which introduces problems when T has a lifetime param. If you use Cow you would be forced
// to have two lifetime parameters basically everywhere for no reason, because
// when you shallow clone it you shorten the lifetime of the cow, but can't shorten the lifetime
// of the inner T, and so you end up with two different lifetimes. The following cow implementations
// are simpler, not relying on the ToOwned trait and are covariant over T, therefore not having
// this problem.

use std::{
	borrow::{Borrow, Cow},
	fmt::{Display, Formatter},
	ops::Deref,
};

use crate::{MakeOwned, ShallowClone};

/// Covariant copy-on-write. This is a simpler version of [`Cow`][std::borrow::Cow] that doesn't
/// rely on [`ToOwned`] trait and is covariant over `T`.
///
/// You may wish to use this instead of the standard [`Cow`][std::borrow::Cow] if your
/// inner type `T` contains references. Standard [`Cow<T>`][std::borrow::Cow] is invariant over `T`,
/// which means you can't subtype the lifetimes of the inner `T` when making a shallow clone, which
/// may introduce problems and force you to use multiple lifetimes.
///
/// This is a general version, if you wish to replicate [`Cow<'a, [T]>`][std::borrow::Cow] you
/// should consider using [`CoCowSlice`], which allows you to have slices without an underlying
/// allocated type like [`Vec`][std::vec::Vec].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(untagged))]
pub enum CoCow<'a, T> {
	Owned(T),
	#[cfg_attr(feature = "serde", serde(skip_deserializing))]
	Borrowed(&'a T),
}

/// Covariant copy-on-write slice. This is a specialised version of [`CoCow`] for slices
/// and allows you to have slices without an underlying allocated type like Vec if you wish.
///
/// You may wish to use this instead of the standard [`Cow`][std::borrow::Cow] if your
/// inner type `T` contains references. Standard [`Cow<T>`][std::borrow::Cow] is invariant over `T`, which means
/// you can't subtype the lifetimes of the inner `T` when making a shallow clone, which
/// may introduce problems and force you to use multiple lifetimes.
///
/// For a more general version, see [`CoCow`].
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(untagged))]
pub enum CoCowSlice<'a, T> {
	Owned(Vec<T>),
	#[cfg_attr(feature = "serde", serde(skip_deserializing))]
	Borrowed(&'a [T]),
}

impl<'a, T: Clone> CoCow<'a, T> {
	/// Returns the inner owned value, cloning if it was borrowed.
	pub fn into_owned(self) -> T {
		match self {
			CoCow::Owned(owned) => owned,
			CoCow::Borrowed(borrowed) => borrowed.clone(),
		}
	}
	/// Returns a mutable reference to the inner owned value, cloning if it was borrowed.
	pub fn to_mut(&mut self) -> &mut T {
		match self {
			CoCow::Owned(owned) => owned,
			CoCow::Borrowed(borrowed) => {
				*self = CoCow::Owned(borrowed.clone());
				match self {
					CoCow::Owned(owned) => owned,
					_ => unreachable!(),
				}
			}
		}
	}
}
impl<'a, T> CoCow<'a, T> {
	/// Returns `true` if the value is borrowed.
	pub fn is_borrowed(&self) -> bool {
		matches!(self, CoCow::Borrowed(_))
	}
	/// Returns `true` if the value is owned.
	pub fn is_owned(&self) -> bool {
		matches!(self, CoCow::Owned(_))
	}
}

impl<'a, T: Clone> CoCowSlice<'a, T> {
	/// Returns the inner owned [`Vec`][std::vec::Vec], cloning if it was borrowed.
	pub fn into_owned(self) -> Vec<T> {
		match self {
			CoCowSlice::Owned(owned) => owned,
			CoCowSlice::Borrowed(borrowed) => borrowed.to_owned(),
		}
	}
	/// Returns a mutable reference to the inner owned [`Vec`][std::vec::Vec], cloning if it was borrowed.
	pub fn to_mut(&mut self) -> &mut Vec<T> {
		match self {
			CoCowSlice::Owned(owned) => owned,
			CoCowSlice::Borrowed(borrowed) => {
				*self = CoCowSlice::Owned(borrowed.to_owned());
				match self {
					CoCowSlice::Owned(owned) => owned,
					_ => unreachable!(),
				}
			}
		}
	}
}
impl<'a, T> CoCowSlice<'a, T> {
	/// Returns `true` if the value is borrowed.
	pub fn is_borrowed(&self) -> bool {
		matches!(self, CoCowSlice::Borrowed(_))
	}
	/// Returns `true` if the value is owned.
	pub fn is_owned(&self) -> bool {
		matches!(self, CoCowSlice::Owned(_))
	}
}

impl<'a, T> ShallowClone<'a> for CoCow<'a, T> {
	type Target = CoCow<'a, T>;

	fn shallow_clone(&'a self) -> Self::Target {
		match self {
			CoCow::Owned(owned) => CoCow::Borrowed(&owned),
			CoCow::Borrowed(borrowed) => CoCow::Borrowed(borrowed),
		}
	}
}
impl<'a, T> ShallowClone<'a> for CoCowSlice<'a, T> {
	type Target = CoCowSlice<'a, T>;

	fn shallow_clone(&'a self) -> Self::Target {
		match self {
			CoCowSlice::Owned(owned) => CoCowSlice::Borrowed(&owned),
			CoCowSlice::Borrowed(borrowed) => CoCowSlice::Borrowed(borrowed),
		}
	}
}

impl<'a, T: MakeOwned> MakeOwned for CoCow<'a, T>
where
	<T as MakeOwned>::Owned: Clone,
{
	type Owned = CoCow<'static, <T as MakeOwned>::Owned>;

	fn make_owned(self) -> <Self as MakeOwned>::Owned {
		CoCow::Owned(self.into_owned().make_owned())
	}
}
impl<'a, T: MakeOwned> MakeOwned for CoCowSlice<'a, T>
where
	<T as MakeOwned>::Owned: Clone,
{
	type Owned = CoCowSlice<'static, <T as MakeOwned>::Owned>;

	fn make_owned(self) -> <Self as MakeOwned>::Owned {
		CoCowSlice::Owned(self.into_owned().make_owned())
	}
}

impl<'a, T> Deref for CoCow<'a, T> {
	type Target = T;

	fn deref(&self) -> &Self::Target {
		match self {
			CoCow::Owned(owned) => owned,
			CoCow::Borrowed(borrowed) => borrowed,
		}
	}
}
impl<'a, T> Deref for CoCowSlice<'a, T> {
	type Target = [T];

	fn deref(&self) -> &Self::Target {
		match self {
			CoCowSlice::Owned(owned) => owned,
			CoCowSlice::Borrowed(borrowed) => borrowed,
		}
	}
}

impl<'a, T> AsRef<T> for CoCow<'a, T> {
	fn as_ref(&self) -> &T {
		self
	}
}
impl<'a, T> AsRef<[T]> for CoCowSlice<'a, T> {
	fn as_ref(&self) -> &[T] {
		self
	}
}

impl<'a, T> Borrow<T> for CoCow<'a, T> {
	fn borrow(&self) -> &T {
		self
	}
}
impl<'a, T> Borrow<[T]> for CoCowSlice<'a, T> {
	fn borrow(&self) -> &[T] {
		self
	}
}

impl<'a, T: Default> Default for CoCow<'a, T> {
	fn default() -> Self {
		CoCow::Owned(Default::default())
	}
}
impl<'a, T> Default for CoCowSlice<'a, T> {
	fn default() -> Self {
		CoCowSlice::Owned(Default::default())
	}
}

impl<'a, T: Display> Display for CoCow<'a, T> {
	fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
		Display::fmt(&**self, f)
	}
}

impl<'a, T> From<T> for CoCow<'a, T> {
	fn from(value: T) -> Self {
		CoCow::Owned(value)
	}
}
impl<'a, T> From<Vec<T>> for CoCowSlice<'a, T> {
	fn from(value: Vec<T>) -> Self {
		CoCowSlice::Owned(value)
	}
}

impl<'a, T> From<&'a T> for CoCow<'a, T> {
	fn from(value: &'a T) -> Self {
		CoCow::Borrowed(value)
	}
}
impl<'a, T> From<&'a [T]> for CoCowSlice<'a, T> {
	fn from(value: &'a [T]) -> Self {
		CoCowSlice::Borrowed(value)
	}
}
impl<'a, T> From<&'a Vec<T>> for CoCowSlice<'a, T> {
	fn from(value: &'a Vec<T>) -> Self {
		CoCowSlice::Borrowed(value)
	}
}
impl<'a, const N: usize, T> From<&'a [T; N]> for CoCowSlice<'a, T> {
	fn from(value: &'a [T; N]) -> Self {
		CoCowSlice::Borrowed(value)
	}
}

impl<'a, T: Clone> From<Cow<'a, T>> for CoCow<'a, T> {
	fn from(value: Cow<'a, T>) -> Self {
		match value {
			Cow::Borrowed(borrowed) => Self::Borrowed(borrowed),
			Cow::Owned(owned) => Self::Owned(owned),
		}
	}
}
impl<'a, T: Clone> From<Cow<'a, [T]>> for CoCowSlice<'a, T> {
	fn from(value: Cow<'a, [T]>) -> Self {
		match value {
			Cow::Borrowed(borrowed) => Self::Borrowed(borrowed),
			Cow::Owned(owned) => Self::Owned(owned),
		}
	}
}

impl<'a, T> IntoIterator for &'a CoCow<'a, T>
where
	&'a T: IntoIterator,
{
	type Item = <&'a T as IntoIterator>::Item;
	type IntoIter = <&'a T as IntoIterator>::IntoIter;

	fn into_iter(self) -> Self::IntoIter {
		match self {
			CoCow::Owned(owned) => owned.into_iter(),
			CoCow::Borrowed(borrowed) => borrowed.into_iter(),
		}
	}
}
impl<'a, T> IntoIterator for &'a CoCowSlice<'a, T>
where
	&'a [T]: IntoIterator,
{
	type Item = <&'a [T] as IntoIterator>::Item;
	type IntoIter = <&'a [T] as IntoIterator>::IntoIter;

	fn into_iter(self) -> Self::IntoIter {
		match self {
			CoCowSlice::Owned(owned) => (&owned[..]).into_iter(),
			CoCowSlice::Borrowed(borrowed) => borrowed.into_iter(),
		}
	}
}

#[cfg(test)]
mod tests {
	use super::{CoCow, CoCowSlice};
	use crate::ShallowClone;

	#[test]
	fn test_covariance() {
		// make sure these cows are actually covariant
		#[derive(ShallowClone, Clone)]
		struct MyStruct<'a>(#[allow(dead_code)] &'a ());

		let u = ();

		let x = MyStruct(&u);
		let cocow: CoCow<MyStruct> = CoCow::from(x);
		fn test<'a>(_: CoCow<'a, MyStruct<'a>>) {}
		test(cocow.shallow_clone());

		let y = [(); 100].map(|_| MyStruct(&u));
		let cocow_slice: CoCowSlice<MyStruct> = CoCowSlice::from(&y[..]);
		fn test_slice<'a>(_: CoCowSlice<'a, MyStruct<'a>>) {}
		test_slice(cocow_slice.shallow_clone());
	}
}