]> git.proxmox.com Git - rustc.git/blob - src/libcollections/borrow.rs
Imported Upstream version 1.6.0+dfsg1
[rustc.git] / src / libcollections / borrow.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A module for working with borrowed data.
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use core::clone::Clone;
16 use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
17 use core::convert::AsRef;
18 use core::hash::{Hash, Hasher};
19 use core::marker::Sized;
20 use core::ops::Deref;
21 use core::option::Option;
22
23 use fmt;
24
25 use self::Cow::*;
26
27 #[stable(feature = "rust1", since = "1.0.0")]
28 pub use core::borrow::{Borrow, BorrowMut};
29
30 #[stable(feature = "rust1", since = "1.0.0")]
31 impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
32 where B: ToOwned,
33 <B as ToOwned>::Owned: 'a
34 {
35 fn borrow(&self) -> &B {
36 &**self
37 }
38 }
39
40 /// A generalization of `Clone` to borrowed data.
41 ///
42 /// Some types make it possible to go from borrowed to owned, usually by
43 /// implementing the `Clone` trait. But `Clone` works only for going from `&T`
44 /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
45 /// from any borrow of a given type.
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub trait ToOwned {
48 #[stable(feature = "rust1", since = "1.0.0")]
49 type Owned: Borrow<Self>;
50
51 /// Creates owned data from borrowed data, usually by cloning.
52 #[stable(feature = "rust1", since = "1.0.0")]
53 fn to_owned(&self) -> Self::Owned;
54 }
55
56 #[stable(feature = "rust1", since = "1.0.0")]
57 impl<T> ToOwned for T where T: Clone {
58 type Owned = T;
59 fn to_owned(&self) -> T {
60 self.clone()
61 }
62 }
63
64 /// A clone-on-write smart pointer.
65 ///
66 /// The type `Cow` is a smart pointer providing clone-on-write functionality: it
67 /// can enclose and provide immutable access to borrowed data, and clone the
68 /// data lazily when mutation or ownership is required. The type is designed to
69 /// work with general borrowed data via the `Borrow` trait.
70 ///
71 /// `Cow` implements `Deref`, which means that you can call
72 /// non-mutating methods directly on the data it encloses. If mutation
73 /// is desired, `to_mut` will obtain a mutable reference to an owned
74 /// value, cloning if necessary.
75 ///
76 /// # Examples
77 ///
78 /// ```
79 /// use std::borrow::Cow;
80 ///
81 /// # #[allow(dead_code)]
82 /// fn abs_all(input: &mut Cow<[i32]>) {
83 /// for i in 0..input.len() {
84 /// let v = input[i];
85 /// if v < 0 {
86 /// // clones into a vector the first time (if not already owned)
87 /// input.to_mut()[i] = -v;
88 /// }
89 /// }
90 /// }
91 /// ```
92 #[stable(feature = "rust1", since = "1.0.0")]
93 pub enum Cow<'a, B: ?Sized + 'a>
94 where B: ToOwned
95 {
96 /// Borrowed data.
97 #[stable(feature = "rust1", since = "1.0.0")]
98 Borrowed(&'a B),
99
100 /// Owned data.
101 #[stable(feature = "rust1", since = "1.0.0")]
102 Owned(<B as ToOwned>::Owned),
103 }
104
105 #[stable(feature = "rust1", since = "1.0.0")]
106 impl<'a, B: ?Sized> Clone for Cow<'a, B> where B: ToOwned {
107 fn clone(&self) -> Cow<'a, B> {
108 match *self {
109 Borrowed(b) => Borrowed(b),
110 Owned(ref o) => {
111 let b: &B = o.borrow();
112 Owned(b.to_owned())
113 }
114 }
115 }
116 }
117
118 impl<'a, B: ?Sized> Cow<'a, B> where B: ToOwned {
119 /// Acquires a mutable reference to the owned form of the data.
120 ///
121 /// Clones the data if it is not already owned.
122 ///
123 /// # Examples
124 ///
125 /// ```
126 /// use std::borrow::Cow;
127 ///
128 /// let mut cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]);
129 ///
130 /// let hello = cow.to_mut();
131 ///
132 /// assert_eq!(hello, &[1, 2, 3]);
133 /// ```
134 #[stable(feature = "rust1", since = "1.0.0")]
135 pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
136 match *self {
137 Borrowed(borrowed) => {
138 *self = Owned(borrowed.to_owned());
139 self.to_mut()
140 }
141 Owned(ref mut owned) => owned,
142 }
143 }
144
145 /// Extracts the owned data.
146 ///
147 /// Clones the data if it is not already owned.
148 ///
149 /// # Examples
150 ///
151 /// ```
152 /// use std::borrow::Cow;
153 ///
154 /// let cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]);
155 ///
156 /// let hello = cow.into_owned();
157 ///
158 /// assert_eq!(vec![1, 2, 3], hello);
159 /// ```
160 #[stable(feature = "rust1", since = "1.0.0")]
161 pub fn into_owned(self) -> <B as ToOwned>::Owned {
162 match self {
163 Borrowed(borrowed) => borrowed.to_owned(),
164 Owned(owned) => owned,
165 }
166 }
167 }
168
169 #[stable(feature = "rust1", since = "1.0.0")]
170 impl<'a, B: ?Sized> Deref for Cow<'a, B> where B: ToOwned {
171 type Target = B;
172
173 fn deref(&self) -> &B {
174 match *self {
175 Borrowed(borrowed) => borrowed,
176 Owned(ref owned) => owned.borrow(),
177 }
178 }
179 }
180
181 #[stable(feature = "rust1", since = "1.0.0")]
182 impl<'a, B: ?Sized> Eq for Cow<'a, B> where B: Eq + ToOwned {}
183
184 #[stable(feature = "rust1", since = "1.0.0")]
185 impl<'a, B: ?Sized> Ord for Cow<'a, B> where B: Ord + ToOwned {
186 #[inline]
187 fn cmp(&self, other: &Cow<'a, B>) -> Ordering {
188 Ord::cmp(&**self, &**other)
189 }
190 }
191
192 #[stable(feature = "rust1", since = "1.0.0")]
193 impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
194 where B: PartialEq<C> + ToOwned,
195 C: ToOwned
196 {
197 #[inline]
198 fn eq(&self, other: &Cow<'b, C>) -> bool {
199 PartialEq::eq(&**self, &**other)
200 }
201 }
202
203 #[stable(feature = "rust1", since = "1.0.0")]
204 impl<'a, B: ?Sized> PartialOrd for Cow<'a, B> where B: PartialOrd + ToOwned {
205 #[inline]
206 fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
207 PartialOrd::partial_cmp(&**self, &**other)
208 }
209 }
210
211 #[stable(feature = "rust1", since = "1.0.0")]
212 impl<'a, B: ?Sized> fmt::Debug for Cow<'a, B>
213 where B: fmt::Debug + ToOwned,
214 <B as ToOwned>::Owned: fmt::Debug
215 {
216 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
217 match *self {
218 Borrowed(ref b) => fmt::Debug::fmt(b, f),
219 Owned(ref o) => fmt::Debug::fmt(o, f),
220 }
221 }
222 }
223
224 #[stable(feature = "rust1", since = "1.0.0")]
225 impl<'a, B: ?Sized> fmt::Display for Cow<'a, B>
226 where B: fmt::Display + ToOwned,
227 <B as ToOwned>::Owned: fmt::Display
228 {
229 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
230 match *self {
231 Borrowed(ref b) => fmt::Display::fmt(b, f),
232 Owned(ref o) => fmt::Display::fmt(o, f),
233 }
234 }
235 }
236
237 #[stable(feature = "rust1", since = "1.0.0")]
238 impl<'a, B: ?Sized> Hash for Cow<'a, B> where B: Hash + ToOwned {
239 #[inline]
240 fn hash<H: Hasher>(&self, state: &mut H) {
241 Hash::hash(&**self, state)
242 }
243 }
244
245 /// Trait for moving into a `Cow`.
246 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`",
247 issue = "27735")]
248 pub trait IntoCow<'a, B: ?Sized> where B: ToOwned {
249 /// Moves `self` into `Cow`
250 fn into_cow(self) -> Cow<'a, B>;
251 }
252
253 #[stable(feature = "rust1", since = "1.0.0")]
254 impl<'a, B: ?Sized> IntoCow<'a, B> for Cow<'a, B> where B: ToOwned {
255 fn into_cow(self) -> Cow<'a, B> {
256 self
257 }
258 }
259
260 #[stable(feature = "rust1", since = "1.0.0")]
261 impl<'a, T: ?Sized + ToOwned> AsRef<T> for Cow<'a, T> {
262 fn as_ref(&self) -> &T {
263 self
264 }
265 }