]> git.lizzy.rs Git - rust.git/blob - src/libcore/borrow.rs
4363a0a444113bc72268563dcfa86b2ebd5f9f62
[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 marker::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<Owned: ?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<Owned: ?Sized> : BorrowFrom<Owned> {
65     /// Mutably borrow from an owned value.
66     fn borrow_from_mut(owned: &mut Owned) -> &mut Self;
67 }
68
69 impl<T: ?Sized> BorrowFrom<T> for T {
70     fn borrow_from(owned: &T) -> &T { owned }
71 }
72
73 impl<T: ?Sized> BorrowFromMut<T> for T {
74     fn borrow_from_mut(owned: &mut T) -> &mut T { owned }
75 }
76
77 impl<'a, T: ?Sized> BorrowFrom<&'a T> for T {
78     fn borrow_from<'b>(owned: &'b &'a T) -> &'b T { &**owned }
79 }
80
81 impl<'a, T: ?Sized> BorrowFrom<&'a mut T> for T {
82     fn borrow_from<'b>(owned: &'b &'a mut T) -> &'b T { &**owned }
83 }
84
85 impl<'a, T: ?Sized> 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, B: ?Sized> 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, B: ?Sized> {
98     /// Moves `self` into `Cow`
99     fn into_cow(self) -> Cow<'a, T, B>;
100 }
101
102 impl<'a, T, B: ?Sized> 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>: 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 #[derive(Show)]
137 pub enum Cow<'a, T, B: ?Sized + 'a> where B: ToOwned<T> {
138     /// Borrowed data.
139     Borrowed(&'a B),
140
141     /// Owned data.
142     Owned(T)
143 }
144
145 #[stable]
146 impl<'a, T, B: ?Sized> Clone for Cow<'a, T, B> where B: ToOwned<T> {
147     fn clone(&self) -> Cow<'a, T, B> {
148         match *self {
149             Borrowed(b) => Borrowed(b),
150             Owned(ref o) => {
151                 let b: &B = BorrowFrom::borrow_from(o);
152                 Owned(b.to_owned())
153             },
154         }
155     }
156 }
157
158 impl<'a, T, B: ?Sized> Cow<'a, T, B> where B: ToOwned<T> {
159     /// Acquire a mutable reference to the owned form of the data.
160     ///
161     /// Copies the data if it is not already owned.
162     pub fn to_mut(&mut self) -> &mut T {
163         match *self {
164             Borrowed(borrowed) => {
165                 *self = Owned(borrowed.to_owned());
166                 self.to_mut()
167             }
168             Owned(ref mut owned) => owned
169         }
170     }
171
172     /// Extract the owned data.
173     ///
174     /// Copies the data if it is not already owned.
175     pub fn into_owned(self) -> T {
176         match self {
177             Borrowed(borrowed) => borrowed.to_owned(),
178             Owned(owned) => owned
179         }
180     }
181
182     /// Returns true if this `Cow` wraps a borrowed value
183     pub fn is_borrowed(&self) -> bool {
184         match *self {
185             Borrowed(_) => true,
186             _ => false,
187         }
188     }
189
190     /// Returns true if this `Cow` wraps an owned value
191     pub fn is_owned(&self) -> bool {
192         match *self {
193             Owned(_) => true,
194             _ => false,
195         }
196     }
197 }
198
199 #[stable]
200 impl<'a, T, B: ?Sized> Deref for Cow<'a, T, B> where B: ToOwned<T>  {
201     type Target = B;
202
203     fn deref(&self) -> &B {
204         match *self {
205             Borrowed(borrowed) => borrowed,
206             Owned(ref owned) => BorrowFrom::borrow_from(owned)
207         }
208     }
209 }
210
211 #[stable]
212 impl<'a, T, B: ?Sized> Eq for Cow<'a, T, B> where B: Eq + ToOwned<T> {}
213
214 #[stable]
215 impl<'a, T, B: ?Sized> Ord for Cow<'a, T, B> where B: Ord + ToOwned<T> {
216     #[inline]
217     fn cmp(&self, other: &Cow<'a, T, B>) -> Ordering {
218         Ord::cmp(&**self, &**other)
219     }
220 }
221
222 #[stable]
223 impl<'a, 'b, T, U, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, U, C>> for Cow<'a, T, B> where
224     B: PartialEq<C> + ToOwned<T>,
225     C: ToOwned<U>,
226 {
227     #[inline]
228     fn eq(&self, other: &Cow<'b, U, C>) -> bool {
229         PartialEq::eq(&**self, &**other)
230     }
231 }
232
233 #[stable]
234 impl<'a, T, B: ?Sized> PartialOrd for Cow<'a, T, B> where B: PartialOrd + ToOwned<T> {
235     #[inline]
236     fn partial_cmp(&self, other: &Cow<'a, T, B>) -> Option<Ordering> {
237         PartialOrd::partial_cmp(&**self, &**other)
238     }
239 }
240
241 #[stable]
242 impl<'a, T, B: ?Sized> fmt::String for Cow<'a, T, B> where
243     B: fmt::String + ToOwned<T>,
244     T: fmt::String,
245 {
246     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
247         match *self {
248             Borrowed(ref b) => fmt::String::fmt(b, f),
249             Owned(ref o) => fmt::String::fmt(o, f),
250         }
251     }
252 }