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
//! Smart pointer owning its pointee and generalization of [`std::borrow::Cow`]
//!
//! `deref_owned` provides a smart pointer [`Owned`], which points to a value
//! that can be borrowed from an owned inner value.
//! It's similar to [`Cow`], except that it's always owning a value.
//!
//! Moreover, a trait [`GenericCow`] is provided, which allows conversion from
//! certain pointers into an owned value though an
//! [`.into_owned()`](GenericCow::into_owned) method. The trait `GenericCow` is
//! implemented for:
//!
//! * `&'a B where B: ToOwned`
//! * `Cow<'a, B> where B: ToOwned`
//! * `Owned<'a, B, O> where O: Borrow<B>`
//!
//! Here
//!
//! * `B: ?Sized` is the borrowed type (and also the type of the
//!   [pointer target](Deref::Target)) and
//! * `O: Borrow<B>` is an owned type.

use std::borrow::{Borrow, Cow};
use std::fmt;
use std::marker::PhantomData;
use std::ops::Deref;

/// Smart pointer to value that can be borrowed from owned inner value
#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Owned<B, O>
where
    B: ?Sized,
{
    pub borrowed: PhantomData<*const B>,
    pub owned: O,
}

impl<B, O> Owned<B, O>
where
    B: ?Sized,
{
    pub const fn new(owned: O) -> Self {
        Owned {
            borrowed: PhantomData,
            owned,
        }
    }
}

impl<B, O> Deref for Owned<B, O>
where
    B: ?Sized,
    O: Borrow<B>,
{
    type Target = B;
    fn deref(&self) -> &Self::Target {
        self.owned.borrow()
    }
}

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

impl<B, O, T> AsRef<T> for Owned<B, O>
where
    B: ?Sized,
    O: AsRef<T>,
{
    fn as_ref(&self) -> &T {
        self.owned.as_ref()
    }
}

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

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

/// Pointer types that can be converted into an owned type
pub trait GenericCow: Deref + Sized {
    /// The type the pointer can be converted into
    type Owned: Borrow<<Self as Deref>::Target>;
    /// Convert into owned type
    fn into_owned(self) -> Self::Owned;
}

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

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

impl<B, O> GenericCow for Owned<B, O>
where
    B: ?Sized,
    O: Borrow<B>,
{
    type Owned = O;
    fn into_owned(self) -> Self::Owned {
        self.owned
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::borrow::Cow;
    #[test]
    fn test_owned() {
        let smart: Owned<str, _> = Owned::new("Alpha".to_string());
        let reference: &str = &*smart;
        assert_eq!(reference, "Alpha");
        let owned: String = smart.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 smart: Owned<[i32], _> = Owned::new(vec![1, 2, 3]);
        assert_eq!(&*smart, &[1, 2, 3] as &[i32]);
        assert_eq!(GenericCow::into_owned(smart), vec![1, 2, 3]);
    }
    #[test]
    fn test_boxed_slice() {
        let smart: Owned<[i32], _> = Owned::new(vec![1, 2, 3].into_boxed_slice());
        assert_eq!(&*smart, &[1, 2, 3] as &[i32]);
        assert_eq!(
            GenericCow::into_owned(smart),
            vec![1, 2, 3].into_boxed_slice()
        );
    }
    #[test]
    fn test_generic_fn() {
        fn generic_fn(arg: impl Deref<Target = str> + GenericCow<Owned = String>) {
            let reference: &str = &*arg;
            assert_eq!(reference, "Echo");
            let owned: String = arg.into_owned();
            assert_eq!(owned, "Echo".to_string());
        }
        generic_fn(Owned::<str, _>::new("Echo".to_string()));
        generic_fn(Cow::Owned("Echo".to_string()));
        generic_fn(Cow::Borrowed("Echo"));
        generic_fn("Echo");
    }
}