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 fn from(value: T) -> Self;
596}
597
598/// An attempted conversion that consumes `self`, which may or may not be
599/// expensive.
600///
601/// Library authors should usually not directly implement this trait,
602/// but should prefer implementing the [`TryFrom`] trait, which offers
603/// greater flexibility and provides an equivalent `TryInto`
604/// implementation for free, thanks to a blanket implementation in the
605/// standard library. For more information on this, see the
606/// documentation for [`Into`].
607///
608/// Prefer using [`TryInto`] over [`TryFrom`] when specifying trait bounds on a generic function
609/// to ensure that types that only implement [`TryInto`] can be used as well.
610///
611/// # Implementing `TryInto`
612///
613/// This suffers the same restrictions and reasoning as implementing
614/// [`Into`], see there for details.
615#[rustc_diagnostic_item = "TryInto"]
616#[stable(feature = "try_from", since = "1.34.0")]
617#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
618pub const trait TryInto<T>: Sized {
619 /// The type returned in the event of a conversion error.
620 #[stable(feature = "try_from", since = "1.34.0")]
621 type Error;
622
623 /// Performs the conversion.
624 #[stable(feature = "try_from", since = "1.34.0")]
625 fn try_into(self) -> Result<T, Self::Error>;
626}
627
628/// Simple and safe type conversions that may fail in a controlled
629/// way under some circumstances. It is the reciprocal of [`TryInto`].
630///
631/// This is useful when you are doing a type conversion that may
632/// trivially succeed but may also need special handling.
633/// For example, there is no way to convert an [`i64`] into an [`i32`]
634/// using the [`From`] trait, because an [`i64`] may contain a value
635/// that an [`i32`] cannot represent and so the conversion would lose data.
636/// This might be handled by truncating the [`i64`] to an [`i32`] or by
637/// simply returning [`i32::MAX`], or by some other method. The [`From`]
638/// trait is intended for perfect conversions, so the `TryFrom` trait
639/// informs the programmer when a type conversion could go bad and lets
640/// them decide how to handle it.
641///
642/// # Generic Implementations
643///
644/// - `TryFrom<T> for U` implies [`TryInto`]`<U> for T`
645/// - [`try_from`] is reflexive, which means that `TryFrom<T> for T`
646/// is implemented and cannot fail -- the associated `Error` type for
647/// calling `T::try_from()` on a value of type `T` is [`Infallible`].
648/// When the [`!`] type is stabilized [`Infallible`] and [`!`] will be
649/// equivalent.
650///
651/// Prefer using [`TryInto`] over [`TryFrom`] when specifying trait bounds on a generic function
652/// to ensure that types that only implement [`TryInto`] can be used as well.
653///
654/// `TryFrom<T>` can be implemented as follows:
655///
656/// ```
657/// struct GreaterThanZero(i32);
658///
659/// impl TryFrom<i32> for GreaterThanZero {
660/// type Error = &'static str;
661///
662/// fn try_from(value: i32) -> Result<Self, Self::Error> {
663/// if value <= 0 {
664/// Err("GreaterThanZero only accepts values greater than zero!")
665/// } else {
666/// Ok(GreaterThanZero(value))
667/// }
668/// }
669/// }
670/// ```
671///
672/// # Examples
673///
674/// As described, [`i32`] implements `TryFrom<`[`i64`]`>`:
675///
676/// ```
677/// let big_number = 1_000_000_000_000i64;
678/// // Silently truncates `big_number`, requires detecting
679/// // and handling the truncation after the fact.
680/// let smaller_number = big_number as i32;
681/// assert_eq!(smaller_number, -727379968);
682///
683/// // Returns an error because `big_number` is too big to
684/// // fit in an `i32`.
685/// let try_smaller_number = i32::try_from(big_number);
686/// assert!(try_smaller_number.is_err());
687///
688/// // Returns `Ok(3)`.
689/// let try_successful_smaller_number = i32::try_from(3);
690/// assert!(try_successful_smaller_number.is_ok());
691/// ```
692///
693/// [`try_from`]: TryFrom::try_from
694#[rustc_diagnostic_item = "TryFrom"]
695#[stable(feature = "try_from", since = "1.34.0")]
696#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
697pub const trait TryFrom<T>: Sized {
698 /// The type returned in the event of a conversion error.
699 #[stable(feature = "try_from", since = "1.34.0")]
700 type Error;
701
702 /// Performs the conversion.
703 #[stable(feature = "try_from", since = "1.34.0")]
704 #[rustc_diagnostic_item = "try_from_fn"]
705 fn try_from(value: T) -> Result<Self, Self::Error>;
706}
707
708////////////////////////////////////////////////////////////////////////////////
709// GENERIC IMPLS
710////////////////////////////////////////////////////////////////////////////////
711
712// As lifts over &
713#[stable(feature = "rust1", since = "1.0.0")]
714#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
715const impl<T: PointeeSized, U: PointeeSized> AsRef<U> for &T
716where
717 T: [const] AsRef<U>,
718{
719 #[inline]
720 #[ferrocene::prevalidated]
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")]
729const impl<T: PointeeSized, U: PointeeSized> AsRef<U> for &mut T
730where
731 T: [const] AsRef<U>,
732{
733 #[inline]
734 #[ferrocene::prevalidated]
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")]
751const impl<T: PointeeSized, U: PointeeSized> AsMut<U> for &mut T
752where
753 T: [const] AsMut<U>,
754{
755 #[inline]
756 #[ferrocene::prevalidated]
757 fn as_mut(&mut self) -> &mut U {
758 (*self).as_mut()
759 }
760}
761
762// FIXME (#45742): replace the above impl for &mut with the following more general one:
763// // AsMut lifts over DerefMut
764// impl<D: ?Sized + Deref<Target: AsMut<U>>, U: ?Sized> AsMut<U> for D {
765// fn as_mut(&mut self) -> &mut U {
766// self.deref_mut().as_mut()
767// }
768// }
769
770// From implies Into
771#[stable(feature = "rust1", since = "1.0.0")]
772#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
773const impl<T, U> Into<U> for T
774where
775 U: [const] From<T>,
776{
777 /// Calls `U::from(self)`.
778 ///
779 /// That is, this conversion is whatever the implementation of
780 /// <code>[From]<T> for U</code> chooses to do.
781 #[inline]
782 #[track_caller]
783 #[ferrocene::prevalidated]
784 fn into(self) -> U {
785 U::from(self)
786 }
787}
788
789// From (and thus Into) is reflexive
790#[stable(feature = "rust1", since = "1.0.0")]
791#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
792const impl<T> From<T> for T {
793 /// Returns the argument unchanged.
794 #[inline(always)]
795 #[ferrocene::prevalidated]
796 fn from(t: T) -> T {
797 t
798 }
799}
800
801/// **Stability note:** This impl does not yet exist, but we are
802/// "reserving space" to add it in the future. See
803/// [rust-lang/rust#64715][#64715] for details.
804///
805/// [#64715]: https://github.com/rust-lang/rust/issues/64715
806#[stable(feature = "convert_infallible", since = "1.34.0")]
807#[rustc_reservation_impl = "permitting this impl would forbid us from adding \
808 `impl<T> From<!> for T` later; see rust-lang/rust#64715 for details"]
809#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
810const impl<T> From<!> for T {
811 fn from(t: !) -> T {
812 t
813 }
814}
815
816// TryFrom implies TryInto
817#[stable(feature = "try_from", since = "1.34.0")]
818#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
819const impl<T, U> TryInto<U> for T
820where
821 U: [const] TryFrom<T>,
822{
823 type Error = U::Error;
824
825 #[inline]
826 #[ferrocene::prevalidated]
827 fn try_into(self) -> Result<U, U::Error> {
828 U::try_from(self)
829 }
830}
831
832// Infallible conversions are semantically equivalent to fallible conversions
833// with an uninhabited error type.
834#[stable(feature = "try_from", since = "1.34.0")]
835#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
836const impl<T, U> TryFrom<U> for T
837where
838 U: [const] Into<T>,
839{
840 type Error = Infallible;
841
842 #[inline]
843 #[ferrocene::prevalidated]
844 fn try_from(value: U) -> Result<Self, Self::Error> {
845 Ok(U::into(value))
846 }
847}
848
849////////////////////////////////////////////////////////////////////////////////
850// CONCRETE IMPLS
851////////////////////////////////////////////////////////////////////////////////
852
853#[stable(feature = "rust1", since = "1.0.0")]
854#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
855const impl<T> AsRef<[T]> for [T] {
856 #[inline(always)]
857 #[ferrocene::prevalidated]
858 fn as_ref(&self) -> &[T] {
859 self
860 }
861}
862
863#[stable(feature = "rust1", since = "1.0.0")]
864#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
865const impl<T> AsMut<[T]> for [T] {
866 #[inline(always)]
867 #[ferrocene::prevalidated]
868 fn as_mut(&mut self) -> &mut [T] {
869 self
870 }
871}
872
873#[stable(feature = "rust1", since = "1.0.0")]
874#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
875const impl AsRef<str> for str {
876 #[inline(always)]
877 fn as_ref(&self) -> &str {
878 self
879 }
880}
881
882#[stable(feature = "as_mut_str_for_str", since = "1.51.0")]
883#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
884const impl AsMut<str> for str {
885 #[inline(always)]
886 #[ferrocene::prevalidated]
887 fn as_mut(&mut self) -> &mut str {
888 self
889 }
890}
891
892////////////////////////////////////////////////////////////////////////////////
893// THE NO-ERROR ERROR TYPE
894////////////////////////////////////////////////////////////////////////////////
895
896/// The error type for errors that can never happen.
897///
898/// Since this enum has no variant, a value of this type can never actually exist.
899/// This can be useful for generic APIs that use [`Result`] and parameterize the error type,
900/// to indicate that the result is always [`Ok`].
901///
902/// For example, the [`TryFrom`] trait (conversion that returns a [`Result`])
903/// has a blanket implementation for all types where a reverse [`Into`] implementation exists.
904///
905/// ```ignore (illustrates std code, duplicating the impl in a doctest would be an error)
906/// impl<T, U> TryFrom<U> for T where U: Into<T> {
907/// type Error = Infallible;
908///
909/// fn try_from(value: U) -> Result<Self, Infallible> {
910/// Ok(U::into(value)) // Never returns `Err`
911/// }
912/// }
913/// ```
914///
915/// # Future compatibility
916///
917/// This enum has the same role as [the `!` “never” type][never],
918/// which is unstable in this version of Rust.
919/// When `!` is stabilized, we plan to make `Infallible` a type alias to it:
920///
921/// ```ignore (illustrates future std change)
922/// pub type Infallible = !;
923/// ```
924///
925/// … and eventually deprecate `Infallible`.
926///
927/// However there is one case where `!` syntax can be used
928/// before `!` is stabilized as a full-fledged type: in the position of a function’s return type.
929/// Specifically, it is possible to have implementations for two different function pointer types:
930///
931/// ```
932/// trait MyTrait {}
933/// impl MyTrait for fn() -> ! {}
934/// impl MyTrait for fn() -> std::convert::Infallible {}
935/// ```
936///
937/// With `Infallible` being an enum, this code is valid.
938/// However when `Infallible` becomes an alias for the never type,
939/// the two `impl`s will start to overlap
940/// and therefore will be disallowed by the language’s trait coherence rules.
941#[stable(feature = "convert_infallible", since = "1.34.0")]
942#[derive(Copy)]
943#[ferrocene::prevalidated]
944pub enum Infallible {}
945
946#[stable(feature = "convert_infallible", since = "1.34.0")]
947#[rustc_const_unstable(feature = "const_clone", issue = "142757")]
948const impl Clone for Infallible {
949 #[ferrocene::prevalidated]
950 fn clone(&self) -> Infallible {
951 match *self {}
952 }
953}
954
955#[stable(feature = "convert_infallible", since = "1.34.0")]
956impl fmt::Debug for Infallible {
957 #[ferrocene::prevalidated]
958 fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
959 match *self {}
960 }
961}
962
963#[stable(feature = "convert_infallible", since = "1.34.0")]
964impl fmt::Display for Infallible {
965 #[ferrocene::prevalidated]
966 fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
967 match *self {}
968 }
969}
970
971#[stable(feature = "str_parse_error2", since = "1.8.0")]
972impl Error for Infallible {}
973
974#[stable(feature = "convert_infallible", since = "1.34.0")]
975#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
976const impl PartialEq for Infallible {
977 #[ferrocene::prevalidated]
978 fn eq(&self, _: &Infallible) -> bool {
979 match *self {}
980 }
981}
982
983#[stable(feature = "convert_infallible", since = "1.34.0")]
984#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
985const impl Eq for Infallible {}
986
987#[stable(feature = "convert_infallible", since = "1.34.0")]
988#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
989const impl PartialOrd for Infallible {
990 fn partial_cmp(&self, _other: &Self) -> Option<crate::cmp::Ordering> {
991 match *self {}
992 }
993}
994
995#[stable(feature = "convert_infallible", since = "1.34.0")]
996#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
997const impl Ord for Infallible {
998 fn cmp(&self, _other: &Self) -> crate::cmp::Ordering {
999 match *self {}
1000 }
1001}
1002
1003#[stable(feature = "convert_infallible", since = "1.34.0")]
1004#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1005const impl From<!> for Infallible {
1006 #[inline]
1007 fn from(x: !) -> Self {
1008 x
1009 }
1010}
1011
1012#[stable(feature = "convert_infallible_hash", since = "1.44.0")]
1013impl Hash for Infallible {
1014 fn hash<H: Hasher>(&self, _: &mut H) {
1015 match *self {}
1016 }
1017}