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
//! Generalization of [`std::borrow::Cow`]
//!
//! `deref_owned` provides a wrapper [`Owned<B>`](Owned) which stores an inner
//! value of type [`<B as ToOwned>::Owned`](ToOwned::Owned) and points to a
//! value of type `B` by implementing [`Deref<Target = B>`](Deref) through
//! [`Borrow::borrow`].
//!
//! `Owned` is similar to [`Cow`], except that it's always owning a value. This
//! can be used to avoid runtime overhead in certain scenarios.
//!
//! Moreover, a trait [`GenericCow`] is provided, which allows conversion from
//! certain types into an owned type through an
//! [`.into_owned()`](GenericCow::into_owned) method. The trait can be seen as
//! a generalization of `Cow<'_, B>` and is implemented for:
//!
//! * [`&'a B`](prim@reference)
//! * [`Cow<'a, B>`](Cow)
//! * [`Owned<B>`](Owned)
//!
//! # Example
//!
//! ```
//! use deref_owned::{GenericCow, Owned};
//! use std::borrow::{Borrow, Cow};
//!
//! fn generic_fn(arg: impl GenericCow<Borrowed = str>) {
//!     let reference: &str = &*arg; // or: arg.borrow()
//!     assert_eq!(reference, "Hello");
//!     let owned: String = arg.into_owned();
//!     assert_eq!(owned, "Hello".to_string());
//! }
//!
//! generic_fn(Owned("Hello".to_string()));
//! generic_fn(Cow::Owned("Hello".to_string()));
//! generic_fn(Cow::Borrowed("Hello"));
//! generic_fn("Hello");
//! ```

use std::borrow::{Borrow, Cow};
use std::cmp;
use std::fmt;
use std::hash;
use std::ops::Deref;

/// Wrapper holding an owned value of type
/// [`<B as ToOwned>::Owned`](ToOwned::Owned) and implementing
/// [`Deref<Target = B>`](Deref)
pub struct Owned<B>(pub <B as ToOwned>::Owned)
where
    B: ?Sized + ToOwned;

impl<B> Clone for Owned<B>
where
    B: ?Sized + ToOwned,
    <B as ToOwned>::Owned: Clone,
{
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
    fn clone_from(&mut self, source: &Self) {
        self.0 = source.0.clone();
    }
}

impl<B> Default for Owned<B>
where
    B: ?Sized + ToOwned,
    <B as ToOwned>::Owned: Default,
{
    fn default() -> Self {
        Self(Default::default())
    }
}

impl<B, C> PartialEq<Owned<C>> for Owned<B>
where
    B: ?Sized + ToOwned,
    C: ?Sized + ToOwned,
    <B as ToOwned>::Owned: PartialEq<<C as ToOwned>::Owned>,
{
    fn eq(&self, other: &Owned<C>) -> bool {
        self.0.eq(&other.0)
    }
    fn ne(&self, other: &Owned<C>) -> bool {
        self.0.ne(&other.0)
    }
}

impl<B> Eq for Owned<B>
where
    B: ?Sized + ToOwned,
    <B as ToOwned>::Owned: Eq,
{
}

impl<B, C> cmp::PartialOrd<Owned<C>> for Owned<B>
where
    B: ?Sized + ToOwned,
    C: ?Sized + ToOwned,
    <B as ToOwned>::Owned: cmp::PartialOrd<<C as ToOwned>::Owned>,
{
    fn partial_cmp(&self, other: &Owned<C>) -> Option<cmp::Ordering> {
        self.0.partial_cmp(&other.0)
    }
    fn lt(&self, other: &Owned<C>) -> bool {
        self.0.lt(&other.0)
    }
    fn le(&self, other: &Owned<C>) -> bool {
        self.0.le(&other.0)
    }
    fn gt(&self, other: &Owned<C>) -> bool {
        self.0.gt(&other.0)
    }
    fn ge(&self, other: &Owned<C>) -> bool {
        self.0.ge(&other.0)
    }
}

impl<B> cmp::Ord for Owned<B>
where
    B: ?Sized + ToOwned,
    <B as ToOwned>::Owned: cmp::Ord,
{
    fn cmp(&self, other: &Owned<B>) -> cmp::Ordering {
        self.0.cmp(&other.0)
    }
}

impl<B> hash::Hash for Owned<B>
where
    B: ?Sized + ToOwned,
    <B as ToOwned>::Owned: hash::Hash,
{
    fn hash<H>(&self, state: &mut H)
    where
        H: hash::Hasher,
    {
        self.0.hash(state)
    }
}

