Skip to main content

core/convert/
mod.rs

1//! Traits for conversions between types.
2//!
3//! The traits in this module provide a way to convert from one type to another type.
4//! Each trait serves a different purpose:
5//!
6//! - Implement the [`AsRef`] trait for cheap reference-to-reference conversions
7//! - Implement the [`AsMut`] trait for cheap mutable-to-mutable conversions
8//! - Implement the [`From`] trait for consuming value-to-value conversions that cannot fail. This
9//!   automatically provides an implementation of [`Into`]
10//! - Implement the [`TryFrom`] trait for consuming value-to-value conversions that can fail. This
11//!   automatically provides an implementation of [`TryInto`]
12//!
13//! The traits in this module are often used as trait bounds for generic functions such that
14//! arguments of multiple types are supported. See the documentation of each trait for examples.
15//!
16//! As a library author, you should always prefer implementing [`From<T>`][`From`] or
17//! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
18//! as [`From`] and [`TryFrom`] provide greater flexibility and offer
19//! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a
20//! blanket implementation in the standard library. In versions of Rust prior to Rust 1.41,
21//! it was sometimes necessary to implement [`Into`] or [`TryInto`] directly when converting to a
22//! type outside the current crate.
23//!
24//! # Generic Implementations
25//!
26//! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference
27//!   (but not generally for all [dereferenceable types][core::ops::Deref])
28//! - [`From`]`<U> for T` implies [`Into`]`<T> for U`
29//! - [`TryFrom`]`<U> for T` implies [`TryInto`]`<T> for U`
30//! - [`From`] and [`Into`] are reflexive, which means that all types can
31//!   `into` themselves and `from` themselves
32//!
33//! See each trait for usage examples.
34
35#![stable(feature = "rust1", since = "1.0.0")]
36
37use crate::marker::PointeeSized;
38
39mod num;
40
41#[unstable(feature = "float_conversions", issue = "159913")]
42pub use num::FloatToFloat;
43#[unstable(feature = "convert_float_to_int", issue = "67057")]
44pub use num::FloatToInt;
45#[unstable(feature = "integer_casts", issue = "157388")]
46pub use num::{BoundedCastFromInt, CheckedCastFromInt};
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"]
219#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
220pub const trait AsRef<T: PointeeSized>: PointeeSized {
221    /// Converts this type into a shared reference of the (usually inferred) input type.
222    #[stable(feature = "rust1", since = "1.0.0")]
223    fn as_ref(&self) -> &T;
224}
225
226/// Used to do a cheap mutable-to-mutable reference conversion.
227///
228/// This trait is similar to [`AsRef`] but used for converting between mutable
229/// references. If you need to do a costly conversion it is better to
230/// implement [`From`] with type `&mut T` or write a custom function.
231///
232/// **Note: This trait must not fail**. If the conversion can fail, use a
233/// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
234///
235/// # Generic Implementations
236///
237/// `AsMut` auto-dereferences if the inner type is a mutable reference
238/// (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo` or `&mut &mut Foo`).
239///
240/// Note that due to historic reasons, the above currently does not hold generally for all
241/// [mutably dereferenceable types], e.g. `foo.as_mut()` will *not* work the same as
242/// `Box::new(foo).as_mut()`. Instead, many smart pointers provide an `as_mut` implementation which
243/// simply returns a reference to the [pointed-to value] (but do not perform a cheap
244/// reference-to-reference conversion for that value). However, [`AsMut::as_mut`] should not be
245/// used for the sole purpose of mutable dereferencing; instead ['`Deref` coercion'] can be used:
246///
247/// [mutably dereferenceable types]: core::ops::DerefMut
248/// [pointed-to value]: core::ops::Deref::Target
249/// ['`Deref` coercion']: core::ops::DerefMut#mutable-deref-coercion
250///
251/// ```
252/// let mut x = Box::new(5i32);
253/// // Avoid this:
254/// // let y: &mut i32 = x.as_mut();
255/// // Better just write:
256/// let y: &mut i32 = &mut x;
257/// ```
258///
259/// Types which implement [`DerefMut`] should consider to add an implementation of `AsMut<T>` as
260/// follows:
261///
262/// [`DerefMut`]: core::ops::DerefMut
263///
264/// ```
265/// # use core::ops::{Deref, DerefMut};
266/// # struct SomeType;
267/// # impl Deref for SomeType {
268/// #     type Target = [u8];
269/// #     fn deref(&self) -> &[u8] {
270/// #         &[]
271/// #     }
272/// # }
273/// # impl DerefMut for SomeType {
274/// #     fn deref_mut(&mut self) -> &mut [u8] {
275/// #         &mut []
276/// #     }
277/// # }
278/// impl<T> AsMut<T> for SomeType
279/// where
280///     <SomeType as Deref>::Target: AsMut<T>,
281/// {
282///     fn as_mut(&mut self) -> &mut T {
283///         self.deref_mut().as_mut()
284///     }
285/// }
286/// ```
287///
288/// # Reflexivity
289///
290/// Ideally, `AsMut` would be reflexive, i.e. there would be an `impl<T: ?Sized> AsMut<T> for T`
291/// with [`as_mut`] simply returning its argument unchanged.
292/// Such a blanket implementation is currently *not* provided due to technical restrictions of
293/// Rust's type system (it would be overlapping with another existing blanket implementation for
294/// `&mut T where T: AsMut<U>` which allows `AsMut` to auto-dereference, see "Generic
295/// Implementations" above).
296///
297/// [`as_mut`]: AsMut::as_mut
298///
299/// A trivial implementation of `AsMut<T> for T` must be added explicitly for a particular type `T`
300/// where needed or desired. Note, however, that not all types from `std` contain such an
301/// implementation, and those cannot be added by external code due to orphan rules.
302///
303/// # Examples
304///
305/// Using `AsMut` as trait bound for a generic function, we can accept all mutable references that
306/// can be converted to type `&mut T`. Unlike [dereference], which has a single [target type],
307/// there can be multiple implementations of `AsMut` for a type. In particular, `Vec<T>` implements
308/// both `AsMut<Vec<T>>` and `AsMut<[T]>`.
309///
310/// In the following, the example functions `caesar` and `null_terminate` provide a generic
311/// interface which works with any type that can be converted by cheap mutable-to-mutable conversion
312/// into a byte slice (`[u8]`) or a byte vector (`Vec<u8>`), respectively.
313///
314/// [dereference]: core::ops::DerefMut
315/// [target type]: core::ops::Deref::Target
316///
317/// ```
318/// struct Document {
319///     info: String,
320///     content: Vec<u8>,
321/// }
322///
323/// impl<T: ?Sized> AsMut<T> for Document
324/// where
325///     Vec<u8>: AsMut<T>,
326/// {
327///     fn as_mut(&mut self) -> &mut T {
328///         self.content.as_mut()
329///     }
330/// }
331///
332/// fn caesar<T: AsMut<[u8]>>(data: &mut T, key: u8) {
333///     for byte in data.as_mut() {
334///         *byte = byte.wrapping_add(key);
335///     }
336/// }
337///
338/// fn null_terminate<T: AsMut<Vec<u8>>>(data: &mut T) {
339///     // Using a non-generic inner function, which contains most of the
340///     // functionality, helps to minimize monomorphization overhead.
341///     fn doit(data: &mut Vec<u8>) {
342///         let len = data.len();
343///         if len == 0 || data[len-1] != 0 {
344///             data.push(0);
345///         }
346///     }
347///     doit(data.as_mut());
348/// }
349///
350/// fn main() {
351///     let mut v: Vec<u8> = vec![1, 2, 3];
352///     caesar(&mut v, 5);
353///     assert_eq!(v, [6, 7, 8]);
354///     null_terminate(&mut v);
355///     assert_eq!(v, [6, 7, 8, 0]);
356///     let mut doc = Document {
357///         info: String::from("Example"),
358///         content: vec![17, 19, 8],
359///     };
360///     caesar(&mut doc, 1);
361///     assert_eq!(doc.content, [18, 20, 9]);
362///     null_terminate(&mut doc);
363///     assert_eq!(doc.content, [18, 20, 9, 0]);
364/// }
365/// ```
366///
367/// Note, however, that APIs don't need to be generic. In many cases taking a `&mut [u8]` or
368/// `&mut Vec<u8>`, for example, is the better choice (callers need to pass the correct type then).
369#[stable(feature = "rust1", since = "1.0.0")]
370#[rustc_diagnostic_item = "AsMut"]
371#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
372pub const trait AsMut<T: PointeeSized>: PointeeSized {
373    /// Converts this type into a mutable reference of the (usually inferred) input type.
374    #[stable(feature = "rust1", since = "1.0.0")]
375    fn as_mut(