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