]> git.lizzy.rs Git - rust.git/blob - src/libcore/borrow.rs
rollup merge of #19577: aidancully/master
[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 pub trait BorrowFrom<Sized? Owned> for Sized? {
57     /// Immutably borrow from an owned value.
58     fn borrow_from(owned: &Owned) -> &Self;
59 }
60
61 /// A trait for mutably borrowing data.
62 pub trait BorrowFromMut<Sized? Owned> for Sized? : BorrowFrom<Owned> {
63     /// Mutably borrow from an owned value.
64     fn borrow_from_mut(owned: &mut Owned) -> &mut Self;
65 }
66
67 impl<Sized? T> BorrowFrom<T> for T {
68     fn borrow_from(owned: &T) -> &T { owned }
69 }
70
71 impl<Sized? T> BorrowFromMut<T> for T {
72     fn borrow_from_mut(owned: &mut T) -> &mut T { owned }
73 }
74
75 impl<'a, Sized? T> BorrowFrom<&'a T> for T {
76     fn borrow_from<'b>(owned: &'b &'a T) -> &'b T { &**owned }
77 }
78
79 impl<'a, Sized? T> BorrowFrom<&'a mut T> for T {
80     fn borrow_from<'b>(owned: &'b &'a mut T) -> &'b T { &**owned }
81 }
82
83 impl<'a, Sized? T> BorrowFromMut<&'a mut T> for T {
84     fn borrow_from_mut<'b>(owned: &'b mut &'a mut T) -> &'b mut T { &mut **owned }
85 }
86
87 impl<'a, T, Sized? B> BorrowFrom<Cow<'a, T, B>> for B where B: ToOwned<T> {
88     fn borrow_from<'b>(owned: &'b Cow<'a, T, B>) -> &'b B {
89         &**owned
90     }
91 }
92
93 /// Trait for moving into a `Cow`
94 pub trait IntoCow<'a, T, Sized? B> {
95     /// Moves `self` into `Cow`
96     fn into_cow(self) -> Cow<'a, T, B>;
97 }
98
99 impl<'a, T, Sized? B> IntoCow<'a, T, B> for Cow<'a, T, B> where B: ToOwned<T> {
100     fn into_cow(self) -> Cow<'a, T, B> {
101         self
102     }
103 }
104
105 /// A generalization of Clone to borrowed data.
106 pub trait ToOwned<Owned> for Sized?: BorrowFrom<Owned> {
107     /// Create owned data from borrowed data, usually by copying.
108     fn to_owned(&self) -> Owned;
109 }
110
111 impl<T> ToOwned<T> for T where T: Clone {
112     fn to_owned(&self) -> T { self.clone() }
113 }
114
115 /// A clone-on-write smart pointer.
116 ///
117 /// # Example
118 ///
119 /// ```rust
120 /// use std::borrow::Cow;
121 ///
122 /// fn abs_all(input: &mut Cow<Vec<int>, [int]>) {
123 ///     for i in range(0, input.len()) {
124 ///         let v = input[i];
125 ///         if v < 0 {
126 ///             // clones into a vector the first time (if not already owned)
127 ///             input.to_mut()[i] = -v;
128 ///         }
129 ///     }
130 /// }
131 /// ```
132 pub enum Cow<'a, T, Sized? B: 'a> where B: ToOwned<T> {
133     /// Borrowed data.
134     Borrowed(&'a B),
135
136     /// Owned data.
137     Owned(T)
138 }
139
140 impl<'a, T, Sized? B> Clone for Cow<'a, T, B> where B: ToOwned<T> {
141     fn clone(&self) -> Cow<'a, T, B> {
142         match *self {
143             Borrowed(b) => Borrowed(b),
144             Owned(ref o) => {
145                 let b: &B = BorrowFrom::borrow_from(o);
146                 Owned(b.to_owned())
147             },
148         }
149     }
150 }
151
152 impl<'a, T, Sized? B> Cow<'a, T, B> where B: ToOwned<T> {
153     /// Acquire a mutable reference to the owned form of the data.
154     ///
155     /// Copies the data if it is not already owned.
156     pub fn to_mut(&mut self) -> &mut T {
157         match *self {
158             Borrowed(borrowed) => {
159                 *self = Owned(borrowed.to_owned());
160                 self.to_mut()
161             }
162             Owned(ref mut owned) => owned
163         }
164     }
165
166     /// Extract the owned data.
167     ///
168     /// Copies the data if it is not already owned.
169     pub fn into_owned(self) -> T {
170         match self {
171             Borrowed(borrowed) => borrowed.to_owned(),
172             Owned(owned) => owned
173         }
174     }
175
176     /// Returns true if this `Cow` wraps a borrowed value
177     pub fn is_borrowed(&self) -> bool {
178         match *self {
179             Borrowed(_) => true,
180             _ => false,
181         }
182     }
183
184     /// Returns true if this `Cow` wraps an owned value
185     pub fn is_owned(&self) -> bool {
186         match *self {
187             Owned(_) => true,
188             _ => false,
189         }
190     }
191 }
192
193 impl<'a, T, Sized? B> Deref<B> for Cow<'a, T, B> where B: ToOwned<T>  {
194     fn deref(&self) -> &B {
195         match *self {
196             Borrowed(borrowed) => borrowed,
197             Owned(ref owned) => BorrowFrom::borrow_from(owned)
198         }
199     }
200 }
201
202 impl<'a, T, Sized? B> Eq for Cow<'a, T, B> where B: Eq + ToOwned<T> {}
203
204 impl<'a, T, Sized? B> Ord for Cow<'a, T, B> where B: Ord + ToOwned<T> {
205     #[inline]
206     fn cmp(&self, other: &Cow<'a, T, B>) -> Ordering {
207         Ord::cmp(&**self, &**other)
208     }
209 }
210
211 impl<'a, 'b, T, U, Sized? B, Sized? C> PartialEq<Cow<'b, U, C>> for Cow<'a, T, B> where
212     B: PartialEq<C> + ToOwned<T>,
213     C: ToOwned<U>,
214 {
215     #[inline]
216     fn eq(&self, other: &Cow<'b, U, C>) -> bool {
217         PartialEq::eq(&**self, &**other)
218     }
219 }
220
221 impl<'a, T, Sized? B> PartialOrd for Cow<'a, T, B> where B: PartialOrd + ToOwned<T> {
222     #[inline]
223     fn partial_cmp(&self, other: &Cow<'a, T, B>) -> Option<Ordering> {
224         PartialOrd::partial_cmp(&**self, &**other)
225     }
226 }
227
228 impl<'a, T, Sized? B> fmt::Show for Cow<'a, T, B> where B: fmt::Show + ToOwned<T>, T: fmt::Show {
229     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
230         match *self {
231             Borrowed(ref b) => fmt::Show::fmt(b, f),
232             Owned(ref o) => fmt::Show::fmt(o, f),
233         }
234     }
235 }