]> git.proxmox.com Git - rustc.git/blame - src/libcore/convert.rs
New upstream version 1.31.0~beta.4+dfsg1
[rustc.git] / src / libcore / convert.rs
CommitLineData
c34b1796
AL
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//!
62682a34
SL
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`.
9346a6ac 16//!
62682a34
SL
17//! Like many traits, these are often used as bounds for generic functions, to
18//! support arguments of multiple types.
9346a6ac 19//!
cc61c64b
XL
20//! - Implement the `As*` traits for reference-to-reference conversions
21//! - Implement the [`Into`] trait when you want to consume the value in the conversion
32a655c1
SL
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
a7813a04 24//! conversion to fail
7453a54e 25//!
32a655c1
SL
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
cc61c64b
XL
29//! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a
30//! blanket implementation in the standard library.
7453a54e 31//!
cc61c64b 32//! # Generic Implementations
7453a54e 33//!
32a655c1
SL
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`
cc61c64b
XL
37//! - [`From`] and [`Into`] are reflexive, which means that all types can
38//! `into` themselves and `from` themselves
7453a54e 39//!
9346a6ac 40//! See each trait for usage examples.
32a655c1
SL
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
c34b1796
AL
48
49#![stable(feature = "rust1", since = "1.0.0")]
50
b7449926
XL
51/// An identity function.
52///
53/// Two things are important to note about this function:
54///
55/// - It is not always equivalent to a closure like `|x| x` since the
56/// closure may coerce `x` into a different type.
57///
58/// - It moves the input `x` passed to the function.
59///
60/// While it might seem strange to have a function that just returns back the
61/// input, there are some interesting uses.
62///
63/// # Examples
64///
65/// Using `identity` to do nothing among other interesting functions:
66///
67/// ```rust
68/// #![feature(convert_id)]
69/// use std::convert::identity;
70///
71/// fn manipulation(x: u32) -> u32 {
72/// // Let's assume that this function does something interesting.
73/// x + 1
74/// }
75///
76/// let _arr = &[identity, manipulation];
77/// ```
78///
79/// Using `identity` to get a function that changes nothing in a conditional:
80///
81/// ```rust
82/// #![feature(convert_id)]
83/// use std::convert::identity;
84///
85/// # let condition = true;
86///
87/// # fn manipulation(x: u32) -> u32 { x + 1 }
88///
89/// let do_stuff = if condition { manipulation } else { identity };
90///
91/// // do more interesting stuff..
92///
93/// let _results = do_stuff(42);
94/// ```
95///
96/// Using `identity` to keep the `Some` variants of an iterator of `Option<T>`:
97///
98/// ```rust
99/// #![feature(convert_id)]
100/// use std::convert::identity;
101///
102/// let iter = vec![Some(1), None, Some(3)].into_iter();
103/// let filtered = iter.filter_map(identity).collect::<Vec<_>>();
104/// assert_eq!(vec![1, 3], filtered);
105/// ```
106#[unstable(feature = "convert_id", issue = "53500")]
107#[rustc_const_unstable(feature = "const_convert_id")]
108#[inline]
109pub const fn identity<T>(x: T) -> T { x }
110
cc61c64b
XL
111/// A cheap reference-to-reference conversion. Used to convert a value to a
112/// reference value within generic code.
113///
114/// `AsRef` is very similar to, but serves a slightly different purpose than,
115/// [`Borrow`].
116///
117/// `AsRef` is to be used when wishing to convert to a reference of another
118/// type.
119/// `Borrow` is more related to the notion of taking the reference. It is
120/// useful when wishing to abstract over the type of reference
121/// (`&T`, `&mut T`) or allow both the referenced and owned type to be treated
122/// in the same manner.
9346a6ac 123///
cc61c64b
XL
124/// The key difference between the two traits is the intention:
125///
8faf50e0
XL
126/// - Use `AsRef` when the goal is to simply convert into a reference
127/// - Use `Borrow` when the goal is related to writing code that is agnostic to
128/// the type of borrow and whether it is a reference or value
cc61c64b
XL
129///
130/// See [the book][book] for a more detailed comparison.
d9579d0f 131///
041b39d2 132/// [book]: ../../book/first-edition/borrow-and-asref.html
9e0c209e 133/// [`Borrow`]: ../../std/borrow/trait.Borrow.html
d9579d0f 134///
cc61c64b
XL
135/// **Note: this trait must not fail**. If the conversion can fail, use a
136/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
9e0c209e
SL
137///
138/// [`Option<T>`]: ../../std/option/enum.Option.html
139/// [`Result<T, E>`]: ../../std/result/enum.Result.html
7453a54e 140///
cc61c64b
XL
141/// # Generic Implementations
142///
143/// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
144/// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type
145/// `&mut Foo` or `&&mut Foo`)
146///
9346a6ac
AL
147/// # Examples
148///
9e0c209e
SL
149/// Both [`String`] and `&str` implement `AsRef<str>`:
150///
151/// [`String`]: ../../std/string/struct.String.html
9346a6ac
AL
152///
153/// ```
154/// fn is_hello<T: AsRef<str>>(s: T) {
155/// assert_eq!("hello", s.as_ref());
156/// }
157///
158/// let s = "hello";
159/// is_hello(s);
160///
161/// let s = "hello".to_string();
162/// is_hello(s);
163/// ```
7453a54e 164///
c34b1796
AL
165#[stable(feature = "rust1", since = "1.0.0")]
166pub trait AsRef<T: ?Sized> {
9346a6ac 167 /// Performs the conversion.
c34b1796
AL
168 #[stable(feature = "rust1", since = "1.0.0")]
169 fn as_ref(&self) -> &T;
170}
171
172/// A cheap, mutable reference-to-mutable reference conversion.
7453a54e 173///
cc61c64b
XL
174/// This trait is similar to `AsRef` but used for converting between mutable
175/// references.
176///
177/// **Note: this trait must not fail**. If the conversion can fail, use a
178/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
9e0c209e
SL
179///
180/// [`Option<T>`]: ../../std/option/enum.Option.html
181/// [`Result<T, E>`]: ../../std/result/enum.Result.html
182///
cc61c64b
XL
183/// # Generic Implementations
184///
2c00a5a8
XL
185/// - `AsMut` auto-dereferences if the inner type is a mutable reference
186/// (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo`
187/// or `&mut &mut Foo`)
cc61c64b 188///
9e0c209e
SL
189/// # Examples
190///
191/// [`Box<T>`] implements `AsMut<T>`:
192///
193/// [`Box<T>`]: ../../std/boxed/struct.Box.html
194///
195/// ```
196/// fn add_one<T: AsMut<u64>>(num: &mut T) {
197/// *num.as_mut() += 1;
198/// }
199///
200/// let mut boxed_num = Box::new(0);
201/// add_one(&mut boxed_num);
202/// assert_eq!(*boxed_num, 1);
203/// ```
7453a54e 204///
7453a54e 205///
c34b1796
AL
206#[stable(feature = "rust1", since = "1.0.0")]
207pub trait AsMut<T: ?Sized> {
9346a6ac 208 /// Performs the conversion.
c34b1796
AL
209 #[stable(feature = "rust1", since = "1.0.0")]
210 fn as_mut(&mut self) -> &mut T;
211}
212
cc61c64b
XL
213/// A conversion that consumes `self`, which may or may not be expensive. The
214/// reciprocal of [`From`][From].
215///
216/// **Note: this trait must not fail**. If the conversion can fail, use
217/// [`TryInto`] or a dedicated method which returns an [`Option<T>`] or a
218/// [`Result<T, E>`].
9346a6ac 219///
cc61c64b
XL
220/// Library authors should not directly implement this trait, but should prefer
221/// implementing the [`From`][From] trait, which offers greater flexibility and
222/// provides an equivalent `Into` implementation for free, thanks to a blanket
223/// implementation in the standard library.
7453a54e 224///
cc61c64b
XL
225/// # Generic Implementations
226///
227/// - [`From<T>`][From]` for U` implies `Into<U> for T`
228/// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
7453a54e 229///
7cac9316
XL
230/// # Implementing `Into`
231///
232/// There is one exception to implementing `Into`, and it's kind of esoteric.
233/// If the destination type is not part of the current crate, and it uses a
234/// generic variable, then you can't implement `From` directly. For example,
235/// take this crate:
236///
237/// ```compile_fail
238/// struct Wrapper<T>(Vec<T>);
239/// impl<T> From<Wrapper<T>> for Vec<T> {
240/// fn from(w: Wrapper<T>) -> Vec<T> {
241/// w.0
242/// }
243/// }
244/// ```
245///
246/// To fix this, you can implement `Into` directly:
247///
248/// ```
249/// struct Wrapper<T>(Vec<T>);
250/// impl<T> Into<Vec<T>> for Wrapper<T> {
251/// fn into(self) -> Vec<T> {
252/// self.0
253/// }
254/// }
255/// ```
256///
257/// This won't always allow the conversion: for example, `try!` and `?`
258/// always use `From`. However, in most cases, people use `Into` to do the
259/// conversions, and this will allow that.
260///
261/// In almost all cases, you should try to implement `From`, then fall back
262/// to `Into` if `From` can't be implemented.
263///
9346a6ac
AL
264/// # Examples
265///
9e0c209e 266/// [`String`] implements `Into<Vec<u8>>`:
9346a6ac
AL
267///
268/// ```
269/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
270/// let bytes = b"hello".to_vec();
271/// assert_eq!(bytes, s.into());
272/// }
273///
274/// let s = "hello".to_string();
275/// is_hello(s);
276/// ```
7453a54e 277///
9e0c209e
SL
278/// [`TryInto`]: trait.TryInto.html
279/// [`Option<T>`]: ../../std/option/enum.Option.html
280/// [`Result<T, E>`]: ../../std/result/enum.Result.html
281/// [`String`]: ../../std/string/struct.String.html
282/// [From]: trait.From.html
cc61c64b 283/// [`into`]: trait.Into.html#tymethod.into
c34b1796
AL
284#[stable(feature = "rust1", since = "1.0.0")]
285pub trait Into<T>: Sized {
9346a6ac 286 /// Performs the conversion.
c34b1796
AL
287 #[stable(feature = "rust1", since = "1.0.0")]
288 fn into(self) -> T;
289}
290
cc61c64b
XL
291/// Simple and safe type conversions in to `Self`. It is the reciprocal of
292/// `Into`.
293///
294/// This trait is useful when performing error handling as described by
295/// [the book][book] and is closely related to the `?` operator.
9346a6ac 296///
cc61c64b
XL
297/// When constructing a function that is capable of failing the return type
298/// will generally be of the form `Result<T, E>`.
299///
300/// The `From` trait allows for simplification of error handling by providing a
301/// means of returning a single error type that encapsulates numerous possible
302/// erroneous situations.
303///
304/// This trait is not limited to error handling, rather the general case for
305/// this trait would be in any type conversions to have an explicit definition
306/// of how they are performed.
307///
308/// **Note: this trait must not fail**. If the conversion can fail, use
309/// [`TryFrom`] or a dedicated method which returns an [`Option<T>`] or a
310/// [`Result<T, E>`].
311///
312/// # Generic Implementations
313///
314/// - `From<T> for U` implies [`Into<U>`]` for T`
315/// - [`from`] is reflexive, which means that `From<T> for T` is implemented
7453a54e 316///
9346a6ac
AL
317/// # Examples
318///
9e0c209e 319/// [`String`] implements `From<&str>`:
9346a6ac
AL
320///
321/// ```
9346a6ac 322/// let string = "hello".to_string();
bd371182 323/// let other_string = String::from("hello");
9346a6ac
AL
324///
325/// assert_eq!(string, other_string);
326/// ```
7453a54e 327///
cc61c64b
XL
328/// An example usage for error handling:
329///
330/// ```
331/// use std::io::{self, Read};
332/// use std::num;
333///
334/// enum CliError {
335/// IoError(io::Error),
336/// ParseError(num::ParseIntError),
337/// }
338///
339/// impl From<io::Error> for CliError {
340/// fn from(error: io::Error) -> Self {
341/// CliError::IoError(error)
342/// }
343/// }
344///
345/// impl From<num::ParseIntError> for CliError {
346/// fn from(error: num::ParseIntError) -> Self {
347/// CliError::ParseError(error)
348/// }
349/// }
350///
351/// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
352/// let mut file = std::fs::File::open("test")?;
353/// let mut contents = String::new();
354/// file.read_to_string(&mut contents)?;
355/// let num: i32 = contents.trim().parse()?;
356/// Ok(num)
357/// }
358/// ```
7453a54e 359///
9e0c209e
SL
360/// [`TryFrom`]: trait.TryFrom.html
361/// [`Option<T>`]: ../../std/option/enum.Option.html
362/// [`Result<T, E>`]: ../../std/result/enum.Result.html
363/// [`String`]: ../../std/string/struct.String.html
c30ab7b3 364/// [`Into<U>`]: trait.Into.html
cc61c64b 365/// [`from`]: trait.From.html#tymethod.from
041b39d2 366/// [book]: ../../book/first-edition/error-handling.html
c34b1796 367#[stable(feature = "rust1", since = "1.0.0")]
b039eaaf 368pub trait From<T>: Sized {
9346a6ac 369 /// Performs the conversion.
c34b1796 370 #[stable(feature = "rust1", since = "1.0.0")]
7cac9316 371 fn from(_: T) -> Self;
c34b1796
AL
372}
373
cc61c64b
XL
374/// An attempted conversion that consumes `self`, which may or may not be
375/// expensive.
a7813a04 376///
cc61c64b
XL
377/// Library authors should not directly implement this trait, but should prefer
378/// implementing the [`TryFrom`] trait, which offers greater flexibility and
379/// provides an equivalent `TryInto` implementation for free, thanks to a
7cac9316
XL
380/// blanket implementation in the standard library. For more information on this,
381/// see the documentation for [`Into`].
9e0c209e
SL
382///
383/// [`TryFrom`]: trait.TryFrom.html
7cac9316 384/// [`Into`]: trait.Into.html
a7813a04
XL
385#[unstable(feature = "try_from", issue = "33417")]
386pub trait TryInto<T>: Sized {
387 /// The type returned in the event of a conversion error.
cc61c64b 388 type Error;
a7813a04
XL
389
390 /// Performs the conversion.
cc61c64b 391 fn try_into(self) -> Result<T, Self::Error>;
a7813a04
XL
392}
393
394/// Attempt to construct `Self` via a conversion.
395#[unstable(feature = "try_from", issue = "33417")]
396pub trait TryFrom<T>: Sized {
397 /// The type returned in the event of a conversion error.
cc61c64b 398 type Error;
a7813a04
XL
399
400 /// Performs the conversion.
cc61c64b 401 fn try_from(value: T) -> Result<Self, Self::Error>;
a7813a04
XL
402}
403
c34b1796
AL
404////////////////////////////////////////////////////////////////////////////////
405// GENERIC IMPLS
406////////////////////////////////////////////////////////////////////////////////
407
408// As lifts over &
409#[stable(feature = "rust1", since = "1.0.0")]
0bf4aa26 410impl<T: ?Sized, U: ?Sized> AsRef<U> for &T where T: AsRef<U>
cc61c64b 411{
c34b1796
AL
412 fn as_ref(&self) -> &U {
413 <T as AsRef<U>>::as_ref(*self)
414 }
415}
416
417// As lifts over &mut
418#[stable(feature = "rust1", since = "1.0.0")]
0bf4aa26 419impl<T: ?Sized, U: ?Sized> AsRef<U> for &mut T where T: AsRef<U>
cc61c64b 420{
c34b1796
AL
421 fn as_ref(&self) -> &U {
422 <T as AsRef<U>>::as_ref(*self)
423 }
424}
425
0531ce1d 426// FIXME (#45742): replace the above impls for &/&mut with the following more general one:
c34b1796
AL
427// // As lifts over Deref
428// impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
429// fn as_ref(&self) -> &U {
430// self.deref().as_ref()
431// }
432// }
433
434// AsMut lifts over &mut
435#[stable(feature = "rust1", since = "1.0.0")]
0bf4aa26 436impl<T: ?Sized, U: ?Sized> AsMut<U> for &mut T where T: AsMut<U>
cc61c64b 437{
c34b1796
AL
438 fn as_mut(&mut self) -> &mut U {
439 (*self).as_mut()
440 }
441}
442
0531ce1d 443// FIXME (#45742): replace the above impl for &mut with the following more general one:
c34b1796
AL
444// // AsMut lifts over DerefMut
445// impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
446// fn as_mut(&mut self) -> &mut U {
447// self.deref_mut().as_mut()
448// }
449// }
450
451// From implies Into
452#[stable(feature = "rust1", since = "1.0.0")]
cc61c64b
XL
453impl<T, U> Into<U> for T where U: From<T>
454{
c34b1796
AL
455 fn into(self) -> U {
456 U::from(self)
457 }
458}
459
460// From (and thus Into) is reflexive
461#[stable(feature = "rust1", since = "1.0.0")]
462impl<T> From<T> for T {
463 fn from(t: T) -> T { t }
464}
465
a7813a04
XL
466
467// TryFrom implies TryInto
468#[unstable(feature = "try_from", issue = "33417")]
cc61c64b
XL
469impl<T, U> TryInto<U> for T where U: TryFrom<T>
470{
471 type Error = U::Error;
a7813a04 472
cc61c64b 473 fn try_into(self) -> Result<U, U::Error> {
a7813a04
XL
474 U::try_from(self)
475 }
476}
477
ea8adc8c
XL
478// Infallible conversions are semantically equivalent to fallible conversions
479// with an uninhabited error type.
480#[unstable(feature = "try_from", issue = "33417")]
481impl<T, U> TryFrom<U> for T where T: From<U> {
0531ce1d 482 type Error = !;
ea8adc8c
XL
483
484 fn try_from(value: U) -> Result<Self, Self::Error> {
485 Ok(T::from(value))
486 }
487}
488
c34b1796
AL
489////////////////////////////////////////////////////////////////////////////////
490// CONCRETE IMPLS
491////////////////////////////////////////////////////////////////////////////////
492
493#[stable(feature = "rust1", since = "1.0.0")]
494impl<T> AsRef<[T]> for [T] {
495 fn as_ref(&self) -> &[T] {
496 self
497 }
498}
499
500#[stable(feature = "rust1", since = "1.0.0")]
501impl<T> AsMut<[T]> for [T] {
502 fn as_mut(&mut self) -> &mut [T] {
503 self
504 }
505}
506
507#[stable(feature = "rust1", since = "1.0.0")]
508impl AsRef<str> for str {
d9579d0f 509 #[inline]
c34b1796
AL
510 fn as_ref(&self) -> &str {
511 self
512 }
513}