metrics/
cow.rs

1use std::{
2    borrow::Borrow,
3    cmp::Ordering,
4    fmt,
5    hash::{Hash, Hasher},
6    marker::PhantomData,
7    mem::ManuallyDrop,
8    ops::Deref,
9    ptr::{slice_from_raw_parts, NonNull},
10    sync::Arc,
11};
12
13#[derive(Clone, Copy)]
14enum Kind {
15    Owned,
16    Borrowed,
17    Shared,
18}
19
20/// A clone-on-write smart pointer with an optimized memory layout, based on `beef`.
21///
22/// # Strings, strings everywhere
23///
24/// In `metrics`, strings are arguably the most common data type used despite the fact that metrics
25/// are measuring numerical values. Both the name of a metric, and its labels, are strings: emitting
26/// a metric may involve one string, or 10 strings. Many of these strings tend to be used over and
27/// over during the life of the process, as well.
28///
29/// In order to achieve and maintain a high level of performance, we use a "clone-on-write" smart
30/// pointer to handle passing these strings around. Doing so allows us to potentially avoid having
31/// to allocate entire copies of a string, instead using a lightweight smart pointer that can live
32/// on the stack.
33///
34/// # Why not `std::borrow::Cow`?
35///
36/// The standard library already provides a clone-on-write smart pointer, `std::borrow::Cow`, which
37/// works well in many cases. However, `metrics` strives to provide minimal overhead where possible,
38/// and so `std::borrow::Cow` falls down in one particular way: it uses an enum representation which
39/// consumes an additional word of storage.
40///
41/// As an example, let's look at strings. A string in `std::borrow::Cow` implies that `T` is `str`,
42/// and the owned version of `str` is simply `String`. Thus, for `std::borrow::Cow`, the in-memory
43/// layout looks like this:
44///
45/// ```text
46///                                                                       Padding
47///                                                                          |
48///                                                                          v
49///                       +--------------+-------------+--------------+--------------+
50/// stdlib Cow::Borrowed: |   Enum Tag   |   Pointer   |    Length    |   XXXXXXXX   |
51///                       +--------------+-------------+--------------+--------------+
52///                       +--------------+-------------+--------------+--------------+
53/// stdlib Cow::Owned:    |   Enum Tag   |   Pointer   |    Length    |   Capacity   |
54///                       +--------------+-------------+--------------+--------------+
55/// ```
56///
57/// As you can see, you pay a memory size penalty to be able to wrap an owned string. This
58/// additional word adds minimal overhead, but we can easily avoid it with some clever logic around
59/// the values of the length and capacity fields.
60///
61/// There is an existing crate that does just that: `beef`. Instead of using an enum, it is simply a
62/// struct that encodes the discriminant values in the length and capacity fields directly. If we're
63/// wrapping a borrowed value, we can infer that the "capacity" will always be zero, as we only need
64/// to track the capacity when we're wrapping an owned value, in order to be able to recreate the
65/// underlying storage when consuming the smart pointer, or dropping it. Instead of the above
66/// layout, `beef` looks like this:
67///
68/// ```text
69///                        +-------------+--------------+----------------+
70/// `beef` Cow (borrowed): |   Pointer   |  Length (N)  |  Capacity (0)  |
71///                        +-------------+--------------+----------------+
72///                        +-------------+--------------+----------------+
73/// `beef` Cow (owned):    |   Pointer   |  Length (N)  |  Capacity (M)  |
74///                        +-------------+--------------+----------------+
75/// ```
76///
77/// # Why not `beef`?
78///
79/// Up until this point, it might not be clear why we didn't just use `beef`. In truth, our design
80/// is fundamentally based on `beef`. Crucially, however, `beef` did not/still does not support
81/// `const` construction for generic slices.  Remember how we mentioned labels? The labels of a
82/// metric `are `[Label]` under-the-hood, and so without a way to construct them in a `const`
83/// fashion, our previous work to allow entirely static keys would not be possible.
84///
85/// Thus, we forked `beef` and copied into directly into `metrics` so that we could write a
86/// specialized `const` constructor for `[Label]`.
87///
88/// This is why we have our own `Cow` bundled into `metrics` directly, which is based on `beef`. In
89/// doing so, we can experiment with more interesting optimizations, and, as mentioned above, we can
90/// add const methods to support all of the types involved in statically building metrics keys.
91///
92/// # What we do that `beef` doesn't do
93///
94/// It was already enough to use our own implementation for the specialized `const` capabilities,
95/// but we've taken things even further in a key way: support for `Arc`-wrapped values.
96///
97/// ## `Arc`-wrapped values
98///
99/// For many strings, there is still a desire to share them cheaply even when they are constructed
100/// at run-time.  Remember, cloning a `Cow` of an owned value means cloning the value itself, so we
101/// need another level of indirection to allow the cheap sharing, which is where `Arc<T>` can
102/// provide value.
103///
104/// Users can construct a `Arc<T>`, where `T` is lined up with the `T` of `metrics::Cow`, and use
105/// that as the initial value instead. When `Cow` is cloned, we end up cloning the underlying
106/// `Arc<T>` instead, avoiding a new allocation.  `Arc<T>` still handles all of the normal logic
107/// necessary to know when the wrapped value must be dropped, and how many live references to the
108/// value that there are, and so on.
109///
110/// We handle this by relying on an invariant of `Vec<T>`: it never allocates more than `isize::MAX`
111/// [1]. This lets us derive the following truth table of the valid combinations of length/capacity:
112///
113/// ```text
114///                         Length (N)     Capacity (M)
115///                     +---------------+----------------+
116/// Borrowed (&T):      |       N       |        0       |
117///                     +---------------+----------------+
118/// Owned (T::ToOwned): |       N       | M < usize::MAX |
119///                     +---------------+----------------+
120/// Shared (Arc<T>):    |       N       |   usize::MAX   |
121///                     +---------------+----------------+
122/// ```
123///
124/// As we only implement `Cow` for types where their owned variants are either explicitly or
125/// implicitly backed by `Vec<_>`, we know that our capacity will never be `usize::MAX`, as it is
126/// limited to `isize::MAX`, and thus we can safely encode our "shared" state within the capacity
127/// field.
128///
129/// # Notes
130///
131/// [1] - technically, `Vec<T>` can have a capacity greater than `isize::MAX` when storing
132/// zero-sized types, but we don't do that here, so we always enforce that an owned version's
133/// capacity cannot be `usize::MAX` when constructing `Cow`.
134pub struct Cow<'a, T: Cowable + ?Sized + 'a> {
135    ptr: NonNull<T::Pointer>,
136    metadata: Metadata,
137    _lifetime: PhantomData<&'a T>,
138}
139
140impl<T> Cow<'_, T>
141where
142    T: Cowable + ?Sized,
143{
144    fn from_parts(ptr: NonNull<T::Pointer>, metadata: Metadata) -> Self {
145        Self { ptr, metadata, _lifetime: PhantomData }
146    }
147
148    /// Creates a pointer to an owned value, consuming it.
149    pub fn from_owned(owned: T::Owned) -> Self {
150        let (ptr, metadata) = T::owned_into_parts(owned);
151
152        // This check is partially to guard against the semantics of `Vec<T>` changing in the
153        // future, and partially to ensure that we don't somehow implement `Cowable` for a type
154        // where its owned version is backed by a vector of ZSTs, where the capacity could
155        // _legitimately_ be `usize::MAX`.
156        if metadata.capacity() == usize::MAX {
157            panic!("Invalid capacity of `usize::MAX` for owned value.");
158        }
159
160        Self::from_parts(ptr, metadata)
161    }
162
163    /// Creates a pointer to a shared value.
164    pub fn from_shared(arc: Arc<T>) -> Self {
165        let (ptr, metadata) = T::shared_into_parts(arc);
166        Self::from_parts(ptr, metadata)
167    }
168
169    /// Extracts the owned data.
170    ///
171    /// Clones the data if it is not already owned.
172    pub fn into_owned(self) -> <T as ToOwned>::Owned {
173        // We need to ensure that our own `Drop` impl does _not_ run because we're simply
174        // transferring ownership of the value back to the caller. For borrowed values, this is
175        // naturally a no-op because there's nothing to drop, but for owned values, like `String` or
176        // `Arc<T>`, we wouldn't want to double drop.
177        let cow = ManuallyDrop::new(self);
178
179        T::owned_from_parts(cow.ptr, &cow.metadata)
180    }
181}
182
183impl<'a, T> Cow<'a, T>
184where
185    T: Cowable + ?Sized,
186{
187    /// Creates a pointer to a borrowed value.
188    pub fn from_borrowed(borrowed: &'a T) -> Self {
189        let (ptr, metadata) = T::borrowed_into_parts(borrowed);
190
191        Self::from_parts(ptr, metadata)
192    }
193}
194
195impl<'a, T> Cow<'a, [T]>
196where
197    T: Clone,
198{
199    pub const fn const_slice(val: &'a [T]) -> Cow<'a, [T]> {
200        // SAFETY: We can never create a null pointer by casting a reference to a pointer.
201        let ptr = unsafe { NonNull::new_unchecked(val.as_ptr() as *mut _) };
202        let metadata = Metadata::borrowed(val.len());
203
204        Self { ptr, metadata, _lifetime: PhantomData }
205    }
206}
207
208impl<'a> Cow<'a, str> {
209    pub const fn const_str(val: &'a str) -> Self {
210        // SAFETY: We can never create a null pointer by casting a reference to a pointer.
211        let ptr = unsafe { NonNull::new_unchecked(val.as_ptr() as *mut _) };
212        let metadata = Metadata::borrowed(val.len());
213
214        Self { ptr, metadata, _lifetime: PhantomData }
215    }
216}
217
218impl<T> Deref for Cow<'_, T>
219where
220    T: Cowable + ?Sized,
221{
222    type Target = T;
223
224    fn deref(&self) -> &Self::Target {
225        let borrowed_ptr = T::borrowed_from_parts(self.ptr, &self.metadata);
226
227        // SAFETY: We only ever hold a pointer to a borrowed value of at least the lifetime of
228        // `Self`, or an owned value which we have ownership of (albeit indirectly when using
229        // `Arc<T>`), so our pointer is always valid and live for derefencing.
230        unsafe { borrowed_ptr.as_ref().unwrap() }
231    }
232}
233
234impl<T> Clone for Cow<'_, T>
235where
236    T: Cowable + ?Sized,
237{
238    fn clone(&self) -> Self {
239        let (ptr, metadata) = T::clone_from_parts(self.ptr, &self.metadata);
240        Self { ptr, metadata, _lifetime: PhantomData }
241    }
242}
243
244impl<T> Drop for Cow<'_, T>
245where
246    T: Cowable + ?Sized,
247{
248    fn drop(&mut self) {
249        T::drop_from_parts(self.ptr, &self.metadata);
250    }
251}
252
253impl<T> Hash for Cow<'_, T>
254where
255    T: Hash + Cowable + ?Sized,
256{
257    #[inline]
258    fn hash<H: Hasher>(&self, state: &mut H) {
259        self.deref().hash(state)
260    }
261}
262
263impl<'a, T> Default for Cow<'a, T>
264where
265    T: Cowable + ?Sized,
266    &'a T: Default,
267{
268    #[inline]
269    fn default() -> Self {
270        Cow::from_borrowed(Default::default())
271    }
272}
273
274impl<T> Eq for Cow<'_, T> where T: Eq + Cowable + ?Sized {}
275
276impl<A, B> PartialOrd<Cow<'_, B>> for Cow<'_, A>
277where
278    A: Cowable + ?Sized + PartialOrd<B>,
279    B: Cowable + ?Sized,
280{
281    #[inline]
282    fn partial_cmp(&self, other: &Cow<'_, B>) -> Option<Ordering> {
283        PartialOrd::partial_cmp(self.deref(), other.deref())
284    }
285}
286
287impl<T> Ord for Cow<'_, T>
288where
289    T: Ord + Cowable + ?Sized,
290{
291    #[inline]
292    fn cmp(&self, other: &Self) -> Ordering {
293        Ord::cmp(self.deref(), other.deref())
294    }
295}
296
297impl<'a, T> From<&'a T> for Cow<'a, T>
298where
299    T: Cowable + ?Sized,
300{
301    #[inline]
302    fn from(val: &'a T) -> Self {
303        Cow::from_borrowed(val)
304    }
305}
306
307impl<'a, T> From<Arc<T>> for Cow<'a, T>
308where
309    T: Cowable + ?Sized,
310{
311    #[inline]
312    fn from(val: Arc<T>) -> Self {
313        Cow::from_shared(val)
314    }
315}
316
317impl<'a> From<std::borrow::Cow<'a, str>> for Cow<'a, str> {
318    #[inline]
319    fn from(s: std::borrow::Cow<'a, str>) -> Self {
320        match s {
321            std::borrow::Cow::Borrowed(bs) => Cow::from_borrowed(bs),
322            std::borrow::Cow::Owned(os) => Cow::from_owned(os),
323        }
324    }
325}
326
327impl<'a, T: Cowable> From<Cow<'a, T>> for std::borrow::Cow<'a, T> {
328    #[inline]
329    fn from(value: Cow<'a, T>) -> Self {
330        match value.metadata.kind() {
331            Kind::Owned | Kind::Shared => Self::Owned(value.into_owned()),
332            Kind::Borrowed => {
333                // SAFETY: We know the contained data is borrowed from 'a, we're simply
334                // restoring the original immutable reference and returning a copy of it.
335                Self::Borrowed(unsafe { &*T::borrowed_from_parts(value.ptr, &value.metadata) })
336            }
337        }
338    }
339}
340
341impl From<String> for Cow<'_, str> {
342    #[inline]
343    fn from(s: String) -> Self {
344        Cow::from_owned(s)
345    }
346}
347
348impl<T> From<Vec<T>> for Cow<'_, [T]>
349where
350    T: Clone,
351{
352    #[inline]
353    fn from(v: Vec<T>) -> Self {
354        Cow::from_owned(v)
355    }
356}
357
358impl<T> AsRef<T> for Cow<'_, T>
359where
360    T: Cowable + ?Sized,
361{
362    #[inline]
363    fn as_ref(&self) -> &T {
364        self.borrow()
365    }
366}
367
368impl<T> Borrow<T> for Cow<'_, T>
369where
370    T: Cowable + ?Sized,
371{
372    #[inline]
373    fn borrow(&self) -> &T {
374        self.deref()
375    }
376}
377
378impl<A, B> PartialEq<Cow<'_, B>> for Cow<'_, A>
379where
380    A: Cowable + ?Sized,
381    B: Cowable + ?Sized,
382    A: PartialEq<B>,
383{
384    fn eq(&self, other: &Cow<B>) -> bool {
385        self.deref() == other.deref()
386    }
387}
388
389impl<T> fmt::Debug for Cow<'_, T>
390where
391    T: Cowable + fmt::Debug + ?Sized,
392{
393    #[inline]
394    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
395        self.deref().fmt(f)
396    }
397}
398
399impl<T> fmt::Display for Cow<'_, T>
400where
401    T: Cowable + fmt::Display + ?Sized,
402{
403    #[inline]
404    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
405        self.deref().fmt(f)
406    }
407}
408
409// SAFETY: `NonNull<T>` is not `Send` or `Sync` by default, but we're asserting that `Cow` is so
410// long as the underlying `T` is.
411unsafe impl<T: Cowable + Sync + ?Sized> Sync for Cow<'_, T> {}
412unsafe impl<T: Cowable + Send + ?Sized> Send for Cow<'_, T> {}
413
414#[repr(C)]
415#[derive(Clone, Copy, PartialEq, Eq)]
416pub struct Metadata(usize, usize);
417
418impl Metadata {
419    #[inline]
420    const fn len(&self) -> usize {
421        self.0
422    }
423
424    #[inline]
425    const fn capacity(&self) -> usize {
426        self.1
427    }
428
429    #[inline]
430    const fn kind(&self) -> Kind {
431        match (self.0, self.1) {
432            (_, usize::MAX) => Kind::Shared,
433            (_, 0) => Kind::Borrowed,
434            _ => Kind::Owned,
435        }
436    }
437
438    #[inline]
439    const fn shared(len: usize) -> Metadata {
440        Metadata(len, usize::MAX)
441    }
442
443    #[inline]
444    const fn borrowed(len: usize) -> Metadata {
445        Metadata(len, 0)
446    }
447
448    #[inline]
449    const fn owned(len: usize, capacity: usize) -> Metadata {
450        Metadata(len, capacity)
451    }
452}
453
454pub trait Cowable: ToOwned {
455    type Pointer;
456
457    fn borrowed_into_parts(&self) -> (NonNull<Self::Pointer>, Metadata);
458    fn owned_into_parts(owned: <Self as ToOwned>::Owned) -> (NonNull<Self::Pointer>, Metadata);
459    fn shared_into_parts(arc: Arc<Self>) -> (NonNull<Self::Pointer>, Metadata);
460
461    fn borrowed_from_parts(ptr: NonNull<Self::Pointer>, metadata: &Metadata) -> *const Self;
462    fn owned_from_parts(
463        ptr: NonNull<Self::Pointer>,
464        metadata: &Metadata,
465    ) -> <Self as ToOwned>::Owned;
466    fn clone_from_parts(
467        ptr: NonNull<Self::Pointer>,
468        metadata: &Metadata,
469    ) -> (NonNull<Self::Pointer>, Metadata);
470    fn drop_from_parts(ptr: NonNull<Self::Pointer>, metadata: &Metadata);
471}
472
473impl Cowable for str {
474    type Pointer = u8;
475
476    #[inline]
477    fn borrowed_into_parts(&self) -> (NonNull<Self::Pointer>, Metadata) {
478        // SAFETY: We know that it's safe to take and hold a pointer to a reference to `Self` since
479        // `Cow` can only live as long as the input reference does, and an invalid pointer cannot
480        // be taken from a live reference.
481        let ptr = unsafe { NonNull::new_unchecked(self.as_ptr() as *mut _) };
482        let metadata = Metadata::borrowed(self.len());
483        (ptr, metadata)
484    }
485
486    #[inline]
487    fn owned_into_parts(owned: Self::Owned) -> (NonNull<Self::Pointer>, Metadata) {
488        // SAFETY: We know that it's safe to take and hold a pointer to a reference to `owned` since
489        // we own the allocation by virtue of consuming it here without dropping it.
490        let mut owned = ManuallyDrop::new(owned.into_bytes());
491        let ptr = unsafe { NonNull::new_unchecked(owned.as_mut_ptr()) };
492        let metadata = Metadata::owned(owned.len(), owned.capacity());
493        (ptr, metadata)
494    }
495
496    #[inline]
497    fn shared_into_parts(arc: Arc<Self>) -> (NonNull<Self::Pointer>, Metadata) {
498        let metadata = Metadata::shared(arc.len());
499        // SAFETY: We know that the pointer given back by `Arc::into_raw` is valid.
500        let ptr = unsafe { NonNull::new_unchecked(Arc::into_raw(arc) as *mut _) };
501        (ptr, metadata)
502    }
503
504    #[inline]
505    fn borrowed_from_parts(ptr: NonNull<Self::Pointer>, metadata: &Metadata) -> *const Self {
506        slice_from_raw_parts(ptr.as_ptr(), metadata.len()) as *const _
507    }
508
509    #[inline]
510    fn owned_from_parts(
511        ptr: NonNull<Self::Pointer>,
512        metadata: &Metadata,
513    ) -> <Self as ToOwned>::Owned {
514        match metadata.kind() {
515            Kind::Borrowed => {
516                // SAFETY: We know that it's safe to take and hold a pointer to a reference to
517                // `Self` since `Cow` can only live as long as the input reference does, and an
518                // invalid pointer cannot be taken from a live reference.
519                let s = unsafe { &*Self::borrowed_from_parts(ptr, metadata) };
520                s.to_owned()
521            }
522
523            // SAFETY: We know that the pointer is valid because it could have only been constructed
524            // from a valid `String` handed to `Cow::from_owned`, which we assumed ownership of.
525            Kind::Owned => unsafe {
526                String::from_raw_parts(ptr.as_ptr(), metadata.len(), metadata.capacity())
527            },
528            Kind::Shared => {
529                // SAFETY: We know that the pointer is valid because it could have only been
530                // constructed from a valid `Arc<str>` handed to `Cow::from_shared`, which we
531                // assumed ownership of, also ensuring that the strong count is at least one.
532                let s = unsafe { Arc::from_raw(Self::borrowed_from_parts(ptr, metadata)) };
533                s.to_string()
534            }
535        }
536    }
537
538    #[inline]
539    fn clone_from_parts(
540        ptr: NonNull<Self::Pointer>,
541        metadata: &Metadata,
542    ) -> (NonNull<Self::Pointer>, Metadata) {
543        match metadata.kind() {
544            Kind::Borrowed => (ptr, *metadata),
545            Kind::Owned => {
546                // SAFETY: We know that the pointer is valid because it could have only been constructed
547                // from a valid `String` handed to `Cow::from_owned`, which we assumed ownership of.
548                let s = unsafe { &*Self::borrowed_from_parts(ptr, metadata) };
549
550                Self::owned_into_parts(s.to_string())
551            }
552            Kind::Shared => clone_shared::<Self>(ptr, metadata),
553        }
554    }
555
556    #[inline]
557    fn drop_from_parts(ptr: NonNull<Self::Pointer>, metadata: &Metadata) {
558        match metadata.kind() {
559            Kind::Borrowed => {}
560
561            // SAFETY: We know that the pointer is valid because it could have only been constructed
562            // from a valid `String` handed to `Cow::from_owned`, which we assumed ownership of.
563            Kind::Owned => unsafe {
564                drop(Vec::from_raw_parts(ptr.as_ptr(), metadata.len(), metadata.capacity()));
565            },
566
567            // SAFETY: We know that the pointer is valid because it could have only been constructed
568            // from a valid `Arc<str>` handed to `Cow::from_shared`, which we assumed ownership of,
569            // also ensuring that the strong count is at least one.
570            Kind::Shared => unsafe {
571                drop(Arc::from_raw(Self::borrowed_from_parts(ptr, metadata)));
572            },
573        }
574    }
575}
576
577impl<T> Cowable for [T]
578where
579    T: Clone,
580{
581    type Pointer = T;
582
583    #[inline]
584    fn borrowed_into_parts(&self) -> (NonNull<Self::Pointer>, Metadata) {
585        // SAFETY: We know that it's safe to take and hold a pointer to a reference to `Self` since
586        // `Cow` can only live as long as the input reference does, and an invalid pointer cannot
587        // be taken from a live reference.
588        let ptr = unsafe { NonNull::new_unchecked(self.as_ptr() as *mut _) };
589        let metadata = Metadata::borrowed(self.len());
590        (ptr, metadata)
591    }
592
593    #[inline]
594    fn owned_into_parts(owned: <Self as ToOwned>::Owned) -> (NonNull<Self::Pointer>, Metadata) {
595        let mut owned = ManuallyDrop::new(owned);
596
597        // SAFETY: We know that it's safe to take and hold a pointer to a reference to `owned` since
598        // we own the allocation by virtue of consuming it here without dropping it.
599        let ptr = unsafe { NonNull::new_unchecked(owned.as_mut_ptr()) };
600        let metadata = Metadata::owned(owned.len(), owned.capacity());
601        (ptr, metadata)
602    }
603
604    #[inline]
605    fn shared_into_parts(arc: Arc<Self>) -> (NonNull<Self::Pointer>, Metadata) {
606        let metadata = Metadata::shared(arc.len());
607        // SAFETY: We know that the pointer given back by `Arc::into_raw` is valid.
608        let ptr = unsafe { NonNull::new_unchecked(Arc::into_raw(arc) as *mut _) };
609        (ptr, metadata)
610    }
611
612    #[inline]
613    fn borrowed_from_parts(ptr: NonNull<Self::Pointer>, metadata: &Metadata) -> *const Self {
614        slice_from_raw_parts(ptr.as_ptr(), metadata.len()) as *const _
615    }
616
617    #[inline]
618    fn owned_from_parts(
619        ptr: NonNull<Self::Pointer>,
620        metadata: &Metadata,
621    ) -> <Self as ToOwned>::Owned {
622        match metadata.kind() {
623            Kind::Borrowed => {
624                // SAFETY: We know that it's safe to take and hold a pointer to a reference to
625                // `Self` since `Cow` can only live as long as the input reference does, and an
626                // invalid pointer cannot be taken from a live reference.
627                let data = unsafe { &*Self::borrowed_from_parts(ptr, metadata) };
628                data.to_vec()
629            }
630
631            // SAFETY: We know that the pointer is valid because it could have only been
632            // constructed from a valid `Vec<T>` handed to `Cow::from_owned`, which we
633            // assumed ownership of.
634            Kind::Owned => unsafe {
635                Vec::from_raw_parts(ptr.as_ptr(), metadata.len(), metadata.capacity())
636            },
637
638            Kind::Shared => {
639                // SAFETY: We know that the pointer is valid because it could have only been
640                // constructed from a valid `Arc<[T]>` handed to `Cow::from_shared`, which we
641                // assumed ownership of, also ensuring that the strong count is at least one.
642                let arc = unsafe { Arc::from_raw(Self::borrowed_from_parts(ptr, metadata)) };
643                arc.to_vec()
644            }
645        }
646    }
647
648    #[inline]
649    fn clone_from_parts(
650        ptr: NonNull<Self::Pointer>,
651        metadata: &Metadata,
652    ) -> (NonNull<Self::Pointer>, Metadata) {
653        match metadata.kind() {
654            Kind::Borrowed => (ptr, *metadata),
655            Kind::Owned => {
656                let vec_ptr = Self::borrowed_from_parts(ptr, metadata);
657
658                // SAFETY: We know that the pointer is valid because it could have only been
659                // constructed from a valid `Vec<T>` handed to `Cow::from_owned`, which we assumed
660                // ownership of.
661                let new_vec = unsafe { vec_ptr.as_ref().unwrap().to_vec() };
662
663                Self::owned_into_parts(new_vec)
664            }
665            Kind::Shared => clone_shared::<Self>(ptr, metadata),
666        }
667    }
668
669    #[inline]
670    fn drop_from_parts(ptr: NonNull<Self::Pointer>, metadata: &Metadata) {
671        match metadata.kind() {
672            Kind::Borrowed => {}
673
674            // SAFETY: We know that the pointer is valid because it could have only been constructed
675            // from a valid `Vec<T>` handed to `Cow::from_owned`, which we assumed ownership of.
676            Kind::Owned => unsafe {
677                drop(Vec::from_raw_parts(ptr.as_ptr(), metadata.len(), metadata.capacity()));
678            },
679
680            // SAFETY: We know that the pointer is valid because it could have only been constructed
681            // from a valid `Arc<[T]>` handed to `Cow::from_shared`, which we assumed ownership of,
682            // also ensuring that the strong count is at least one.
683            Kind::Shared => unsafe {
684                drop(Arc::from_raw(Self::borrowed_from_parts(ptr, metadata)));
685            },
686        }
687    }
688}
689
690fn clone_shared<T: Cowable + ?Sized>(
691    ptr: NonNull<T::Pointer>,
692    metadata: &Metadata,
693) -> (NonNull<T::Pointer>, Metadata) {
694    let arc_ptr = T::borrowed_from_parts(ptr, metadata);
695
696    // SAFETY: We know that the pointer is valid because it could have only been
697    // constructed from a valid `Arc<T>` handed to `Cow::from_shared`, which we assumed
698    // ownership of, also ensuring that the strong count is at least one.
699    unsafe {
700        Arc::increment_strong_count(arc_ptr);
701    }
702
703    (ptr, *metadata)
704}