flex_alloc/
borrow.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
//! Support for flexibility over owned or borrowed collections.

use core::{
    borrow::Borrow,
    fmt::{self, Debug, Display},
    ops::Deref,
};

use const_default::ConstDefault;

use crate::alloc::{AllocateIn, Allocator};
use crate::error::StorageError;

/// The owned type for a collection which may be owned or borrowed.
pub type Owned<B, A> = <B as ToOwnedIn<A>>::Owned;

/// Support conversion from borrowed types to owned ones associated with an allocator.
pub trait ToOwnedIn<A: Allocator> {
    /// The owned representation of this type.
    type Owned: Borrow<Self>;

    /// Create an owned copy of this instance in a given allocation target.
    fn to_owned_in<I>(&self, alloc_in: I) -> Self::Owned
    where
        I: AllocateIn<Alloc = A>,
    {
        match self.try_to_owned_in(alloc_in) {
            Ok(inst) => inst,
            Err(err) => err.panic(),
        }
    }

    /// To to create an owned copy of this instance in a given allocation target.
    fn try_to_owned_in<I>(&self, alloc_in: I) -> Result<Self::Owned, StorageError>
    where
        I: AllocateIn<Alloc = A>;
}

impl<T: Clone + 'static, A: Allocator> ToOwnedIn<A> for T {
    type Owned = T;

    fn try_to_owned_in<I>(&self, _alloc_in: I) -> Result<Self::Owned, StorageError>
    where
        I: AllocateIn<Alloc = A>,
    {
        Ok(self.clone())
    }
}

/// Representation of either an owned or borrowed instance of a type.
pub enum Cow<'b, T: ToOwnedIn<A> + ?Sized, A: Allocator> {
    /// The borrowed variant, limited by a lifetime.
    Borrowed(&'b T),

    /// The owned variant.
    Owned(Owned<T, A>),
}

impl<'b, T: ToOwnedIn<A> + ?Sized, A: Allocator> Cow<'b, T, A> {
    /// Determine if this instance is borrowed.
    #[inline]
    pub fn is_borrowed(&self) -> bool {
        matches!(self, Self::Borrowed(_))
    }

    /// Determine if this instance is owned.
    #[inline]
    pub fn is_owned(&self) -> bool {
        matches!(self, Self::Owned(_))
    }

    /// If necessary, convert `self` into an owned instance. Return a mutable reference
    /// to the owned instance.
    #[inline]
    pub fn to_mut(&mut self) -> &mut Owned<T, A>
    where
        A: Default + Allocator,
    {
        self.to_mut_in(A::default())
    }

    /// If necessary, convert `self` into an owned instance given an allocation target.
    /// Return a mutable reference to the owned instance.
    pub fn to_mut_in<I>(&mut self, alloc_in: I) -> &mut Owned<T, A>
    where
        I: AllocateIn<Alloc = A>,
    {
        match *self {
            Self::Borrowed(borrowed) => {
                *self = Self::Owned(borrowed.to_owned_in(alloc_in));
                let Self::Owned(owned) = self else {
                    unreachable!()
                };
                owned
            }
            Self::Owned(ref mut owned) => owned,
        }
    }

    /// If necessary, convert `self` into an owned instance. Unwrap and return the
    /// owned instance.
    pub fn into_owned(self) -> Owned<T, A>
    where
        A: Default + Allocator,
    {
        match self {
            Self::Borrowed(borrowed) => borrowed.to_owned_in(A::default()),
            Self::Owned(owned) => owned,
        }
    }

    /// If necessary, convert `self` into an owned instance given an allocation target.
    /// Unwrap and return the owned instance.
    pub fn into_owned_in<I>(self, alloc_in: I) -> Owned<T, A>
    where
        I: AllocateIn<Alloc = A>,
    {
        match self {
            Self::Borrowed(borrowed) => borrowed.to_owned_in(alloc_in),
            Self::Owned(owned) => owned,
        }
    }

    /// If necessary, try to convert `self` into an owned instance.
    /// Unwrap and return the owned instance or a storage error.
    pub fn try_into_owned(self) -> Result<Owned<T, A>, StorageError>
    where
        A: Default + Allocator,
    {
        match self {
            Self::Borrowed(borrowed) => borrowed.try_to_owned_in(A::default()),
            Self::Owned(owned) => Ok(owned),
        }
    }

