nu_utils/
shared_cow.rs

1use serde::{Deserialize, Serialize};
2use std::{fmt, ops, sync::Arc};
3
4/// A container that transparently shares a value when possible, but clones on mutate.
5///
6/// Unlike `Arc`, this is only intended to help save memory usage and reduce the amount of effort
7/// required to clone unmodified values with easy to use copy-on-write.
8///
9/// This should more or less reflect the API of [`std::borrow::Cow`] as much as is sensible.
10#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
11#[repr(transparent)]
12pub struct SharedCow<T: Clone>(Arc<T>);
13
14impl<T: Clone> SharedCow<T> {
15    /// Create a new `Shared` value.
16    pub fn new(value: T) -> SharedCow<T> {
17        SharedCow(Arc::new(value))
18    }
19
20    /// Take an exclusive clone of the shared value, or move and take ownership if it wasn't shared.
21    pub fn into_owned(self: SharedCow<T>) -> T {
22        // Optimized: if the Arc is not shared, just unwraps the Arc
23        match Arc::try_unwrap(self.0) {
24            Ok(value) => value,
25            Err(arc) => (*arc).clone(),
26        }
27    }
28
29    /// Get a mutable reference to the value inside the [`SharedCow`]. This will result in a clone
30    /// being created only if the value was shared with multiple references.
31    pub fn to_mut(&mut self) -> &mut T {
32        Arc::make_mut(&mut self.0)
33    }
34
35    /// Convert the `Shared` value into an `Arc`
36    pub fn into_arc(value: SharedCow<T>) -> Arc<T> {
37        value.0
38    }
39
40    /// Return the number of references to the shared value.
41    pub fn ref_count(value: &SharedCow<T>) -> usize {
42        Arc::strong_count(&value.0)
43    }
44}
45
46impl<T> From<T> for SharedCow<T>
47where
48    T: Clone,
49{
50    fn from(value: T) -> Self {
51        SharedCow::new(value)
52    }
53}
54
55impl<T> From<Arc<T>> for SharedCow<T>
56where
57    T: Clone,
58{
59    fn from(value: Arc<T>) -> Self {
60        SharedCow(value)
61    }
62}
63
64impl<T> fmt::Debug for SharedCow<T>
65where
66    T: fmt::Debug + Clone,
67{
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        // Appears transparent
70        (*self.0).fmt(f)
71    }
72}
73
74impl<T> fmt::Display for SharedCow<T>
75where
76    T: fmt::Display + Clone,
77{
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        (*self.0).fmt(f)
80    }
81}
82
83impl<T: Clone> Serialize for SharedCow<T>
84where
85    T: Serialize,
86{
87    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
88    where
89        S: serde::Serializer,
90    {
91        self.0.serialize(serializer)
92    }
93}
94
95impl<'de, T: Clone> Deserialize<'de> for SharedCow<T>
96where
97    T: Deserialize<'de>,
98{
99    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
100    where
101        D: serde::Deserializer<'de>,
102    {
103        T::deserialize(deserializer).map(Arc::new).map(SharedCow)
104    }
105}
106
107impl<T: Clone> ops::Deref for SharedCow<T> {
108    type Target = T;
109
110    fn deref(&self) -> &Self::Target {
111        &self.0
112    }
113}