]> git.lizzy.rs Git - rust.git/blob - src/libcore/borrow.rs
Auto merge of #56838 - Aaron1011:fix/rustdoc-infer-unify, r=nikomatsakis
[rust.git] / src / libcore / borrow.rs
1 //! A module for working with borrowed data.
2
3 #![stable(feature = "rust1", since = "1.0.0")]
4
5 /// A trait for borrowing data.
6 ///
7 /// In Rust, it is common to provide different representations of a type for
8 /// different use cases. For instance, storage location and management for a
9 /// value can be specifically chosen as appropriate for a particular use via
10 /// pointer types such as [`Box<T>`] or [`Rc<T>`]. Beyond these generic
11 /// wrappers that can be used with any type, some types provide optional
12 /// facets providing potentially costly functionality. An example for such a
13 /// type is [`String`] which adds the ability to extend a string to the basic
14 /// [`str`]. This requires keeping additional information unnecessary for a
15 /// simple, immutable string.
16 ///
17 /// These types provide access to the underlying data through references
18 /// to the type of that data. They are said to be ‘borrowed as’ that type.
19 /// For instance, a [`Box<T>`] can be borrowed as `T` while a [`String`]
20 /// can be borrowed as `str`.
21 ///
22 /// Types express that they can be borrowed as some type `T` by implementing
23 /// `Borrow<T>`, providing a reference to a `T` in the trait’s
24 /// [`borrow`] method. A type is free to borrow as several different types.
25 /// If it wishes to mutably borrow as the type – allowing the underlying data
26 /// to be modified, it can additionally implement [`BorrowMut<T>`].
27 ///
28 /// Further, when providing implementations for additional traits, it needs
29 /// to be considered whether they should behave identical to those of the
30 /// underlying type as a consequence of acting as a representation of that
31 /// underlying type. Generic code typically uses `Borrow<T>` when it relies
32 /// on the identical behavior of these additional trait implementations.
33 /// These traits will likely appear as additional trait bounds.
34 ///
35 /// If generic code merely needs to work for all types that can
36 /// provide a reference to related type `T`, it is often better to use
37 /// [`AsRef<T>`] as more types can safely implement it.
38 ///
39 /// [`AsRef<T>`]: ../../std/convert/trait.AsRef.html
40 /// [`BorrowMut<T>`]: trait.BorrowMut.html
41 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
42 /// [`Mutex<T>`]: ../../std/sync/struct.Mutex.html
43 /// [`Rc<T>`]: ../../std/rc/struct.Rc.html
44 /// [`str`]: ../../std/primitive.str.html
45 /// [`String`]: ../../std/string/struct.String.html
46 /// [`borrow`]: #tymethod.borrow
47 ///
48 /// # Examples
49 ///
50 /// As a data collection, [`HashMap<K, V>`] owns both keys and values. If
51 /// the key’s actual data is wrapped in a managing type of some kind, it
52 /// should, however, still be possible to search for a value using a
53 /// reference to the key’s data. For instance, if the key is a string, then
54 /// it is likely stored with the hash map as a [`String`], while it should
55 /// be possible to search using a [`&str`][`str`]. Thus, `insert` needs to
56 /// operate on a `String` while `get` needs to be able to use a `&str`.
57 ///
58 /// Slightly simplified, the relevant parts of `HashMap<K, V>` look like
59 /// this:
60 ///
61 /// ```
62 /// use std::borrow::Borrow;
63 /// use std::hash::Hash;
64 ///
65 /// pub struct HashMap<K, V> {
66 ///     # marker: ::std::marker::PhantomData<(K, V)>,
67 ///     // fields omitted
68 /// }
69 ///
70 /// impl<K, V> HashMap<K, V> {
71 ///     pub fn insert(&self, key: K, value: V) -> Option<V>
72 ///     where K: Hash + Eq
73 ///     {
74 ///         # unimplemented!()
75 ///         // ...
76 ///     }
77 ///
78 ///     pub fn get<Q>(&self, k: &Q) -> Option<&V>
79 ///     where
80 ///         K: Borrow<Q>,
81 ///         Q: Hash + Eq + ?Sized
82 ///     {
83 ///         # unimplemented!()
84 ///         // ...
85 ///     }
86 /// }
87 /// ```
88 ///
89 /// The entire hash map is generic over a key type `K`. Because these keys
90 /// are stored with the hash map, this type has to own the key’s data.
91 /// When inserting a key-value pair, the map is given such a `K` and needs
92 /// to find the correct hash bucket and check if the key is already present
93 /// based on that `K`. It therefore requires `K: Hash + Eq`.
94 ///
95 /// When searching for a value in the map, however, having to provide a
96 /// reference to a `K` as the key to search for would require to always
97 /// create such an owned value. For string keys, this would mean a `String`
98 /// value needs to be created just for the search for cases where only a
99 /// `str` is available.
100 ///
101 /// Instead, the `get` method is generic over the type of the underlying key
102 /// data, called `Q` in the method signature above. It states that `K`
103 /// borrows as a `Q` by requiring that `K: Borrow<Q>`. By additionally
104 /// requiring `Q: Hash + Eq`, it signals the requirement that `K` and `Q`
105 /// have implementations of the `Hash` and `Eq` traits that produce identical
106 /// results.
107 ///
108 /// The implementation of `get` relies in particular on identical
109 /// implementations of `Hash` by determining the key’s hash bucket by calling
110 /// `Hash::hash` on the `Q` value even though it inserted the key based on
111 /// the hash value calculated from the `K` value.
112 ///
113 /// As a consequence, the hash map breaks if a `K` wrapping a `Q` value
114 /// produces a different hash than `Q`. For instance, imagine you have a
115 /// type that wraps a string but compares ASCII letters ignoring their case:
116 ///
117 /// ```
118 /// pub struct CaseInsensitiveString(String);
119 ///
120 /// impl PartialEq for CaseInsensitiveString {
121 ///     fn eq(&self, other: &Self) -> bool {
122 ///         self.0.eq_ignore_ascii_case(&other.0)
123 ///     }
124 /// }
125 ///
126 /// impl Eq for CaseInsensitiveString { }
127 /// ```
128 ///
129 /// Because two equal values need to produce the same hash value, the
130 /// implementation of `Hash` needs to ignore ASCII case, too:
131 ///
132 /// ```
133 /// # use std::hash::{Hash, Hasher};
134 /// # pub struct CaseInsensitiveString(String);
135 /// impl Hash for CaseInsensitiveString {
136 ///     fn hash<H: Hasher>(&self, state: &mut H) {
137 ///         for c in self.0.as_bytes() {
138 ///             c.to_ascii_lowercase().hash(state)
139 ///         }
140 ///     }
141 /// }
142 /// ```
143 ///
144 /// Can `CaseInsensitiveString` implement `Borrow<str>`? It certainly can
145 /// provide a reference to a string slice via its contained owned string.
146 /// But because its `Hash` implementation differs, it behaves differently
147 /// from `str` and therefore must not, in fact, implement `Borrow<str>`.
148 /// If it wants to allow others access to the underlying `str`, it can do
149 /// that via `AsRef<str>` which doesn’t carry any extra requirements.
150 ///
151 /// [`Hash`]: ../../std/hash/trait.Hash.html
152 /// [`HashMap<K, V>`]: ../../std/collections/struct.HashMap.html
153 /// [`String`]: ../../std/string/struct.String.html
154 /// [`str`]: ../../std/primitive.str.html
155 #[stable(feature = "rust1", since = "1.0.0")]
156 pub trait Borrow<Borrowed: ?Sized> {
157     /// Immutably borrows from an owned value.
158     ///
159     /// # Examples
160     ///
161     /// ```
162     /// use std::borrow::Borrow;
163     ///
164     /// fn check<T: Borrow<str>>(s: T) {
165     ///     assert_eq!("Hello", s.borrow());
166     /// }
167     ///
168     /// let s = "Hello".to_string();
169     ///
170     /// check(s);
171     ///
172     /// let s = "Hello";
173     ///
174     /// check(s);
175     /// ```
176     #[stable(feature = "rust1", since = "1.0.0")]
177     fn borrow(&self) -> &Borrowed;
178 }
179
180 /// A trait for mutably borrowing data.
181 ///
182 /// As a companion to [`Borrow<T>`] this trait allows a type to borrow as
183 /// an underlying type by providing a mutable reference. See [`Borrow<T>`]
184 /// for more information on borrowing as another type.
185 ///
186 /// [`Borrow<T>`]: trait.Borrow.html
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub trait BorrowMut<Borrowed: ?Sized> : Borrow<Borrowed> {
189     /// Mutably borrows from an owned value.
190     ///
191     /// # Examples
192     ///
193     /// ```
194     /// use std::borrow::BorrowMut;
195     ///
196     /// fn check<T: BorrowMut<[i32]>>(mut v: T) {
197     ///     assert_eq!(&mut [1, 2, 3], v.borrow_mut());
198     /// }
199     ///
200     /// let v = vec![1, 2, 3];
201     ///
202     /// check(v);
203     /// ```
204     #[stable(feature = "rust1", since = "1.0.0")]
205     fn borrow_mut(&mut self) -> &mut Borrowed;
206 }
207
208 #[stable(feature = "rust1", since = "1.0.0")]
209 impl<T: ?Sized> Borrow<T> for T {
210     fn borrow(&self) -> &T { self }
211 }
212
213 #[stable(feature = "rust1", since = "1.0.0")]
214 impl<T: ?Sized> BorrowMut<T> for T {
215     fn borrow_mut(&mut self) -> &mut T { self }
216 }
217
218 #[stable(feature = "rust1", since = "1.0.0")]
219 impl<T: ?Sized> Borrow<T> for &T {
220     fn borrow(&self) -> &T { &**self }
221 }
222
223 #[stable(feature = "rust1", since = "1.0.0")]
224 impl<T: ?Sized> Borrow<T> for &mut T {
225     fn borrow(&self) -> &T { &**self }
226 }
227
228 #[stable(feature = "rust1", since = "1.0.0")]
229 impl<T: ?Sized> BorrowMut<T> for &mut T {
230     fn borrow_mut(&mut self) -> &mut T { &mut **self }
231 }