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 //! # The `BorrowFrom` traits
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]`.
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>>`.
26 //! # The `ToOwned` trait
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.
33 //! # The `Cow` (clone-on-write) type
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.
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.
45 #![unstable = "recently added as part of collections reform"]
48 use cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
55 /// A trait for borrowing data.
57 pub trait BorrowFrom<Owned: ?Sized> {
58 /// Immutably borrow from an owned value.
59 fn borrow_from(owned: &Owned) -> &Self;
62 /// A trait for mutably borrowing data.
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;
69 impl<T: ?Sized> BorrowFrom<T> for T {
70 fn borrow_from(owned: &T) -> &T { owned }
73 impl<T: ?Sized> BorrowFromMut<T> for T {
74 fn borrow_from_mut(owned: &mut T) -> &mut T { owned }
77 impl<'a, T: ?Sized> BorrowFrom<&'a T> for T {
78 fn borrow_from<'b>(owned: &'b &'a T) -> &'b T { &**owned }
81 impl<'a, T: ?Sized> BorrowFrom<&'a mut T> for T {
82 fn borrow_from<'b>(owned: &'b &'a mut T) -> &'b T { &**owned }
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 }
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 {
95 /// Trait for moving into a `Cow`
97 pub trait IntoCow<'a, T, B: ?Sized> {
98 /// Moves `self` into `Cow`
99 fn into_cow(self) -> Cow<'a, T, B>;
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> {
108 /// A generalization of Clone to borrowed data.
110 pub trait ToOwned<Owned>: BorrowFrom<Owned> {
111 /// Create owned data from borrowed data, usually by copying.
112 fn to_owned(&self) -> Owned;
115 impl<T> ToOwned<T> for T where T: Clone {
116 fn to_owned(&self) -> T { self.clone() }
119 /// A clone-on-write smart pointer.
124 /// use std::borrow::Cow;
126 /// fn abs_all(input: &mut Cow<Vec<int>, [int]>) {
127 /// for i in range(0, input.len()) {
128 /// let v = input[i];
130 /// // clones into a vector the first time (if not already owned)
131 /// input.to_mut()[i] = -v;
137 pub enum Cow<'a, T, B: ?Sized + 'a> where B: ToOwned<T> {
146 impl<'a, T, B: ?Sized> Clone for Cow<'a, T, B> where B: ToOwned<T> {
147 fn clone(&self) -> Cow<'a, T, B> {
149 Borrowed(b) => Borrowed(b),
151 let b: &B = BorrowFrom::borrow_from(o);
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.
161 /// Copies the data if it is not already owned.
162 pub fn to_mut(&mut self) -> &mut T {
164 Borrowed(borrowed) => {
165 *self = Owned(borrowed.to_owned());
168 Owned(ref mut owned) => owned
172 /// Extract the owned data.
174 /// Copies the data if it is not already owned.
175 pub fn into_owned(self) -> T {
177 Borrowed(borrowed) => borrowed.to_owned(),
178 Owned(owned) => owned
182 /// Returns true if this `Cow` wraps a borrowed value
183 pub fn is_borrowed(&self) -> bool {
190 /// Returns true if this `Cow` wraps an owned value
191 pub fn is_owned(&self) -> bool {
200 impl<'a, T, B: ?Sized> Deref for Cow<'a, T, B> where B: ToOwned<T> {
203 fn deref(&self) -> &B {
205 Borrowed(borrowed) => borrowed,
206 Owned(ref owned) => BorrowFrom::borrow_from(owned)
212 impl<'a, T, B: ?Sized> Eq for Cow<'a, T, B> where B: Eq + ToOwned<T> {}
215 impl<'a, T, B: ?Sized> Ord for Cow<'a, T, B> where B: Ord + ToOwned<T> {
217 fn cmp(&self, other: &Cow<'a, T, B>) -> Ordering {
218 Ord::cmp(&**self, &**other)
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>,
228 fn eq(&self, other: &Cow<'b, U, C>) -> bool {
229 PartialEq::eq(&**self, &**other)
234 impl<'a, T, B: ?Sized> PartialOrd for Cow<'a, T, B> where B: PartialOrd + ToOwned<T> {
236 fn partial_cmp(&self, other: &Cow<'a, T, B>) -> Option<Ordering> {
237 PartialOrd::partial_cmp(&**self, &**other)
242 impl<'a, T, B: ?Sized> fmt::String for Cow<'a, T, B> where
243 B: fmt::String + ToOwned<T>,
246 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
248 Borrowed(ref b) => fmt::String::fmt(b, f),
249 Owned(ref o) => fmt::String::fmt(o, f),