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
use std::borrow::Cow;
use std::ops::{Deref, DerefMut};
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
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
}
}
pub trait IntoOwned: Sized {
type Owned;
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");
}
}