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

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy