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
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
extern crate std as alloc;
#[cfg(not(feature = "std"))]
extern crate alloc;
use alloc::borrow::{Cow, ToOwned};
use core::borrow::{Borrow, BorrowMut};
pub trait AsIs: Sized {
type Is: ?Sized + ToOwned;
fn as_is<'a>(self) -> Is<'a, Self::Is>
where
Self: 'a;
fn copy_or_borrow<'a>(&'a self) -> Is<'a, Self::Is>
where
Self: 'a;
fn into_is_cow<'a>(self) -> IsCow<'a, Self::Is>
where
Self: 'a,
{
match self.as_is() {
Is::Owned(x) => IsCow::Owned(x),
Is::MutBorrowed(x) => IsCow::Borrowed((*x).borrow()),
Is::Borrowed(x) => IsCow::Borrowed(x),
}
}
fn into_is_mut<'a>(self) -> IsMut<'a, Self::Is>
where
Self: 'a,
{
match self.as_is() {
Is::Owned(x) => IsMut::Owned(x),
Is::MutBorrowed(x) => IsMut::MutBorrowed(x),
Is::Borrowed(x) => IsMut::Owned(x.to_owned()),
}
}
fn into_owned(self) -> Owned<Self> {
match self.as_is() {
Is::Owned(x) => x,
Is::MutBorrowed(x) => (*x).borrow().to_owned(),
Is::Borrowed(x) => x.to_owned(),
}
}
fn into_cow<'a>(self) -> Cow<'a, Self::Is>
where
Self: 'a,
{
match self.as_is() {
Is::Owned(x) => Cow::Owned(x),
Is::MutBorrowed(x) => Cow::Borrowed((*x).borrow()),
Is::Borrowed(x) => Cow::Borrowed(x),
}
}
}
pub trait AsIsMut: AsIs {}
mod impl_as_is_foreign;
mod is;
pub use is::Is;
mod is_cow;
pub use is_cow::IsCow;
mod is_mut;
pub use is_mut::IsMut;
pub type Owned<T> = <<T as AsIs>::Is as ToOwned>::Owned;
impl<T: ?Sized> AsIs for &T
where
T: ToOwned + Borrow<<T::Owned as AsIs>::Is>,
T::Owned: AsIs,
<T::Owned as AsIs>::Is: ToOwned<Owned = T::Owned>,
{
type Is = <T::Owned as AsIs>::Is;
fn as_is<'a>(self) -> Is<'a, Self::Is>
where
Self: 'a,
{
Is::Borrowed(self.borrow())
}
fn copy_or_borrow<'a>(&'a self) -> Is<'a, Self::Is>
where
Self: 'a,
{
Is::Borrowed((**self).borrow())
}
}
impl<T: ?Sized> AsIs for &mut T
where
T: ToOwned + Borrow<<T::Owned as AsIs>::Is> + BorrowMut<T::Owned>,
T::Owned: AsIs,
<T::Owned as AsIs>::Is: ToOwned<Owned = T::Owned>,
{
type Is = <T::Owned as AsIs>::Is;
fn as_is<'a>(self) -> Is<'a, Self::Is>
where
Self: 'a,
{
Is::MutBorrowed(self.borrow_mut())
}
fn copy_or_borrow<'a>(&'a self) -> Is<'a, Self::Is>
where
Self: 'a,
{
Is::Borrowed((**self).borrow())
}
}
impl<T: ?Sized> AsIsMut for &mut T where Self: AsIs {}