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
//! 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
//! implemented for:
//!
//! * `&'a T where T: ?Sized + ToOwned`
//! * `Cow<'a, T> where T: ?Sized + ToOwned`
//! * `Owned<T>`

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

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

impl<T> Deref for Owned<T> {
    type Target = T;
    /// Returns a reference to the contained value
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for Owned<T> {
    /// Returns a mutable reference to the contained value
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Pointer types that can be converted into an owned type
pub trait IntoOwned: Sized {
    /// The type the pointer can be converted into
    type Owned;
    /// 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
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::borrow::Cow;
    #[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");
    }
}