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
//! Smart pointer owning its pointee and trait which allows conversion into
//! owned type
//!
//! `deref_owned` provides a smart pointer [`Owned`], which points to an owned
//! value. It's similar to [`Cow`], except that it's always owning its pointee.
//! Moreover, a trait [`IntoOwned`] is provided, which allows conversion of
//! pointers to an owned value though an
//! [`.into_owned()`](IntoOwned::into_owned) method. The trait `IntoOwned` is
//! currently implemented for:
//!
//! * `&'a T where T: ?Sized + ToOwned`
//! * `Cow<'a, T> where T: ?Sized + ToOwned`
//! * `Owned<T>`
//! * `Box<T> where T: ?Sized`
//! * `Vec<T>`
//! * `String`

use std::borrow::{Borrow, BorrowMut, Cow};
use std::fmt;
use std::ops::{Deref, DerefMut};

/// Smart pointer to owned inner value
#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Owned<T>(pub T);

impl<T> Deref for Owned<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Owned<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

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

impl<T, U> AsMut<U> for Owned<T>
where
    T: AsMut<U>,
    U: ?Sized,
{
    fn as_mut(&mut self) -> &mut U {
        self.0.as_mut()
    }
}

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

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

impl<T: fmt::Display> fmt::Display for Owned<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl<T: fmt::Debug> fmt::Debug for Owned<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

/// Pointer types that can be converted into an owned type
pub trait IntoOwned: Sized + Deref {
    /// 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, T> IntoOwned for &'a T
where
    T: ?Sized + ToOwned,
{
    type Owned = <T as ToOwned>::Owned;
    fn into_owned(self) -> Self::Owned {
        self.to_owned()
    }
}

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

impl<T> IntoOwned for Owned<T> {
    type Owned = T;
    fn into_owned(self) -> Self::Owned {
        self.0
    }
}

impl<T: ?Sized> IntoOwned for Box<T> {
    type Owned = Self;
    fn into_owned(self) -> Self::Owned {
        self
    }
}

impl<T> IntoOwned for Vec<T> {
    type Owned = Self;
    fn into_owned(self) -> Self::Owned {
        self
    }
}

impl IntoOwned for String {
    type Owned = Self;
    fn into_owned(self) -> Self::Owned {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::borrow::Cow;
    #[test]
    fn test_string() {
        let string: String = "S".to_string();
        let reference: &str = &*string;
        assert_eq!(reference, &"S".to_string());
        let owned: String = string.into_owned();
        assert_eq!(owned, "S".to_string());
    }
    #[test]
    fn test_owned() {
        let smart = Owned("Alpha".to_string());
        let reference: &String = &*smart;
        assert_eq!(reference, &"Alpha".to_string());
        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!(IntoOwned::into_owned(cow_owned), "Bravo".to_string());
        let cow_borrowed: Cow<'static, str> = Cow::Borrowed("Charlie");
        assert_eq!(IntoOwned::into_owned(cow_borrowed), "Charlie".to_string());
    }
    #[test]
    fn test_ref() {
        let reference: &str = "Delta";
        assert_eq!(IntoOwned::into_owned(reference), "Delta".to_string());
    }
    #[test]
    fn test_boxed_slice() {
        let boxed_slice: Box<[i32]> = Box::new([1, 2, 3]);
        assert_eq!(
            IntoOwned::into_owned(boxed_slice),
            Box::new([1, 2, 3]) as Box<[i32]>
        );
    }
    #[test]
    fn test_generic_fn() {
        fn generic_fn(arg: impl IntoOwned<Owned = String> + Borrow<str>) {
            let borrowed: &str = arg.borrow();
            assert_eq!(borrowed, "Echo");
            let owned: String = arg.into_owned();
            assert_eq!(owned, "Echo".to_string());
        }
        generic_fn("Echo".to_string());
        generic_fn(Owned("Echo".to_string()));
        generic_fn(Cow::Owned("Echo".to_string()));
        generic_fn(Cow::Borrowed("Echo"));
        generic_fn("Echo");
    }
}