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
//! Smart pointers owning their targets

use std::ops::Deref;

/// Smart pointer to owned inner value
/// (see [`deref`](Owned::deref) implementation)
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Owned<X>(pub X);

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

/// Smart pointer to value pointed-to by owned inner value
/// (see [`deref`](OwnedPointer::deref) implementation)
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct OwnedPointer<X>(pub X);

impl<X: Deref> Deref for OwnedPointer<X> {
    type Target = <X as Deref>::Target;
    /// Returns a reference to the value referenced by the contained value
    /// (double indirection)
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Pointer types that can be converted into an owned type
pub trait PointerIntoOwned: Sized {
    /// The type the pointer can be converted into
    type Owned;
    /// Convert into owned type
    fn into_owned(self) -> Self::Owned;
}

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

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

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