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.
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.
11 //! A module for working with borrowed data.
13 #![stable(feature = "rust1", since = "1.0.0")]
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
;
21 use core
::option
::Option
;
24 use alloc
::{boxed, rc, arc}
;
28 /// A trait for borrowing data.
30 /// In general, there may be several ways to "borrow" a piece of data. The
31 /// typical ways of borrowing a type `T` are `&T` (a shared borrow) and `&mut T`
32 /// (a mutable borrow). But types like `Vec<T>` provide additional kinds of
33 /// borrows: the borrowed slices `&[T]` and `&mut [T]`.
35 /// When writing generic code, it is often desirable to abstract over all ways
36 /// of borrowing data from a given type. That is the role of the `Borrow`
37 /// trait: if `T: Borrow<U>`, then `&U` can be borrowed from `&T`. A given
38 /// type can be borrowed as multiple different types. In particular, `Vec<T>:
39 /// Borrow<Vec<T>>` and `Vec<T>: Borrow<[T]>`.
41 /// `Borrow` is very similar to, but different than, `AsRef`. See
42 /// [the book][book] for more.
44 /// [book]: ../../book/borrow-and-asref.html
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub trait Borrow
<Borrowed
: ?Sized
> {
47 /// Immutably borrows from an owned value.
52 /// use std::borrow::Borrow;
54 /// fn check<T: Borrow<str>>(s: T) {
55 /// assert_eq!("Hello", s.borrow());
58 /// let s = "Hello".to_string();
66 #[stable(feature = "rust1", since = "1.0.0")]
67 fn borrow(&self) -> &Borrowed
;
70 /// A trait for mutably borrowing data.
72 /// Similar to `Borrow`, but for mutable borrows.
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub trait BorrowMut
<Borrowed
: ?Sized
> : Borrow
<Borrowed
> {
75 /// Mutably borrows from an owned value.
80 /// use std::borrow::BorrowMut;
82 /// fn check<T: BorrowMut<[i32]>>(mut v: T) {
83 /// assert_eq!(&mut [1, 2, 3], v.borrow_mut());
86 /// let v = vec![1, 2, 3];
90 #[stable(feature = "rust1", since = "1.0.0")]
91 fn borrow_mut(&mut self) -> &mut Borrowed
;
94 #[stable(feature = "rust1", since = "1.0.0")]
95 impl<T
: ?Sized
> Borrow
<T
> for T
{
96 fn borrow(&self) -> &T { self }
99 #[stable(feature = "rust1", since = "1.0.0")]
100 impl<T
: ?Sized
> BorrowMut
<T
> for T
{
101 fn borrow_mut(&mut self) -> &mut T { self }
104 #[stable(feature = "rust1", since = "1.0.0")]
105 impl<'a
, T
: ?Sized
> Borrow
<T
> for &'a T
{
106 fn borrow(&self) -> &T { &**self }
109 #[stable(feature = "rust1", since = "1.0.0")]
110 impl<'a
, T
: ?Sized
> Borrow
<T
> for &'a
mut T
{
111 fn borrow(&self) -> &T { &**self }
114 #[stable(feature = "rust1", since = "1.0.0")]
115 impl<'a
, T
: ?Sized
> BorrowMut
<T
> for &'a
mut T
{
116 fn borrow_mut(&mut self) -> &mut T { &mut **self }
119 impl<T
: ?Sized
> Borrow
<T
> for boxed
::Box
<T
> {
120 fn borrow(&self) -> &T { &**self }
123 impl<T
: ?Sized
> BorrowMut
<T
> for boxed
::Box
<T
> {
124 fn borrow_mut(&mut self) -> &mut T { &mut **self }
127 impl<T
: ?Sized
> Borrow
<T
> for rc
::Rc
<T
> {
128 fn borrow(&self) -> &T { &**self }
131 impl<T
: ?Sized
> Borrow
<T
> for arc
::Arc
<T
> {
132 fn borrow(&self) -> &T { &**self }
135 #[stable(feature = "rust1", since = "1.0.0")]
136 impl<'a
, B
: ?Sized
> Borrow
<B
> for Cow
<'a
, B
> where B
: ToOwned
, <B
as ToOwned
>::Owned
: 'a
{
137 fn borrow(&self) -> &B
{
142 /// A generalization of `Clone` to borrowed data.
144 /// Some types make it possible to go from borrowed to owned, usually by
145 /// implementing the `Clone` trait. But `Clone` works only for going from `&T`
146 /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
147 /// from any borrow of a given type.
148 #[stable(feature = "rust1", since = "1.0.0")]
150 #[stable(feature = "rust1", since = "1.0.0")]
151 type Owned
: Borrow
<Self>;
153 /// Creates owned data from borrowed data, usually by cloning.
154 #[stable(feature = "rust1", since = "1.0.0")]
155 fn to_owned(&self) -> Self::Owned
;
158 #[stable(feature = "rust1", since = "1.0.0")]
159 impl<T
> ToOwned
for T
where T
: Clone
{
161 fn to_owned(&self) -> T { self.clone() }
164 /// A clone-on-write smart pointer.
166 /// The type `Cow` is a smart pointer providing clone-on-write functionality: it
167 /// can enclose and provide immutable access to borrowed data, and clone the
168 /// data lazily when mutation or ownership is required. The type is designed to
169 /// work with general borrowed data via the `Borrow` trait.
171 /// `Cow` implements `Deref`, which means that you can call
172 /// non-mutating methods directly on the data it encloses. If mutation
173 /// is desired, `to_mut` will obtain a mutable reference to an owned
174 /// value, cloning if necessary.
179 /// use std::borrow::Cow;
181 /// fn abs_all(input: &mut Cow<[i32]>) {
182 /// for i in 0..input.len() {
183 /// let v = input[i];
185 /// // clones into a vector the first time (if not already owned)
186 /// input.to_mut()[i] = -v;
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub enum Cow
<'a
, B
: ?Sized
+ 'a
> where B
: ToOwned
{
194 #[stable(feature = "rust1", since = "1.0.0")]
198 #[stable(feature = "rust1", since = "1.0.0")]
199 Owned(<B
as ToOwned
>::Owned
)
202 #[stable(feature = "rust1", since = "1.0.0")]
203 impl<'a
, B
: ?Sized
> Clone
for Cow
<'a
, B
> where B
: ToOwned
{
204 fn clone(&self) -> Cow
<'a
, B
> {
206 Borrowed(b
) => Borrowed(b
),
208 let b
: &B
= o
.borrow();
215 impl<'a
, B
: ?Sized
> Cow
<'a
, B
> where B
: ToOwned
{
216 /// Acquires a mutable reference to the owned form of the data.
218 /// Clones the data if it is not already owned.
223 /// use std::borrow::Cow;
225 /// let mut cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]);
227 /// let hello = cow.to_mut();
229 /// assert_eq!(hello, &[1, 2, 3]);
231 #[stable(feature = "rust1", since = "1.0.0")]
232 pub fn to_mut(&mut self) -> &mut <B
as ToOwned
>::Owned
{
234 Borrowed(borrowed
) => {
235 *self = Owned(borrowed
.to_owned());
238 Owned(ref mut owned
) => owned
242 /// Extracts the owned data.
244 /// Clones the data if it is not already owned.
249 /// use std::borrow::Cow;
251 /// let cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]);
253 /// let hello = cow.into_owned();
255 /// assert_eq!(vec![1, 2, 3], hello);
257 #[stable(feature = "rust1", since = "1.0.0")]
258 pub fn into_owned(self) -> <B
as ToOwned
>::Owned
{
260 Borrowed(borrowed
) => borrowed
.to_owned(),
261 Owned(owned
) => owned
266 #[stable(feature = "rust1", since = "1.0.0")]
267 impl<'a
, B
: ?Sized
> Deref
for Cow
<'a
, B
> where B
: ToOwned
{
270 fn deref(&self) -> &B
{
272 Borrowed(borrowed
) => borrowed
,
273 Owned(ref owned
) => owned
.borrow()
278 #[stable(feature = "rust1", since = "1.0.0")]
279 impl<'a
, B
: ?Sized
> Eq
for Cow
<'a
, B
> where B
: Eq
+ ToOwned {}
281 #[stable(feature = "rust1", since = "1.0.0")]
282 impl<'a
, B
: ?Sized
> Ord
for Cow
<'a
, B
> where B
: Ord
+ ToOwned
{
284 fn cmp(&self, other
: &Cow
<'a
, B
>) -> Ordering
{
285 Ord
::cmp(&**self, &**other
)
289 #[stable(feature = "rust1", since = "1.0.0")]
290 impl<'a
, 'b
, B
: ?Sized
, C
: ?Sized
> PartialEq
<Cow
<'b
, C
>> for Cow
<'a
, B
> where
291 B
: PartialEq
<C
> + ToOwned
, C
: ToOwned
,
294 fn eq(&self, other
: &Cow
<'b
, C
>) -> bool
{
295 PartialEq
::eq(&**self, &**other
)
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl<'a
, B
: ?Sized
> PartialOrd
for Cow
<'a
, B
> where B
: PartialOrd
+ ToOwned
,
303 fn partial_cmp(&self, other
: &Cow
<'a
, B
>) -> Option
<Ordering
> {
304 PartialOrd
::partial_cmp(&**self, &**other
)
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl<'a
, B
: ?Sized
> fmt
::Debug
for Cow
<'a
, B
> where
310 B
: fmt
::Debug
+ ToOwned
,
311 <B
as ToOwned
>::Owned
: fmt
::Debug
,
313 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
315 Borrowed(ref b
) => fmt
::Debug
::fmt(b
, f
),
316 Owned(ref o
) => fmt
::Debug
::fmt(o
, f
),
321 #[stable(feature = "rust1", since = "1.0.0")]
322 impl<'a
, B
: ?Sized
> fmt
::Display
for Cow
<'a
, B
> where
323 B
: fmt
::Display
+ ToOwned
,
324 <B
as ToOwned
>::Owned
: fmt
::Display
,
326 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
328 Borrowed(ref b
) => fmt
::Display
::fmt(b
, f
),
329 Owned(ref o
) => fmt
::Display
::fmt(o
, f
),
334 #[stable(feature = "rust1", since = "1.0.0")]
335 impl<'a
, B
: ?Sized
> Hash
for Cow
<'a
, B
> where B
: Hash
+ ToOwned
338 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
339 Hash
::hash(&**self, state
)
343 /// Trait for moving into a `Cow`.
344 #[unstable(feature = "into_cow", reason = "may be replaced by `convert::Into`")]
345 pub trait IntoCow
<'a
, B
: ?Sized
> where B
: ToOwned
{
346 /// Moves `self` into `Cow`
347 fn into_cow(self) -> Cow
<'a
, B
>;
350 #[stable(feature = "rust1", since = "1.0.0")]
351 impl<'a
, B
: ?Sized
> IntoCow
<'a
, B
> for Cow
<'a
, B
> where B
: ToOwned
{
352 fn into_cow(self) -> Cow
<'a
, B
> {
357 #[stable(feature = "rust1", since = "1.0.0")]
358 impl<'a
, T
: ?Sized
+ ToOwned
> AsRef
<T
> for Cow
<'a
, T
> {
359 fn as_ref(&self) -> &T
{