impl<B> Deref for Owned<B>
where
    B: ?Sized + ToOwned,
{
    type Target = B;
    fn deref(&self) -> &B {
        self.0.borrow()
    }
}

impl<B> Borrow<B> for Owned<B>
where
    B: ?Sized + ToOwned,
{
    fn borrow(&self) -> &B {
        self.0.borrow()
    }
}

impl<B, U> AsRef<U> for Owned<B>
where
    B: ?Sized + ToOwned,
    <B as ToOwned>::Owned: AsRef<U>,
    U: ?Sized,
{
    fn as_ref(&self) -> &U {
        self.0.as_ref()
    }
}

impl<B: fmt::Display> fmt::Display for Owned<B>
where
    B: ?Sized + ToOwned,
    <B as ToOwned>::Owned: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl<B: fmt::Debug> fmt::Debug for Owned<B>
where
    B: ?Sized + ToOwned,
    <B as ToOwned>::Owned: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

/// Generalized [`Cow`]
///
/// `impl GenericCow<Borrowed = B>` is a generalization of:
///
/// * [`&'a B`](prim@reference)
/// * [`Cow<'a, B>`](Cow)
/// * [`Owned<B>`](Owned)
pub trait GenericCow
where
    Self: Sized,
    Self: Deref<Target = Self::Borrowed>,
    Self: Borrow<Self::Borrowed>,
{
    /// Borrowed type
    type Borrowed: ?Sized + ToOwned;
    /// Convert into owned type
    fn into_owned(self) -> <Self::Borrowed as ToOwned>::Owned;
}

impl<'a, B> GenericCow for &'a B
where
    B: ?Sized + ToOwned,
{
    type Borrowed = B;
    fn into_owned(self) -> <Self::Borrowed as ToOwned>::Owned {
        self.to_owned()
    }
}

impl<'a, B> GenericCow for Cow<'a, B>
where
    B: ?Sized + ToOwned,
{
    type Borrowed = B;
    fn into_owned(self) -> <B as ToOwned>::Owned {
        Cow::into_owned(self)
    }
}

impl<B> GenericCow for Owned<B>
where
    B: ?Sized + ToOwned,
{
    type Borrowed = B;
    fn into_owned(self) -> <B as ToOwned>::Owned {
        self.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::borrow::Cow;
    #[test]
    fn test_owned() {
        let wrapped: Owned<str> = Owned("Alpha".to_string());
        let reference: &str = &*wrapped;
        assert_eq!(reference, "Alpha");
        let owned: String = wrapped.into_owned();
        assert_eq!(owned, "Alpha".to_string());
    }
    #[test]
    fn test_cow() {
        let cow_owned: Cow<'static, str> = Cow::Owned("Bravo".to_string());
        assert_eq!(GenericCow::into_owned(cow_owned), "Bravo".to_string());
        let cow_borrowed: Cow<'static, str> = Cow::Borrowed("Charlie");
        assert_eq!(GenericCow::into_owned(cow_borrowed), "Charlie".to_string());
    }
    #[test]
    fn test_ref() {
        let reference: &str = "Delta";
        assert_eq!(GenericCow::into_owned(reference), "Delta".to_string());
    }
    #[test]
    fn test_vec() {
        let wrapped: Owned<[i32]> = Owned(vec![1, 2, 3]);
        assert_eq!(&*wrapped, &[1, 2, 3] as &[i32]);
        assert_eq!(wrapped.into_owned(), vec![1, 2, 3]);
    }
    #[test]
    fn test_generic_fn() {
        fn generic_fn(arg: impl GenericCow<Borrowed = str>) {
            let reference1: &str = &*arg;
            assert_eq!(reference1, "Echo");
            let reference2: &str = arg.borrow();
            assert_eq!(reference2, "Echo");
            let owned: String = arg.into_owned();
            assert_eq!(owned, "Echo".to_string());
        }
        generic_fn(Owned("Echo".to_string()));
        generic_fn(Cow::Owned("Echo".to_string()));
        generic_fn(Cow::Borrowed("Echo"));
        generic_fn("Echo");
    }
    #[test]
    fn test_vec_borrow() {
        let wrapped: Owned<[i32]> = Owned(vec![2, 7, 4]);
        let slice_ref: &[i32] = wrapped.borrow();
        assert_eq!(slice_ref, &[2, 7, 4] as &[i32]);
    }
    #[test]
    fn test_int_borrow() {
        let wrapped: Owned<i32> = Owned(5);
        let reference: &i32 = wrapped.borrow();
        assert_eq!(reference, &5);
    }
}