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