Skip to main content

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