core/convert/mod.rs
1//! Traits for conversions between types.
2//!
3//! The traits in this module provide a way to convert from one type to another type.
4//! Each trait serves a different purpose:
5//!
6//! - Implement the [`AsRef`] trait for cheap reference-to-reference conversions
7//! - Implement the [`AsMut`] trait for cheap mutable-to-mutable conversions
8//! - Implement the [`From`] trait for consuming value-to-value conversions
9//! - Implement the [`Into`] trait for consuming value-to-value conversions to types
10//!   outside the current crate
11//! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`],
12//!   but should be implemented when the conversion can fail.
13//!
14//! The traits in this module are often used as trait bounds for generic functions such that to
15//! arguments of multiple types are supported. See the documentation of each trait for examples.
16//!
17//! As a library author, you should always prefer implementing [`From<T>`][`From`] or
18//! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
19//! as [`From`] and [`TryFrom`] provide greater flexibility and offer
20//! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a
21//! blanket implementation in the standard library. When targeting a version prior to Rust 1.41, it
22//! may be necessary to implement [`Into`] or [`TryInto`] directly when converting to a type
23//! outside the current crate.
24//!
25//! # Generic Implementations
26//!
27//! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference
28//!   (but not generally for all [dereferenceable types][core::ops::Deref])
29//! - [`From`]`<U> for T` implies [`Into`]`<T> for U`
30//! - [`TryFrom`]`<U> for T` implies [`TryInto`]`<T> for U`
31//! - [`From`] and [`Into`] are reflexive, which means that all types can
32//!   `into` themselves and `from` themselves
33//!
34//! See each trait for usage examples.
35
36#![stable(feature = "rust1", since = "1.0.0")]
37
38#[cfg(not(feature = "ferrocene_certified"))]
39use crate::error::Error;
40#[cfg(not(feature = "ferrocene_certified"))]
41use crate::fmt;
42#[cfg(not(feature = "ferrocene_certified"))]
43use crate::hash::{Hash, Hasher};
44use crate::marker::PointeeSized;
45
46mod num;
47
48#[unstable(feature = "convert_float_to_int", issue = "67057")]
49#[cfg(not(feature = "ferrocene_certified"))]
50pub use num::FloatToInt;
51
52/// The identity function.
53///
54/// Two things are important to note about this function:
55///
56/// - It is not always equivalent to a closure like `|x| x`, since the
57///   closure may coerce `x` into a different type.
58///
59/// - It moves the input `x` passed to the function.
60///
61/// While it might seem strange to have a function that just returns back the
62/// input, there are some interesting uses.
63///
64/// # Examples
65///
66/// Using `identity` to do nothing in a sequence of other, interesting,
67/// functions:
68///
69/// ```rust
70/// use std::convert::identity;
71///
72/// fn manipulation(x: u32) -> u32 {
73///     // Let's pretend that adding one is an interesting function.
74///     x + 1
75/// }
76///
77/// let _arr = &[identity, manipulation];
78/// ```
79///
80/// Using `identity` as a "do nothing" base case in a conditional:
81///
82/// ```rust
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/// use std::convert::identity;
100///
101/// let iter = [Some(1), None, Some(3)].into_iter();
102/// let filtered = iter.filter_map(identity).collect::<Vec<_>>();
103/// assert_eq!(vec![1, 3], filtered);
104/// ```
105#[stable(feature = "convert_id", since = "1.33.0")]
106#[rustc_const_stable(feature = "const_identity", since = "1.33.0")]
107#[inline(always)]
108#[rustc_diagnostic_item = "convert_identity"]
109pub const fn identity<T>(x: T) -> T {
110    x
111}
112
113/// Used to do a cheap reference-to-reference conversion.
114///
115/// This trait is similar to [`AsMut`] which is used for converting between mutable references.
116/// If you need to do a costly conversion it is better to implement [`From`] with type
117/// `&T` or write a custom function.
118///
119/// # Relation to `Borrow`
120///
121/// `AsRef` has the same signature as [`Borrow`], but [`Borrow`] is different in a few aspects:
122///
123/// - Unlike `AsRef`, [`Borrow`] has a blanket impl for any `T`, and can be used to accept either
124///   a reference or a value. (See also note on `AsRef`'s reflexibility below.)
125/// - [`Borrow`] also requires that [`Hash`], [`Eq`] and [`Ord`] for a borrowed value are
126///   equivalent to those of the owned value. For this reason, if you want to
127///   borrow only a single field of a struct you can implement `AsRef`, but not [`Borrow`].
128///
129/// **Note: This trait must not fail**. If the conversion can fail, use a
130/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
131///
132/// # Generic Implementations
133///
134/// `AsRef` auto-dereferences if the inner type is a reference or a mutable reference
135/// (e.g.: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`).
136///
137/// Note that due to historic reasons, the above currently does not hold generally for all
138/// [dereferenceable types], e.g. `foo.as_ref()` will *not* work the same as
139/// `Box::new(foo).as_ref()`. Instead, many smart pointers provide an `as_ref` implementation which
140/// simply returns a reference to the [pointed-to value] (but do not perform a cheap
141/// reference-to-reference conversion for that value). However, [`AsRef::as_ref`] should not be
142/// used for the sole purpose of dereferencing; instead ['`Deref` coercion'] can be used:
143///
144/// [dereferenceable types]: core::ops::Deref
145/// [pointed-to value]: core::ops::Deref::Target
146/// ['`Deref` coercion']: core::ops::Deref#deref-coercion
147///
148/// ```
149/// let x = Box::new(5i32);
150/// // Avoid this:
151/// // let y: &i32 = x.as_ref();
152/// // Better just write:
153/// let y: &i32 = &x;
154/// ```
155///
156/// Types which implement [`Deref`] should consider implementing `AsRef<T>` as follows:
157///
158/// [`Deref`]: core::ops::Deref
159///
160/// ```
161/// # use core::ops::Deref;
162/// # struct SomeType;
163/// # impl Deref for SomeType {
164/// #     type Target = [u8];
165/// #     fn deref(&self) -> &[u8] {
166/// #         &[]
167/// #     }
168/// # }
169/// impl<T> AsRef<T> for SomeType
170/// where
171///     T: ?Sized,
172///     <SomeType as Deref>::Target: AsRef<T>,
173/// {
174///     fn as_ref(&self) -> &T {
175///         self.deref().as_ref()
176///     }
177/// }
178/// ```
179///
180/// # Reflexivity
181///
182/// Ideally, `AsRef` would be reflexive, i.e. there would be an `impl<T: ?Sized> AsRef<T> for T`
183/// with [`as_ref`] simply returning its argument unchanged.
184/// Such a blanket implementation is currently *not* provided due to technical restrictions of
185/// Rust's type system (it would be overlapping with another existing blanket implementation for
186/// `&T where T: AsRef<U>` which allows `AsRef` to auto-dereference, see "Generic Implementations"
187/// above).
188///
189/// [`as_ref`]: AsRef::as_ref
190///
191/// A trivial implementation of `AsRef<T> for T` must be added explicitly for a particular type `T`
192/// where needed or desired. Note, however, that not all types from `std` contain such an
193/// implementation, and those cannot be added by external code due to orphan rules.
194///
195/// # Examples
196///
197/// By using trait bounds we can accept arguments of different types as long as they can be
198/// converted to the specified type `T`.
199///
200/// For example: By creating a generic function that takes an `AsRef<str>` we express that we
201/// want to accept all references that can be converted to [`&str`] as an argument.
202/// Since both [`String`] and [`&str`] implement `AsRef<str>` we can accept both as input argument.
203///
204/// [`&str`]: primitive@str
205/// [`Borrow`]: crate::borrow::Borrow
206/// [`Eq`]: crate::cmp::Eq
207/// [`Ord`]: crate::cmp::Ord
208/// [`String`]: ../../std/string/struct.String.html
209///
210/// ```
211/// fn is_hello<T: AsRef<str>>(s: T) {
212///    assert_eq!("hello", s.as_ref());
213/// }
214///
215/// let s = "hello";
216/// is_hello(s);
217///
218/// let s = "hello".to_string();
219/// is_hello(s);
220/// ```
221#[stable(feature = "rust1", since = "1.0.0")]
222#[rustc_diagnostic_item = "AsRef"]
223#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
224pub const trait AsRef<T: PointeeSized>: PointeeSized {
225    /// Converts this type into a shared reference of the (usually inferred) input type.
226    #[stable(feature = "rust1", since = "1.0.0")]
227    fn as_ref(&self) -> &T;
228}
229
230/// Used to do a cheap mutable-to-mutable reference conversion.
231///
232/// This trait is similar to [`AsRef`] but used for converting between mutable
233/// references. If you need to do a costly conversion it is better to
234/// implement [`From`] with type `&mut T` or write a custom function.
235///
236/// **Note: This trait must not fail**. If the conversion can fail, use a
237/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
238///
239/// # Generic Implementations
240///
241/// `AsMut` auto-dereferences if the inner type is a mutable reference
242/// (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo` or `&mut &mut Foo`).
243///
244/// Note that due to historic reasons, the above currently does not hold generally for all
245/// [mutably dereferenceable types], e.g. `foo.as_mut()` will *not* work the same as
246/// `Box::new(foo).as_mut()`. Instead, many smart pointers provide an `as_mut` implementation which
247/// simply returns a reference to the [pointed-to value] (but do not perform a cheap
248/// reference-to-reference conversion for that value). However, [`AsMut::as_mut`] should not be
249/// used for the sole purpose of mutable dereferencing; instead ['`Deref` coercion'] can be used:
250///
251/// [mutably dereferenceable types]: core::ops::DerefMut
252/// [pointed-to value]: core::ops::Deref::Target
253/// ['`Deref` coercion']: core::ops::DerefMut#mutable-deref-coercion
254///
255/// ```
256/// let mut x = Box::new(5i32);
257/// // Avoid this:
258/// // let y: &mut i32 = x.as_mut();
259/// // Better just write:
260/// let y: &mut i32 = &mut x;
261/// ```
262///
263/// Types which implement [`DerefMut`] should consider to add an implementation of `AsMut<T>` as
264/// follows:
265///
266/// [`DerefMut`]: core::ops::DerefMut
267///
268/// ```
269/// # use core::ops::{Deref, DerefMut};
270/// # struct SomeType;
271/// # impl Deref for SomeType {
272/// #     type Target = [u8];
273/// #     fn deref(&self) -> &[u8] {
274/// #         &[]
275/// #     }
276/// # }
277/// # impl DerefMut for SomeType {
278/// #     fn deref_mut(&mut self) -> &mut [u8] {
279/// #         &mut []
280/// #     }
281/// # }
282/// impl<T> AsMut<T> for SomeType
283/// where
284///     <SomeType as Deref>::Target: AsMut<T>,
285/// {
286///     fn as_mut(&mut self) -> &mut T {
287///         self.deref_mut().as_mut()
288///     }
289/// }
290/// ```
291///
292/// # Reflexivity
293///
294/// Ideally, `AsMut` would be reflexive, i.e. there would be an `impl<T: ?Sized> AsMut<T> for T`
295/// with [`as_mut`] simply returning its argument unchanged.
296/// Such a blanket implementation is currently *not* provided due to technical restrictions of
297/// Rust's type system (it would be overlapping with another existing blanket implementation for
298/// `&mut T where T: AsMut<U>` which allows `AsMut` to auto-dereference, see "Generic
299/// Implementations" above).
300///
301/// [`as_mut`]: AsMut::as_mut
302///
303/// A trivial implementation of `AsMut<T> for T` must be added explicitly for a particular type `T`
304/// where needed or desired. Note, however, that not all types from `std` contain such an
305/// implementation, and those cannot be added by external code due to orphan rules.
306///
307/// # Examples
308///
309/// Using `AsMut` as trait bound for a generic function, we can accept all mutable references that
310/// can be converted to type `&mut T`. Unlike [dereference], which has a single [target type],
311/// there can be multiple implementations of `AsMut` for a type. In particular, `Vec<T>` implements
312/// both `AsMut<Vec<T>>` and `AsMut<[T]>`.
313///
314/// In the following, the example functions `caesar` and `null_terminate` provide a generic
315/// interface which work with any type that can be converted by cheap mutable-to-mutable conversion
316/// into a byte slice (`[u8]`) or byte vector (`Vec<u8>`), respectively.
317///
318/// [dereference]: core::ops::DerefMut
319/// [target type]: core::ops::Deref::Target
320///
321/// ```
322/// struct Document {
323///     info: String,
324///     content: Vec<u8>,
325/// }
326///
327/// impl<T: ?Sized> AsMut<T> for Document
328/// where
329///     Vec<u8>: AsMut<T>,
330/// {
331///     fn as_mut(&mut self) -> &mut T {
332///         self.content.as_mut()
333///     }
334/// }
335///
336/// fn caesar<T: AsMut<[u8]>>(data: &mut T, key: u8) {
337///     for byte in data.as_mut() {
338///         *byte = byte.wrapping_add(key);
339///     }
340/// }
341///
342/// fn null_terminate<T: AsMut<Vec<u8>>>(data: &mut T) {
343///     // Using a non-generic inner function, which contains most of the
344///     // functionality, helps to minimize monomorphization overhead.
345///     fn doit(data: &mut Vec<u8>) {
346///         let len = data.len();
347///         if len == 0 || data[len-1] != 0 {
348///             data.push(0);
349///         }
350///     }
351///     doit(data.as_mut());
352/// }
353///
354/// fn main() {
355///     let mut v: Vec<u8> = vec![1, 2, 3];
356///     caesar(&mut v, 5);
357///     assert_eq!(v, [6, 7, 8]);
358///     null_terminate(&mut v);
359///     assert_eq!(v, [6, 7, 8, 0]);
360///     let mut doc = Document {
361///         info: String::from("Example"),
362///         content: vec![17, 19, 8],
363///     };
364///     caesar(&mut doc, 1);
365///     assert_eq!(doc.content, [18, 20, 9]);
366///     null_terminate(&mut doc);
367///     assert_eq!(doc.content, [18, 20, 9, 0]);
368/// }
369/// ```
370///
371/// Note, however, that APIs don't need to be generic. In many cases taking a `&mut [u8]` or
372/// `&mut Vec<u8>`, for example, is the better choice (callers need to pass the correct type then).
373#[stable(feature = "rust1", since = "1.0.0")]
374#[rustc_diagnostic_item = "AsMut"]
375#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
376pub const trait AsMut<T: PointeeSized>: PointeeSized {
377    /// Converts this type into a mutable reference of the (usually inferred) input type.
378    #[stable(feature = "rust1", since = "1.0.0")]
379    fn as_mut(&mut self) -> &mut T;
380}
381
382/// A value-to-value conversion that consumes the input value. The
383/// opposite of [`From`].
384///
385/// One should avoid implementing [`Into`] and implement [`From`] instead.
386/// Implementing [`From`] automatically provides one with an implementation of [`Into`]
387/// thanks to the blanket implementation in the standard library.
388///
389/// Prefer using [`Into`] over [`From`] when specifying trait bounds on a generic function
390/// to ensure that types that only implement [`Into`] can be used as well.
391///
392/// **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`].
393///
394/// # Generic Implementations
395///
396/// - [`From`]`<T> for U` implies `Into<U> for T`
397/// - [`Into`] is reflexive, which means that `Into<T> for T` is implemented
398///
399/// # Implementing [`Into`] for conversions to external types in old versions of Rust
400///
401/// Prior to Rust 1.41, if the destination type was not part of the current crate
402/// then you couldn't implement [`From`] directly.
403/// For example, take this code:
404///
405/// ```
406/// # #![allow(non_local_definitions)]
407/// struct Wrapper<T>(Vec<T>);
408/// impl<T> From<Wrapper<T>> for Vec<T> {
409///     fn from(w: Wrapper<T>) -> Vec<T> {
410///         w.0
411///     }
412/// }
413/// ```
414/// This will fail to compile in older versions of the language because Rust's orphaning rules
415/// used to be a little bit more strict. To bypass this, you could implement [`Into`] directly:
416///
417/// ```
418/// struct Wrapper<T>(Vec<T>);
419/// impl<T> Into<Vec<T>> for Wrapper<T> {
420///     fn into(self) -> Vec<T> {
421///         self.0
422///     }
423/// }
424/// ```
425///
426/// It is important to understand that [`Into`] does not provide a [`From`] implementation
427/// (as [`From`] does with [`Into`]). Therefore, you should always try to implement [`From`]
428/// and then fall back to [`Into`] if [`From`] can't be implemented.
429///
430/// # Examples
431///
432/// [`String`] implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>`:
433///
434/// In order to express that we want a generic function to take all arguments that can be
435/// converted to a specified type `T`, we can use a trait bound of [`Into`]`<T>`.
436/// For example: The function `is_hello` takes all arguments that can be converted into a
437/// [`Vec`]`<`[`u8`]`>`.
438///
439/// ```
440/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
441///    let bytes = b"hello".to_vec();
442///    assert_eq!(bytes, s.into());
443/// }
444///
445/// let s = "hello".to_string();
446/// is_hello(s);
447/// ```
448///
449/// [`String`]: ../../std/string/struct.String.html
450/// [`Vec`]: ../../std/vec/struct.Vec.html
451#[rustc_diagnostic_item = "Into"]
452#[stable(feature = "rust1", since = "1.0.0")]
453#[doc(search_unbox)]
454#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
455pub const trait Into<T>: Sized {
456    /// Converts this type into the (usually inferred) input type.
457    #[must_use]
458    #[stable(feature = "rust1", since = "1.0.0")]
459    fn into(self) -> T;
460}
461
462/// Used to do value-to-value conversions while consuming the input value. It is the reciprocal of
463/// [`Into`].
464///
465/// One should always prefer implementing `From` over [`Into`]
466/// because implementing `From` automatically provides one with an implementation of [`Into`]
467/// thanks to the blanket implementation in the standard library.
468///
469/// Only implement [`Into`] when targeting a version prior to Rust 1.41 and converting to a type
470/// outside the current crate.
471/// `From` was not able to do these types of conversions in earlier versions because of Rust's
472/// orphaning rules.
473/// See [`Into`] for more details.
474///
475/// Prefer using [`Into`] over [`From`] when specifying trait bounds on a generic function
476/// to ensure that types that only implement [`Into`] can be used as well.
477///
478/// The `From` trait is also very useful when performing error handling. When constructing a function
479/// that is capable of failing, the return type will generally be of the form `Result<T, E>`.
480/// `From` simplifies error handling by allowing a function to return a single error type
481/// that encapsulates multiple error types. See the "Examples" section and [the book][book] for more
482/// details.
483///
484/// **Note: This trait must not fail**. The `From` trait is intended for perfect conversions.
485/// If the conversion can fail or is not perfect, use [`TryFrom`].
486///
487/// # Generic Implementations
488///
489/// - `From<T> for U` implies [`Into`]`<U> for T`
490/// - `From` is reflexive, which means that `From<T> for T` is implemented
491///
492/// # When to implement `From`
493///
494/// While there's no technical restrictions on which conversions can be done using
495/// a `From` implementation, the general expectation is that the conversions
496/// should typically be restricted as follows:
497///
498/// * The conversion is *infallible*: if the conversion can fail, use [`TryFrom`]
499///   instead; don't provide a `From` impl that panics.
500///
501/// * The conversion is *lossless*: semantically, it should not lose or discard
502///   information. For example, `i32: From<u16>` exists, where the original
503///   value can be recovered using `u16: TryFrom<i32>`.  And `String: From<&str>`
504///   exists, where you can get something equivalent to the original value via
505///   `Deref`.  But `From` cannot be used to convert from `u32` to `u16`, since
506///   that cannot succeed in a lossless way.  (There's some wiggle room here for
507///   information not considered semantically relevant.  For example,
508///   `Box<[T]>: From<Vec<T>>` exists even though it might not preserve capacity,
509///   like how two vectors can be equal despite differing capacities.)
510///
511/// * The conversion is *value-preserving*: the conceptual kind and meaning of
512///   the resulting value is the same, even though the Rust type and technical
513///   representation might be different.  For example `-1_i8 as u8` is *lossless*,
514///   since `as` casting back can recover the original value, but that conversion
515///   is *not* available via `From` because `-1` and `255` are different conceptual
516///   values (despite being identical bit patterns technically).  But
517///   `f32: From<i16>` *is* available because `1_i16` and `1.0_f32` are conceptually
518///   the same real number (despite having very different bit patterns technically).
519///   `String: From<char>` is available because they're both *text*, but
520///   `String: From<u32>` is *not* available, since `1` (a number) and `"1"`
521///   (text) are too different.  (Converting values to text is instead covered
522///   by the [`Display`](crate::fmt::Display) trait.)
523///
524/// * The conversion is *obvious*: it's the only reasonable conversion between
525///   the two types.  Otherwise it's better to have it be a named method or
526///   constructor, like how [`str::as_bytes`] is a method and how integers have
527///   methods like [`u32::from_ne_bytes`], [`u32::from_le_bytes`], and
528///   [`u32::from_be_bytes`], none of which are `From` implementations.  Whereas
529///   there's only one reasonable way to wrap an [`Ipv6Addr`](crate::net::Ipv6Addr)
530///   into an [`IpAddr`](crate::net::IpAddr), thus `IpAddr: From<Ipv6Addr>` exists.
531///
532/// # Examples
533///
534/// [`String`] implements `From<&str>`:
535///
536/// An explicit conversion from a `&str` to a String is done as follows:
537///
538/// ```
539/// let string = "hello".to_string();
540/// let other_string = String::from("hello");
541///
542/// assert_eq!(string, other_string);
543/// ```
544///
545/// While performing error handling it is often useful to implement `From` for your own error type.
546/// By converting underlying error types to our own custom error type that encapsulates the
547/// underlying error type, we can return a single error type without losing information on the
548/// underlying cause. The '?' operator automatically converts the underlying error type to our
549/// custom error type with `From::from`.
550///
551/// ```
552/// use std::fs;
553/// use std::io;
554/// use std::num;
555///
556/// enum CliError {
557///     IoError(io::Error),
558///     ParseError(num::ParseIntError),
559/// }
560///
561/// impl From<io::Error> for CliError {
562///     fn from(error: io::Error) -> Self {
563///         CliError::IoError(error)
564///     }
565/// }
566///
567/// impl From<num::ParseIntError> for CliError {
568///     fn from(error: num::ParseIntError) -> Self {
569///         CliError::ParseError(error)
570///     }
571/// }
572///
573/// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
574///     let mut contents = fs::read_to_string(&file_name)?;
575///     let num: i32 = contents.trim().parse()?;
576///     Ok(num)
577/// }
578/// ```
579///
580/// [`String`]: ../../std/string/struct.String.html
581/// [`from`]: From::from
582/// [book]: ../../book/ch09-00-error-handling.html
583#[rustc_diagnostic_item = "From"]
584#[stable(feature = "rust1", since = "1.0.0")]
585#[rustc_on_unimplemented(on(
586    all(Self = "&str", T = "alloc::string::String"),
587    note = "to coerce a `{T}` into a `{Self}`, use `&*` as a prefix",
588))]
589#[doc(search_unbox)]
590#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
591pub const trait From<T>: Sized {
592    /// Converts to this type from the input type.
593    #[rustc_diagnostic_item = "from_fn"]
594    #[must_use]
595    #[stable(feature = "rust1", since = "1.0.0")]
596    fn from(value: T) -> Self;
597}
598
599/// An attempted conversion that consumes `self`, which may or may not be
600/// expensive.
601///
602/// Library authors should usually not directly implement this trait,
603/// but should prefer implementing the [`TryFrom`] trait, which offers
604/// greater flexibility and provides an equivalent `TryInto`
605/// implementation for free, thanks to a blanket implementation in the
606/// standard library. For more information on this, see the
607/// documentation for [`Into`].
608///
609/// Prefer using [`TryInto`] over [`TryFrom`] when specifying trait bounds on a generic function
610/// to ensure that types that only implement [`TryInto`] can be used as well.
611///
612/// # Implementing `TryInto`
613///
614/// This suffers the same restrictions and reasoning as implementing
615/// [`Into`], see there for details.
616#[rustc_diagnostic_item = "TryInto"]
617#[stable(feature = "try_from", since = "1.34.0")]
618#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
619pub const trait TryInto<T>: Sized {
620    /// The type returned in the event of a conversion error.
621    #[stable(feature = "try_from", since = "1.34.0")]
622    type Error;
623
624    /// Performs the conversion.
625    #[stable(feature = "try_from", since = "1.34.0")]
626    fn try_into(self) -> Result<T, Self::Error>;
627}
628
629/// Simple and safe type conversions that may fail in a controlled
630/// way under some circumstances. It is the reciprocal of [`TryInto`].
631///
632/// This is useful when you are doing a type conversion that may
633/// trivially succeed but may also need special handling.
634/// For example, there is no way to convert an [`i64`] into an [`i32`]
635/// using the [`From`] trait, because an [`i64`] may contain a value
636/// that an [`i32`] cannot represent and so the conversion would lose data.
637/// This might be handled by truncating the [`i64`] to an [`i32`] or by
638/// simply returning [`i32::MAX`], or by some other method.  The [`From`]
639/// trait is intended for perfect conversions, so the `TryFrom` trait
640/// informs the programmer when a type conversion could go bad and lets
641/// them decide how to handle it.
642///
643/// # Generic Implementations
644///
645/// - `TryFrom<T> for U` implies [`TryInto`]`<U> for T`
646/// - [`try_from`] is reflexive, which means that `TryFrom<T> for T`
647/// is implemented and cannot fail -- the associated `Error` type for
648/// calling `T::try_from()` on a value of type `T` is [`Infallible`].
649/// When the [`!`] type is stabilized [`Infallible`] and [`!`] will be
650/// equivalent.
651///
652/// Prefer using [`TryInto`] over [`TryFrom`] when specifying trait bounds on a generic function
653/// to ensure that types that only implement [`TryInto`] can be used as well.
654///
655/// `TryFrom<T>` can be implemented as follows:
656///
657/// ```
658/// struct GreaterThanZero(i32);
659///
660/// impl TryFrom<i32> for GreaterThanZero {
661///     type Error = &'static str;
662///
663///     fn try_from(value: i32) -> Result<Self, Self::Error> {
664///         if value <= 0 {
665///             Err("GreaterThanZero only accepts values greater than zero!")
666///         } else {
667///             Ok(GreaterThanZero(value))
668///         }
669///     }
670/// }
671/// ```
672///
673/// # Examples
674///
675/// As described, [`i32`] implements `TryFrom<`[`i64`]`>`:
676///
677/// ```
678/// let big_number = 1_000_000_000_000i64;
679/// // Silently truncates `big_number`, requires detecting
680/// // and handling the truncation after the fact.
681/// let smaller_number = big_number as i32;
682/// assert_eq!(smaller_number, -727379968);
683///
684/// // Returns an error because `big_number` is too big to
685/// // fit in an `i32`.
686/// let try_smaller_number = i32::try_from(big_number);
687/// assert!(try_smaller_number.is_err());
688///
689/// // Returns `Ok(3)`.
690/// let try_successful_smaller_number = i32::try_from(3);
691/// assert!(try_successful_smaller_number.is_ok());
692/// ```
693///
694/// [`try_from`]: TryFrom::try_from
695#[rustc_diagnostic_item = "TryFrom"]
696#[stable(feature = "try_from", since = "1.34.0")]
697#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
698pub const trait TryFrom<T>: Sized {
699    /// The type returned in the event of a conversion error.
700    #[stable(feature = "try_from", since = "1.34.0")]
701    type Error;
702
703    /// Performs the conversion.
704    #[stable(feature = "try_from", since = "1.34.0")]
705    #[rustc_diagnostic_item = "try_from_fn"]
706    fn try_from(value: T) -> Result<Self, Self::Error>;
707}
708
709////////////////////////////////////////////////////////////////////////////////
710// GENERIC IMPLS
711////////////////////////////////////////////////////////////////////////////////
712
713// As lifts over &
714#[stable(feature = "rust1", since = "1.0.0")]
715#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
716impl<T: PointeeSized, U: PointeeSized> const AsRef<U> for &T
717where
718    T: [const] AsRef<U>,
719{
720    #[inline]
721    fn as_ref(&self) -> &U {
722        <T as AsRef<U>>::as_ref(*self)
723    }
724}
725
726// As lifts over &mut
727#[stable(feature = "rust1", since = "1.0.0")]
728#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
729impl<T: PointeeSized, U: PointeeSized> const AsRef<U> for &mut T
730where
731    T: [const] AsRef<U>,
732{
733    #[inline]
734    fn as_ref(&self) -> &U {
735        <T as AsRef<U>>::as_ref(*self)
736    }
737}
738
739// FIXME (#45742): replace the above impls for &/&mut with the following more general one:
740// // As lifts over Deref
741// impl<D: ?Sized + Deref<Target: AsRef<U>>, U: ?Sized> AsRef<U> for D {
742//     fn as_ref(&self) -> &U {
743//         self.deref().as_ref()
744//     }
745// }
746
747// AsMut lifts over &mut
748#[stable(feature = "rust1", since = "1.0.0")]
749#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
750impl<T: PointeeSized, U: PointeeSized> const AsMut<U> for &mut T
751where
752    T: [const] AsMut<U>,
753{
754    #[inline]
755    fn as_mut(&mut self) -> &mut U {
756        (*self).as_mut()
757    }
758}
759
760// FIXME (#45742): replace the above impl for &mut with the following more general one:
761// // AsMut lifts over DerefMut
762// impl<D: ?Sized + Deref<Target: AsMut<U>>, U: ?Sized> AsMut<U> for D {
763//     fn as_mut(&mut self) -> &mut U {
764//         self.deref_mut().as_mut()
765//     }
766// }
767
768// From implies Into
769#[stable(feature = "rust1", since = "1.0.0")]
770#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
771impl<T, U> const Into<U> for T
772where
773    U: [const] From<T>,
774{
775    /// Calls `U::from(self)`.
776    ///
777    /// That is, this conversion is whatever the implementation of
778    /// <code>[From]<T> for U</code> chooses to do.
779    #[inline]
780    #[track_caller]
781    fn into(self) -> U {
782        U::from(self)
783    }
784}
785
786// From (and thus Into) is reflexive
787#[stable(feature = "rust1", since = "1.0.0")]
788#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
789impl<T> const From<T> for T {
790    /// Returns the argument unchanged.
791    #[inline(always)]
792    fn from(t: T) -> T {
793        t
794    }
795}
796
797/// **Stability note:** This impl does not yet exist, but we are
798/// "reserving space" to add it in the future. See
799/// [rust-lang/rust#64715][#64715] for details.
800///
801/// [#64715]: https://github.com/rust-lang/rust/issues/64715
802#[stable(feature = "convert_infallible", since = "1.34.0")]
803#[rustc_reservation_impl = "permitting this impl would forbid us from adding \
804                            `impl<T> From<!> for T` later; see rust-lang/rust#64715 for details"]
805#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
806#[cfg(not(feature = "ferrocene_certified"))]
807impl<T> const From<!> for T {
808    fn from(t: !) -> T {
809        t
810    }
811}
812
813// TryFrom implies TryInto
814#[stable(feature = "try_from", since = "1.34.0")]
815#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
816impl<T, U> const TryInto<U> for T
817where
818    U: [const] TryFrom<T>,
819{
820    type Error = U::Error;
821
822    #[inline]
823    fn try_into(self) -> Result<U, U::Error> {
824        U::try_from(self)
825    }
826}
827
828// Infallible conversions are semantically equivalent to fallible conversions
829// with an uninhabited error type.
830#[stable(feature = "try_from", since = "1.34.0")]
831#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
832impl<T, U> const TryFrom<U> for T
833where
834    U: [const] Into<T>,
835{
836    type Error = Infallible;
837
838    #[inline]
839    fn try_from(value: U) -> Result<Self, Self::Error> {
840        Ok(U::into(value))
841    }
842}
843
844////////////////////////////////////////////////////////////////////////////////
845// CONCRETE IMPLS
846////////////////////////////////////////////////////////////////////////////////
847
848#[stable(feature = "rust1", since = "1.0.0")]
849#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
850#[cfg(not(feature = "ferrocene_certified"))]
851impl<T> const AsRef<[T]> for [T] {
852    #[inline(always)]
853    fn as_ref(&self) -> &[T] {
854        self
855    }
856}
857
858#[stable(feature = "rust1", since = "1.0.0")]
859#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
860impl<T> const AsMut<[T]> for [T] {
861    #[inline(always)]
862    fn as_mut(&mut self) -> &mut [T] {
863        self
864    }
865}
866
867#[stable(feature = "rust1", since = "1.0.0")]
868#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
869#[cfg(not(feature = "ferrocene_certified"))]
870impl const AsRef<str> for str {
871    #[inline(always)]
872    fn as_ref(&self) -> &str {
873        self
874    }
875}
876
877#[stable(feature = "as_mut_str_for_str", since = "1.51.0")]
878#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
879impl const AsMut<str> for str {
880    #[inline(always)]
881    fn as_mut(&mut self) -> &mut str {
882        self
883    }
884}
885
886////////////////////////////////////////////////////////////////////////////////
887// THE NO-ERROR ERROR TYPE
888////////////////////////////////////////////////////////////////////////////////
889
890/// The error type for errors that can never happen.
891///
892/// Since this enum has no variant, a value of this type can never actually exist.
893/// This can be useful for generic APIs that use [`Result`] and parameterize the error type,
894/// to indicate that the result is always [`Ok`].
895///
896/// For example, the [`TryFrom`] trait (conversion that returns a [`Result`])
897/// has a blanket implementation for all types where a reverse [`Into`] implementation exists.
898///
899/// ```ignore (illustrates std code, duplicating the impl in a doctest would be an error)
900/// impl<T, U> TryFrom<U> for T where U: Into<T> {
901///     type Error = Infallible;
902///
903///     fn try_from(value: U) -> Result<Self, Infallible> {
904///         Ok(U::into(value))  // Never returns `Err`
905///     }
906/// }
907/// ```
908///
909/// # Future compatibility
910///
911/// This enum has the same role as [the `!` “never” type][never],
912/// which is unstable in this version of Rust.
913/// When `!` is stabilized, we plan to make `Infallible` a type alias to it:
914///
915/// ```ignore (illustrates future std change)
916/// pub type Infallible = !;
917/// ```
918///
919/// … and eventually deprecate `Infallible`.
920///
921/// However there is one case where `!` syntax can be used
922/// before `!` is stabilized as a full-fledged type: in the position of a function’s return type.
923/// Specifically, it is possible to have implementations for two different function pointer types:
924///
925/// ```
926/// trait MyTrait {}
927/// impl MyTrait for fn() -> ! {}
928/// impl MyTrait for fn() -> std::convert::Infallible {}
929/// ```
930///
931/// With `Infallible` being an enum, this code is valid.
932/// However when `Infallible` becomes an alias for the never type,
933/// the two `impl`s will start to overlap
934/// and therefore will be disallowed by the language’s trait coherence rules.
935#[stable(feature = "convert_infallible", since = "1.34.0")]
936#[derive(Copy)]
937pub enum Infallible {}
938
939#[stable(feature = "convert_infallible", since = "1.34.0")]
940#[rustc_const_unstable(feature = "const_clone", issue = "142757")]
941impl const Clone for Infallible {
942    fn clone(&self) -> Infallible {
943        match *self {}
944    }
945}
946
947#[stable(feature = "convert_infallible", since = "1.34.0")]
948#[cfg(not(feature = "ferrocene_certified"))]
949impl fmt::Debug for Infallible {
950    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
951        match *self {}
952    }
953}
954
955#[stable(feature = "convert_infallible", since = "1.34.0")]
956#[cfg(not(feature = "ferrocene_certified"))]
957impl fmt::Display for Infallible {
958    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
959        match *self {}
960    }
961}
962
963#[stable(feature = "str_parse_error2", since = "1.8.0")]
964#[cfg(not(feature = "ferrocene_certified"))]
965impl Error for Infallible {}
966
967#[stable(feature = "convert_infallible", since = "1.34.0")]
968#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
969impl const PartialEq for Infallible {
970    fn eq(&self, _: &Infallible) -> bool {
971        match *self {}
972    }
973}
974
975#[stable(feature = "convert_infallible", since = "1.34.0")]
976#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
977impl const Eq for Infallible {}
978
979#[stable(feature = "convert_infallible", since = "1.34.0")]
980#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
981#[cfg(not(feature = "ferrocene_certified"))]
982impl const PartialOrd for Infallible {
983    fn partial_cmp(&self, _other: &Self) -> Option<crate::cmp::Ordering> {
984        match *self {}
985    }
986}
987
988#[stable(feature = "convert_infallible", since = "1.34.0")]
989#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
990#[cfg(not(feature = "ferrocene_certified"))]
991impl const Ord for Infallible {
992    fn cmp(&self, _other: &Self) -> crate::cmp::Ordering {
993        match *self {}
994    }
995}
996
997#[stable(feature = "convert_infallible", since = "1.34.0")]
998#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
999#[cfg(not(feature = "ferrocene_certified"))]
1000impl const From<!> for Infallible {
1001    #[inline]
1002    fn from(x: !) -> Self {
1003        x
1004    }
1005}
1006
1007#[stable(feature = "convert_infallible_hash", since = "1.44.0")]
1008#[cfg(not(feature = "ferrocene_certified"))]
1009impl Hash for Infallible {
1010    fn hash<H: Hasher>(&self, _: &mut H) {
1011        match *self {}
1012    }
1013}