]> git.lizzy.rs Git - rust.git/blob - src/libcore/convert.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[rust.git] / src / libcore / convert.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 //! Traits for conversions between types.
12 //!
13 //! The traits in this module provide a general way to talk about conversions
14 //! from one type to another. They follow the standard Rust conventions of
15 //! `as`/`into`/`from`.
16 //!
17 //! Like many traits, these are often used as bounds for generic functions, to
18 //! support arguments of multiple types.
19 //!
20 //! - Impl the `As*` traits for reference-to-reference conversions
21 //! - Impl the [`Into`] trait when you want to consume the value in the conversion
22 //! - The [`From`] trait is the most flexible, useful for value _and_ reference conversions
23 //! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], but allow for the
24 //!   conversion to fail
25 //!
26 //! As a library author, you should prefer implementing [`From<T>`][`From`] or
27 //! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
28 //! as [`From`] and [`TryFrom`] provide greater flexibility and offer
29 //! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a blanket implementation
30 //! in the standard library.
31 //!
32 //! # Generic impl
33 //!
34 //! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference
35 //! - [`From`]`<U> for T` implies [`Into`]`<T> for U`
36 //! - [`TryFrom`]`<U> for T` implies [`TryInto`]`<T> for U`
37 //! - [`From`] and [`Into`] are reflexive, which means that all types can `into()`
38 //!   themselves and `from()` themselves
39 //!
40 //! See each trait for usage examples.
41 //!
42 //! [`Into`]: trait.Into.html
43 //! [`From`]: trait.From.html
44 //! [`TryFrom`]: trait.TryFrom.html
45 //! [`TryInto`]: trait.TryInto.html
46 //! [`AsRef`]: trait.AsRef.html
47 //! [`AsMut`]: trait.AsMut.html
48
49 #![stable(feature = "rust1", since = "1.0.0")]
50
51 use str::FromStr;
52
53 /// A cheap, reference-to-reference conversion.
54 ///
55 /// `AsRef` is very similar to, but different than, [`Borrow`]. See
56 /// [the book][book] for more.
57 ///
58 /// [book]: ../../book/borrow-and-asref.html
59 /// [`Borrow`]: ../../std/borrow/trait.Borrow.html
60 ///
61 /// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which
62 /// returns an [`Option<T>`] or a [`Result<T, E>`].
63 ///
64 /// [`Option<T>`]: ../../std/option/enum.Option.html
65 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
66 ///
67 /// # Examples
68 ///
69 /// Both [`String`] and `&str` implement `AsRef<str>`:
70 ///
71 /// [`String`]: ../../std/string/struct.String.html
72 ///
73 /// ```
74 /// fn is_hello<T: AsRef<str>>(s: T) {
75 ///    assert_eq!("hello", s.as_ref());
76 /// }
77 ///
78 /// let s = "hello";
79 /// is_hello(s);
80 ///
81 /// let s = "hello".to_string();
82 /// is_hello(s);
83 /// ```
84 ///
85 /// # Generic Impls
86 ///
87 /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
88 /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`)
89 ///
90 #[stable(feature = "rust1", since = "1.0.0")]
91 pub trait AsRef<T: ?Sized> {
92     /// Performs the conversion.
93     #[stable(feature = "rust1", since = "1.0.0")]
94     fn as_ref(&self) -> &T;
95 }
96
97 /// A cheap, mutable reference-to-mutable reference conversion.
98 ///
99 /// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which
100 /// returns an [`Option<T>`] or a [`Result<T, E>`].
101 ///
102 /// [`Option<T>`]: ../../std/option/enum.Option.html
103 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
104 ///
105 /// # Examples
106 ///
107 /// [`Box<T>`] implements `AsMut<T>`:
108 ///
109 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
110 ///
111 /// ```
112 /// fn add_one<T: AsMut<u64>>(num: &mut T) {
113 ///     *num.as_mut() += 1;
114 /// }
115 ///
116 /// let mut boxed_num = Box::new(0);
117 /// add_one(&mut boxed_num);
118 /// assert_eq!(*boxed_num, 1);
119 /// ```
120 ///
121 /// # Generic Impls
122 ///
123 /// - `AsMut` auto-dereferences if the inner type is a reference or a mutable
124 /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`)
125 ///
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub trait AsMut<T: ?Sized> {
128     /// Performs the conversion.
129     #[stable(feature = "rust1", since = "1.0.0")]
130     fn as_mut(&mut self) -> &mut T;
131 }
132
133 /// A conversion that consumes `self`, which may or may not be expensive.
134 ///
135 /// **Note: this trait must not fail**. If the conversion can fail, use [`TryInto`] or a dedicated
136 /// method which returns an [`Option<T>`] or a [`Result<T, E>`].
137 ///
138 /// Library authors should not directly implement this trait, but should prefer implementing
139 /// the [`From`][From] trait, which offers greater flexibility and provides an equivalent `Into`
140 /// implementation for free, thanks to a blanket implementation in the standard library.
141 ///
142 /// # Examples
143 ///
144 /// [`String`] implements `Into<Vec<u8>>`:
145 ///
146 /// ```
147 /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
148 ///    let bytes = b"hello".to_vec();
149 ///    assert_eq!(bytes, s.into());
150 /// }
151 ///
152 /// let s = "hello".to_string();
153 /// is_hello(s);
154 /// ```
155 ///
156 /// # Generic Impls
157 ///
158 /// - [`From<T>`][From]` for U` implies `Into<U> for T`
159 /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
160 ///
161 /// [`TryInto`]: trait.TryInto.html
162 /// [`Option<T>`]: ../../std/option/enum.Option.html
163 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
164 /// [`String`]: ../../std/string/struct.String.html
165 /// [From]: trait.From.html
166 /// [`into`]: trait.Into.html#tymethod.into
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub trait Into<T>: Sized {
169     /// Performs the conversion.
170     #[stable(feature = "rust1", since = "1.0.0")]
171     fn into(self) -> T;
172 }
173
174 /// Construct `Self` via a conversion.
175 ///
176 /// **Note: this trait must not fail**. If the conversion can fail, use [`TryFrom`] or a dedicated
177 /// method which returns an [`Option<T>`] or a [`Result<T, E>`].
178 ///
179 /// # Examples
180 ///
181 /// [`String`] implements `From<&str>`:
182 ///
183 /// ```
184 /// let string = "hello".to_string();
185 /// let other_string = String::from("hello");
186 ///
187 /// assert_eq!(string, other_string);
188 /// ```
189 /// # Generic impls
190 ///
191 /// - `From<T> for U` implies [`Into<U>`]` for T`
192 /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
193 ///
194 /// [`TryFrom`]: trait.TryFrom.html
195 /// [`Option<T>`]: ../../std/option/enum.Option.html
196 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
197 /// [`String`]: ../../std/string/struct.String.html
198 /// [`Into<U>`]: trait.Into.html
199 /// [`from`]: trait.From.html#tymethod.from
200 #[stable(feature = "rust1", since = "1.0.0")]
201 pub trait From<T>: Sized {
202     /// Performs the conversion.
203     #[stable(feature = "rust1", since = "1.0.0")]
204     fn from(T) -> Self;
205 }
206
207 /// An attempted conversion that consumes `self`, which may or may not be expensive.
208 ///
209 /// Library authors should not directly implement this trait, but should prefer implementing
210 /// the [`TryFrom`] trait, which offers greater flexibility and provides an equivalent `TryInto`
211 /// implementation for free, thanks to a blanket implementation in the standard library.
212 ///
213 /// [`TryFrom`]: trait.TryFrom.html
214 #[unstable(feature = "try_from", issue = "33417")]
215 pub trait TryInto<T>: Sized {
216     /// The type returned in the event of a conversion error.
217     type Error;
218
219     /// Performs the conversion.
220     fn try_into(self) -> Result<T, Self::Error>;
221 }
222
223 /// Attempt to construct `Self` via a conversion.
224 #[unstable(feature = "try_from", issue = "33417")]
225 pub trait TryFrom<T>: Sized {
226     /// The type returned in the event of a conversion error.
227     type Error;
228
229     /// Performs the conversion.
230     fn try_from(value: T) -> Result<Self, Self::Error>;
231 }
232
233 ////////////////////////////////////////////////////////////////////////////////
234 // GENERIC IMPLS
235 ////////////////////////////////////////////////////////////////////////////////
236
237 // As lifts over &
238 #[stable(feature = "rust1", since = "1.0.0")]
239 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
240     fn as_ref(&self) -> &U {
241         <T as AsRef<U>>::as_ref(*self)
242     }
243 }
244
245 // As lifts over &mut
246 #[stable(feature = "rust1", since = "1.0.0")]
247 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
248     fn as_ref(&self) -> &U {
249         <T as AsRef<U>>::as_ref(*self)
250     }
251 }
252
253 // FIXME (#23442): replace the above impls for &/&mut with the following more general one:
254 // // As lifts over Deref
255 // impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
256 //     fn as_ref(&self) -> &U {
257 //         self.deref().as_ref()
258 //     }
259 // }
260
261 // AsMut lifts over &mut
262 #[stable(feature = "rust1", since = "1.0.0")]
263 impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
264     fn as_mut(&mut self) -> &mut U {
265         (*self).as_mut()
266     }
267 }
268
269 // FIXME (#23442): replace the above impl for &mut with the following more general one:
270 // // AsMut lifts over DerefMut
271 // impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
272 //     fn as_mut(&mut self) -> &mut U {
273 //         self.deref_mut().as_mut()
274 //     }
275 // }
276
277 // From implies Into
278 #[stable(feature = "rust1", since = "1.0.0")]
279 impl<T, U> Into<U> for T where U: From<T> {
280     fn into(self) -> U {
281         U::from(self)
282     }
283 }
284
285 // From (and thus Into) is reflexive
286 #[stable(feature = "rust1", since = "1.0.0")]
287 impl<T> From<T> for T {
288     fn from(t: T) -> T { t }
289 }
290
291
292 // TryFrom implies TryInto
293 #[unstable(feature = "try_from", issue = "33417")]
294 impl<T, U> TryInto<U> for T where U: TryFrom<T> {
295     type Error = U::Error;
296
297     fn try_into(self) -> Result<U, U::Error> {
298         U::try_from(self)
299     }
300 }
301
302 ////////////////////////////////////////////////////////////////////////////////
303 // CONCRETE IMPLS
304 ////////////////////////////////////////////////////////////////////////////////
305
306 #[stable(feature = "rust1", since = "1.0.0")]
307 impl<T> AsRef<[T]> for [T] {
308     fn as_ref(&self) -> &[T] {
309         self
310     }
311 }
312
313 #[stable(feature = "rust1", since = "1.0.0")]
314 impl<T> AsMut<[T]> for [T] {
315     fn as_mut(&mut self) -> &mut [T] {
316         self
317     }
318 }
319
320 #[stable(feature = "rust1", since = "1.0.0")]
321 impl AsRef<str> for str {
322     #[inline]
323     fn as_ref(&self) -> &str {
324         self
325     }
326 }
327
328 // FromStr implies TryFrom<&str>
329 #[unstable(feature = "try_from", issue = "33417")]
330 impl<'a, T> TryFrom<&'a str> for T where T: FromStr {
331     type Error = <T as FromStr>::Err;
332
333     fn try_from(s: &'a str) -> Result<T, Self::Error> {
334         FromStr::from_str(s)
335     }
336 }