    /// If necessary, try to convert `self` into an owned instance given an allocation
    /// target. Unwrap and return the owned instance or a storage error.
    pub fn try_into_owned_in<I>(self, storage: I) -> Result<Owned<T, A>, StorageError>
    where
        I: AllocateIn<Alloc = A>,
    {
        match self {
            Self::Borrowed(borrowed) => borrowed.try_to_owned_in(storage),
            Self::Owned(owned) => Ok(owned),
        }
    }
}

impl<T: ToOwnedIn<A> + ?Sized, A: Allocator> AsRef<T> for Cow<'_, T, A> {
    fn as_ref(&self) -> &T {
        self
    }
}

impl<T: ToOwnedIn<A> + ?Sized, A: Allocator> Borrow<T> for Cow<'_, T, A> {
    fn borrow(&self) -> &T {
        self
    }
}

impl<T: ToOwnedIn<A> + ?Sized, A: Allocator> Clone for Cow<'_, T, A>
where
    Owned<T, A>: Clone,
{
    fn clone(&self) -> Self {
        match self {
            Self::Borrowed(b) => Self::Borrowed(*b),
            Self::Owned(o) => Self::Owned(o.clone()),
        }
    }

    fn clone_from(&mut self, source: &Self) {
        match (self, source) {
            (&mut Self::Owned(ref mut dest), Self::Owned(ref o)) => dest.clone_from(o),
            (t, s) => *t = s.clone(),
        }
    }
}

impl<T, A: Allocator> ConstDefault for Cow<'_, T, A>
where
    T: ToOwnedIn<A> + ?Sized,
    T::Owned: ConstDefault,
{
    const DEFAULT: Self = Self::Owned(T::Owned::DEFAULT);
}

impl<T, A: Allocator> Debug for Cow<'_, T, A>
where
    T: ToOwnedIn<A> + Debug + ?Sized,
    Owned<T, A>: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::Borrowed(b) => Debug::fmt(b, f),
            Self::Owned(ref o) => Debug::fmt(o, f),
        }
    }
}

impl<T, A: Allocator> Display for Cow<'_, T, A>
where
    T: ToOwnedIn<A> + Display + ?Sized,
    Owned<T, A>: Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::Borrowed(ref b) => Display::fmt(b, f),
            Self::Owned(ref o) => Display::fmt(o, f),
        }
    }
}

impl<T: ToOwnedIn<A> + ?Sized, A: Allocator> Deref for Cow<'_, T, A> {
    type Target = T;

    fn deref(&self) -> &T {
        match *self {
            Self::Borrowed(borrowed) => borrowed,
            Self::Owned(ref owned) => owned.borrow(),
        }
    }
}

impl<T: ToOwnedIn<A> + ?Sized, A: Allocator> Default for Cow<'_, T, A>
where
    Owned<T, A>: Default,
{
    #[inline]
    fn default() -> Self {
        Self::Owned(Default::default())
    }
}

impl<'b, T: ToOwnedIn<A> + ?Sized, A: Allocator> From<&'b T> for Cow<'b, T, A> {
    #[inline]
    fn from(borrow: &'b T) -> Self {
        Self::Borrowed(borrow)
    }
}

impl<'b, T: ToOwnedIn<A> + ?Sized, A: Allocator> From<&'b mut T> for Cow<'b, T, A> {
    #[inline]
    fn from(borrow: &'b mut T) -> Self {
        Self::Borrowed(borrow)
    }
}

impl<'a, 'b, T: ToOwnedIn<A> + ?Sized, A: Allocator, U: ToOwnedIn<B> + ?Sized, B: Allocator>
    PartialEq<Cow<'b, U, B>> for Cow<'a, T, A>
where
    T: PartialEq<U>,
{
    #[inline]
    fn eq(&self, other: &Cow<'b, U, B>) -> bool {
        self.deref().eq(other.deref())
    }
}

impl<'a, T: ToOwnedIn<A> + Eq + ?Sized, A: Allocator> Eq for Cow<'a, T, A> {}