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