]> git.lizzy.rs Git - rust.git/blob - src/libcore/borrow.rs
rollup merge of #20594: nikomatsakis/orphan-ordered
[rust.git] / src / libcore / 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 //! # The `BorrowFrom` traits
14 //!
15 //! In general, there may be several ways to "borrow" a piece of data.  The
16 //! typical ways of borrowing a type `T` are `&T` (a shared borrow) and `&mut T`
17 //! (a mutable borrow). But types like `Vec<T>` provide additional kinds of
18 //! borrows: the borrowed slices `&[T]` and `&mut [T]`.
19 //!
20 //! When writing generic code, it is often desirable to abstract over all ways
21 //! of borrowing data from a given type. That is the role of the `BorrowFrom`
22 //! trait: if `T: BorrowFrom<U>`, then `&T` can be borrowed from `&U`.  A given
23 //! type can be borrowed as multiple different types. In particular, `Vec<T>:
24 //! BorrowFrom<Vec<T>>` and `[T]: BorrowFrom<Vec<T>>`.
25 //!
26 //! # The `ToOwned` trait
27 //!
28 //! Some types make it possible to go from borrowed to owned, usually by
29 //! implementing the `Clone` trait. But `Clone` works only for going from `&T`
30 //! to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
31 //! from any borrow of a given type.
32 //!
33 //! # The `Cow` (clone-on-write) type
34 //!
35 //! The type `Cow` is a smart pointer providing clone-on-write functionality: it
36 //! can enclose and provide immutable access to borrowed data, and clone the
37 //! data lazily when mutation or ownership is required. The type is designed to
38 //! work with general borrowed data via the `BorrowFrom` trait.
39 //!
40 //! `Cow` implements both `Deref`, which means that you can call
41 //! non-mutating methods directly on the data it encloses. If mutation
42 //! is desired, `to_mut` will obtain a mutable references to an owned
43 //! value, cloning if necessary.
44
45 #![unstable = "recently added as part of collections reform"]
46
47 use clone::Clone;
48 use cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
49 use fmt;
50 use kinds::Sized;
51 use ops::Deref;
52 use option::Option;
53 use self::Cow::*;
54
55 /// A trait for borrowing data.
56 #[old_orphan_check]
57 pub trait BorrowFrom<Sized? Owned> for Sized? {
58     /// Immutably borrow from an owned value.
59     fn borrow_from(owned: &Owned) -> &Self;
60 }
61
62 /// A trait for mutably borrowing data.
63 #[old_orphan_check]
64 pub trait BorrowFromMut<Sized? Owned> for Sized? : BorrowFrom<Owned> {
65     /// Mutably borrow from an owned value.
66     fn borrow_from_mut(owned: &mut Owned) -> &mut Self;
67 }
68
69 impl<Sized? T> BorrowFrom<T> for T {
70     fn borrow_from(owned: &T) -> &T { owned }
71 }
72
73 impl<Sized? T> BorrowFromMut<T> for T {
74     fn borrow_from_mut(owned: &mut T) -> &mut T { owned }
75 }
76
77 impl<'a, Sized? T> BorrowFrom<&'a T> for T {
78     fn borrow_from<'b>(owned: &'b &'a T) -> &'b T { &**owned }
79 }
80
81 impl<'a, Sized? T> BorrowFrom<&'a mut T> for T {
82     fn borrow_from<'b>(owned: &'b &'a mut T) -> &'b T { &**owned }
83 }
84
85 impl<'a, Sized? T> BorrowFromMut<&'a mut T> for T {
86     fn borrow_from_mut<'b>(owned: &'b mut &'a mut T) -> &'b mut T { &mut **owned }
87 }
88
89 impl<'a, T, Sized? B> BorrowFrom<Cow<'a, T, B>> for B where B: ToOwned<T> {
90     fn borrow_from<'b>(owned: &'b Cow<'a, T, B>) -> &'b B {
91         &**owned
92     }
93 }
94
95 /// Trait for moving into a `Cow`
96 #[old_orphan_check]
97 pub trait IntoCow<'a, T, Sized? B> {
98     /// Moves `self` into `Cow`
99     fn into_cow(self) -> Cow<'a, T, B>;
100 }
101
102 impl<'a, T, Sized? B> IntoCow<'a, T, B> for Cow<'a, T, B> where B: ToOwned<T> {
103     fn into_cow(self) -> Cow<'a, T, B> {
104         self
105     }
106 }
107
108 /// A generalization of Clone to borrowed data.
109 #[old_orphan_check]
110 pub trait ToOwned<Owned> for Sized?: BorrowFrom<Owned> {
111     /// Create owned data from borrowed data, usually by copying.
112     fn to_owned(&self) -> Owned;
113 }
114
115 impl<T> ToOwned<T> for T where T: Clone {
116     fn to_owned(&self) -> T { self.clone() }
117 }
118
119 /// A clone-on-write smart pointer.
120 ///
121 /// # Example
122 ///
123 /// ```rust
124 /// use std::borrow::Cow;
125 ///
126 /// fn abs_all(input: &mut Cow<Vec<int>, [int]>) {
127 ///     for i in range(0, input.len()) {
128 ///         let v = input[i];
129 ///         if v < 0 {
130 ///             // clones into a vector the first time (if not already owned)
131 ///             input.to_mut()[i] = -v;
132 ///         }
133 ///     }
134 /// }
135 /// ```
136 pub enum Cow<'a, T, Sized? B: 'a> where B: ToOwned<T> {
137     /// Borrowed data.
138     Borrowed(&'a B),
139
140     /// Owned data.
141     Owned(T)
142 }
143
144 #[stable]
145 impl<'a, T, Sized? B> Clone for Cow<'a, T, B> where B: ToOwned<T> {
146     fn clone(&self) -> Cow<'a, T, B> {
147         match *self {
148             Borrowed(b) => Borrowed(b),
149             Owned(ref o) => {
150                 let b: &B = BorrowFrom::borrow_from(o);
151                 Owned(b.to_owned())
152             },
153         }
154     }
155 }
156
157 impl<'a, T, Sized? B> Cow<'a, T, B> where B: ToOwned<T> {
158     /// Acquire a mutable reference to the owned form of the data.
159     ///
160     /// Copies the data if it is not already owned.
161     pub fn to_mut(&mut self) -> &mut T {
162         match *self {
163             Borrowed(borrowed) => {
164                 *self = Owned(borrowed.to_owned());
165                 self.to_mut()
166             }
167             Owned(ref mut owned) => owned
168         }
169     }
170
171     /// Extract the owned data.
172     ///
173     /// Copies the data if it is not already owned.
174     pub fn into_owned(self) -> T {
175         match self {
176             Borrowed(borrowed) => borrowed.to_owned(),
177             Owned(owned) => owned
178         }
179     }
180
181     /// Returns true if this `Cow` wraps a borrowed value
182     pub fn is_borrowed(&self) -> bool {
183         match *self {
184             Borrowed(_) => true,
185             _ => false,
186         }
187     }
188
189     /// Returns true if this `Cow` wraps an owned value
190     pub fn is_owned(&self) -> bool {
191         match *self {
192             Owned(_) => true,
193             _ => false,
194         }
195     }
196 }
197
198 #[stable]
199 impl<'a, T, Sized? B> Deref for Cow<'a, T, B> where B: ToOwned<T>  {
200     type Target = B;
201
202     fn deref(&self) -> &B {
203         match *self {
204             Borrowed(borrowed) => borrowed,
205             Owned(ref owned) => BorrowFrom::borrow_from(owned)
206         }
207     }
208 }
209
210 #[stable]
211 impl<'a, T, Sized? B> Eq for Cow<'a, T, B> where B: Eq + ToOwned<T> {}
212
213 #[stable]
214 impl<'a, T, Sized? B> Ord for Cow<'a, T, B> where B: Ord + ToOwned<T> {
215     #[inline]
216     fn cmp(&self, other: &Cow<'a, T, B>) -> Ordering {
217         Ord::cmp(&**self, &**other)
218     }
219 }
220
221 #[stable]
222 impl<'a, 'b, T, U, Sized? B, Sized? C> PartialEq<Cow<'b, U, C>> for Cow<'a, T, B> where
223     B: PartialEq<C> + ToOwned<T>,
224     C: ToOwned<U>,
225 {
226     #[inline]
227     fn eq(&self, other: &Cow<'b, U, C>) -> bool {
228         PartialEq::eq(&**self, &**other)
229     }
230 }
231
232 #[stable]
233 impl<'a, T, Sized? B> PartialOrd for Cow<'a, T, B> where B: PartialOrd + ToOwned<T> {
234     #[inline]
235     fn partial_cmp(&self, other: &Cow<'a, T, B>) -> Option<Ordering> {
236         PartialOrd::partial_cmp(&**self, &**other)
237     }
238 }
239
240 impl<'a, T, Sized? B> fmt::Show for Cow<'a, T, B> where B: fmt::Show + ToOwned<T>, T: fmt::Show {
241     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
242         match *self {
243             Borrowed(ref b) => fmt::Show::fmt(b, f),
244             Owned(ref o) => fmt::Show::fmt(o, f),
245         }
246     }
247 }