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
//! Generalization of [`std::borrow::Cow`]
//!
//! `deref_owned` provides a wrapper [`Owned`] which holds an inner value and
//! points to it by implementing [`Deref`]. `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<B: ?Sized + ToOwned>: Borrow<B>`](GenericCow)
//! is provided, which allows conversion from certain types into an owned type
//! [`<B as ToOwned>::Owned`](ToOwned::Owned) 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`
//! * `Cow<'a, B>`
//! * `Owned<<B as ToOwned>::Owned>`
//!
//! # Example
//!
//! ```
//! use deref_owned::{GenericCow, Owned};
//! use std::borrow::{Borrow, Cow};
//!
//! fn generic_fn(arg: impl GenericCow<str>) {
//!     let reference: &str = 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::fmt;
use std::ops::Deref;

/// Wrapper holding an owned value of type `T` and implementing
/// [`Deref<Target = T>`](Deref)
#[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) -> &T {
        &self.0
    }
}

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

impl<T> AsRef<T> for Owned<T> {
    fn as_ref(&self) -> &T {
        &self.0
    }
}

impl<T> From<T> for Owned<T> {
    fn from(inner: T) -> Self {
        Self(inner)
    }
}

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)
    }
}

/// Types which implement [`Borrow<B>`](Borrow) and can be converted into
/// [`<B as ToOwned>::Owned`](ToOwned::Owned)
pub trait GenericCow<B>: Sized + Borrow<B>
where
    B: ?Sized + ToOwned,
{
    /// Convert into owned type
    fn into_owned(self) -> <B as ToOwned>::Owned;
}

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

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

impl<B> GenericCow<B> for Owned<<B as ToOwned>::Owned>
where
    B: ?Sized + ToOwned,
{
    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<String> = Owned("Alpha".to_string());
        let reference: &str = &*wrapped;
        assert_eq!(reference, "Alpha");
        let owned: String = GenericCow::<str>::into_owned(wrapped);
        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<Vec<i32>> = Owned(vec![1, 2, 3]);
        assert_eq!(&*wrapped, &[1, 2, 3] as &[i32]);
        assert_eq!(GenericCow::<[i32]>::into_owned(wrapped), vec![1, 2, 3]);
    }
    #[test]
    fn test_generic_fn() {
        fn generic_fn(arg: impl GenericCow<str>) {
            let reference: &str = arg.borrow();
            assert_eq!(reference, "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_as_ref() {
        let wrapped: Owned<Vec<i32>> = Owned(vec![2, 7, 4]);
        let vec_ref: &Vec<i32> = wrapped.as_ref();
        assert_eq!(vec_ref, &vec![2, 7, 4]);
        let slice_ref: &[i32] = wrapped.as_ref();
        assert_eq!(slice_ref, &[2, 7, 4] as &[i32]);
    }
    #[test]
    fn test_int_as_ref() {
        let wrapped: Owned<i32> = Owned(5);
        let reference: &i32 = wrapped.as_ref();
        assert_eq!(reference, &5);
    }
}