]> git.lizzy.rs Git - rust.git/blob - src/libcore/convert.rs
Rollup merge of #58595 - stjepang:make-duration-consts-associated, r=oli-obk
[rust.git] / src / libcore / convert.rs
1 //! Traits for conversions between types.
2 //!
3 //! The traits in this module provide a general way to talk about conversions
4 //! from one type to another. They follow the standard Rust conventions of
5 //! `as`/`into`/`from`.
6 //!
7 //! Like many traits, these are often used as bounds for generic functions, to
8 //! support arguments of multiple types.
9 //!
10 //! - Implement the `As*` traits for reference-to-reference conversions
11 //! - Implement the [`Into`] trait when you want to consume the value in the conversion
12 //! - The [`From`] trait is the most flexible, useful for value _and_ reference conversions
13 //! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], but allow for the
14 //!   conversion to fail
15 //!
16 //! As a library author, you should 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.  However, there are some cases
21 //! where this is not possible, such as creating conversions into a type defined
22 //! outside your library, so implementing [`Into`] instead of [`From`] is
23 //! sometimes necessary.
24 //!
25 //! # Generic Implementations
26 //!
27 //! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference
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 //! [`Into`]: trait.Into.html
36 //! [`From`]: trait.From.html
37 //! [`TryFrom`]: trait.TryFrom.html
38 //! [`TryInto`]: trait.TryInto.html
39 //! [`AsRef`]: trait.AsRef.html
40 //! [`AsMut`]: trait.AsMut.html
41
42 #![stable(feature = "rust1", since = "1.0.0")]
43
44 /// An identity function.
45 ///
46 /// Two things are important to note about this function:
47 ///
48 /// - It is not always equivalent to a closure like `|x| x` since the
49 ///   closure may coerce `x` into a different type.
50 ///
51 /// - It moves the input `x` passed to the function.
52 ///
53 /// While it might seem strange to have a function that just returns back the
54 /// input, there are some interesting uses.
55 ///
56 /// # Examples
57 ///
58 /// Using `identity` to do nothing among other interesting functions:
59 ///
60 /// ```rust
61 /// use std::convert::identity;
62 ///
63 /// fn manipulation(x: u32) -> u32 {
64 ///     // Let's assume that this function does something interesting.
65 ///     x + 1
66 /// }
67 ///
68 /// let _arr = &[identity, manipulation];
69 /// ```
70 ///
71 /// Using `identity` to get a function that changes nothing in a conditional:
72 ///
73 /// ```rust
74 /// use std::convert::identity;
75 ///
76 /// # let condition = true;
77 ///
78 /// # fn manipulation(x: u32) -> u32 { x + 1 }
79 ///
80 /// let do_stuff = if condition { manipulation } else { identity };
81 ///
82 /// // do more interesting stuff..
83 ///
84 /// let _results = do_stuff(42);
85 /// ```
86 ///
87 /// Using `identity` to keep the `Some` variants of an iterator of `Option<T>`:
88 ///
89 /// ```rust
90 /// use std::convert::identity;
91 ///
92 /// let iter = vec![Some(1), None, Some(3)].into_iter();
93 /// let filtered = iter.filter_map(identity).collect::<Vec<_>>();
94 /// assert_eq!(vec![1, 3], filtered);
95 /// ```
96 #[stable(feature = "convert_id", since = "1.33.0")]
97 #[inline]
98 pub const fn identity<T>(x: T) -> T { x }
99
100 /// A cheap reference-to-reference conversion. Used to convert a value to a
101 /// reference value within generic code.
102 ///
103 /// `AsRef` is very similar to, but serves a slightly different purpose than,
104 /// [`Borrow`].
105 ///
106 /// `AsRef` is to be used when wishing to convert to a reference of another
107 /// type.
108 /// `Borrow` is more related to the notion of taking the reference. It is
109 /// useful when wishing to abstract over the type of reference
110 /// (`&T`, `&mut T`) or allow both the referenced and owned type to be treated
111 /// in the same manner.
112 ///
113 /// The key difference between the two traits is the intention:
114 ///
115 /// - Use `AsRef` when the goal is to simply convert into a reference
116 /// - Use `Borrow` when the goal is related to writing code that is agnostic to
117 ///   the type of borrow and whether it is a reference or value
118 ///
119 /// [`Borrow`]: ../../std/borrow/trait.Borrow.html
120 ///
121 /// **Note: this trait must not fail**. If the conversion can fail, use a
122 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
123 ///
124 /// [`Option<T>`]: ../../std/option/enum.Option.html
125 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
126 ///
127 /// # Generic Implementations
128 ///
129 /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
130 ///   reference (e.g.: `foo.as_ref()` will work the same if `foo` has type
131 ///   `&mut Foo` or `&&mut Foo`)
132 ///
133 /// # Examples
134 ///
135 /// Both [`String`] and `&str` implement `AsRef<str>`:
136 ///
137 /// [`String`]: ../../std/string/struct.String.html
138 ///
139 /// ```
140 /// fn is_hello<T: AsRef<str>>(s: T) {
141 ///    assert_eq!("hello", s.as_ref());
142 /// }
143 ///
144 /// let s = "hello";
145 /// is_hello(s);
146 ///
147 /// let s = "hello".to_string();
148 /// is_hello(s);
149 /// ```
150 ///
151 #[stable(feature = "rust1", since = "1.0.0")]
152 pub trait AsRef<T: ?Sized> {
153     /// Performs the conversion.
154     #[stable(feature = "rust1", since = "1.0.0")]
155     fn as_ref(&self) -> &T;
156 }
157
158 /// A cheap, mutable reference-to-mutable reference conversion.
159 ///
160 /// This trait is similar to `AsRef` but used for converting between mutable
161 /// references.
162 ///
163 /// **Note: this trait must not fail**. If the conversion can fail, use a
164 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
165 ///
166 /// [`Option<T>`]: ../../std/option/enum.Option.html
167 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
168 ///
169 /// # Generic Implementations
170 ///
171 /// - `AsMut` auto-dereferences if the inner type is a mutable reference
172 ///   (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo`
173 ///   or `&mut &mut Foo`)
174 ///
175 /// # Examples
176 ///
177 /// [`Box<T>`] implements `AsMut<T>`:
178 ///
179 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
180 ///
181 /// ```
182 /// fn add_one<T: AsMut<u64>>(num: &mut T) {
183 ///     *num.as_mut() += 1;
184 /// }
185 ///
186 /// let mut boxed_num = Box::new(0);
187 /// add_one(&mut boxed_num);
188 /// assert_eq!(*boxed_num, 1);
189 /// ```
190 ///
191 ///
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub trait AsMut<T: ?Sized> {
194     /// Performs the conversion.
195     #[stable(feature = "rust1", since = "1.0.0")]
196     fn as_mut(&mut self) -> &mut T;
197 }
198
199 /// A conversion that consumes `self`, which may or may not be expensive. The
200 /// reciprocal of [`From`][From].
201 ///
202 /// **Note: this trait must not fail**. If the conversion can fail, use
203 /// [`TryInto`] or a dedicated method which returns an [`Option<T>`] or a
204 /// [`Result<T, E>`].
205 ///
206 /// Library authors should not directly implement this trait, but should prefer
207 /// implementing the [`From`][From] trait, which offers greater flexibility and
208 /// provides an equivalent `Into` implementation for free, thanks to a blanket
209 /// implementation in the standard library.
210 ///
211 /// # Generic Implementations
212 ///
213 /// - [`From<T>`][From]` for U` implies `Into<U> for T`
214 /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
215 ///
216 /// # Implementing `Into`
217 ///
218 /// There is one exception to implementing `Into`, and it's kind of esoteric.
219 /// If the destination type is not part of the current crate, and it uses a
220 /// generic variable, then you can't implement `From` directly. For example,
221 /// take this crate:
222 ///
223 /// ```compile_fail
224 /// struct Wrapper<T>(Vec<T>);
225 /// impl<T> From<Wrapper<T>> for Vec<T> {
226 ///     fn from(w: Wrapper<T>) -> Vec<T> {
227 ///         w.0
228 ///     }
229 /// }
230 /// ```
231 ///
232 /// To fix this, you can implement `Into` directly:
233 ///
234 /// ```
235 /// struct Wrapper<T>(Vec<T>);
236 /// impl<T> Into<Vec<T>> for Wrapper<T> {
237 ///     fn into(self) -> Vec<T> {
238 ///         self.0
239 ///     }
240 /// }
241 /// ```
242 ///
243 /// This won't always allow the conversion: for example, `try!` and `?`
244 /// always use `From`. However, in most cases, people use `Into` to do the
245 /// conversions, and this will allow that.
246 ///
247 /// In almost all cases, you should try to implement `From`, then fall back
248 /// to `Into` if `From` can't be implemented.
249 ///
250 /// # Examples
251 ///
252 /// [`String`] implements `Into<Vec<u8>>`:
253 ///
254 /// ```
255 /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
256 ///    let bytes = b"hello".to_vec();
257 ///    assert_eq!(bytes, s.into());
258 /// }
259 ///
260 /// let s = "hello".to_string();
261 /// is_hello(s);
262 /// ```
263 ///
264 /// [`TryInto`]: trait.TryInto.html
265 /// [`Option<T>`]: ../../std/option/enum.Option.html
266 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
267 /// [`String`]: ../../std/string/struct.String.html
268 /// [From]: trait.From.html
269 /// [`into`]: trait.Into.html#tymethod.into
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub trait Into<T>: Sized {
272     /// Performs the conversion.
273     #[stable(feature = "rust1", since = "1.0.0")]
274     fn into(self) -> T;
275 }
276
277 /// Simple and safe type conversions in to `Self`. It is the reciprocal of
278 /// `Into`.
279 ///
280 /// This trait is useful when performing error handling as described by
281 /// [the book][book] and is closely related to the `?` operator.
282 ///
283 /// When constructing a function that is capable of failing the return type
284 /// will generally be of the form `Result<T, E>`.
285 ///
286 /// The `From` trait allows for simplification of error handling by providing a
287 /// means of returning a single error type that encapsulates numerous possible
288 /// erroneous situations.
289 ///
290 /// This trait is not limited to error handling, rather the general case for
291 /// this trait would be in any type conversions to have an explicit definition
292 /// of how they are performed.
293 ///
294 /// **Note: this trait must not fail**. If the conversion can fail, use
295 /// [`TryFrom`] or a dedicated method which returns an [`Option<T>`] or a
296 /// [`Result<T, E>`].
297 ///
298 /// # Generic Implementations
299 ///
300 /// - `From<T> for U` implies [`Into<U>`]` for T`
301 /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
302 ///
303 /// # Examples
304 ///
305 /// [`String`] implements `From<&str>`:
306 ///
307 /// ```
308 /// let string = "hello".to_string();
309 /// let other_string = String::from("hello");
310 ///
311 /// assert_eq!(string, other_string);
312 /// ```
313 ///
314 /// An example usage for error handling:
315 ///
316 /// ```
317 /// use std::fs;
318 /// use std::io;
319 /// use std::num;
320 ///
321 /// enum CliError {
322 ///     IoError(io::Error),
323 ///     ParseError(num::ParseIntError),
324 /// }
325 ///
326 /// impl From<io::Error> for CliError {
327 ///     fn from(error: io::Error) -> Self {
328 ///         CliError::IoError(error)
329 ///     }
330 /// }
331 ///
332 /// impl From<num::ParseIntError> for CliError {
333 ///     fn from(error: num::ParseIntError) -> Self {
334 ///         CliError::ParseError(error)
335 ///     }
336 /// }
337 ///
338 /// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
339 ///     let mut contents = fs::read_to_string(&file_name)?;
340 ///     let num: i32 = contents.trim().parse()?;
341 ///     Ok(num)
342 /// }
343 /// ```
344 ///
345 /// [`TryFrom`]: trait.TryFrom.html
346 /// [`Option<T>`]: ../../std/option/enum.Option.html
347 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
348 /// [`String`]: ../../std/string/struct.String.html
349 /// [`Into<U>`]: trait.Into.html
350 /// [`from`]: trait.From.html#tymethod.from
351 /// [book]: ../../book/ch09-00-error-handling.html
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub trait From<T>: Sized {
354     /// Performs the conversion.
355     #[stable(feature = "rust1", since = "1.0.0")]
356     fn from(_: T) -> Self;
357 }
358
359 /// An attempted conversion that consumes `self`, which may or may not be
360 /// expensive.
361 ///
362 /// Library authors should not directly implement this trait, but should prefer
363 /// implementing the [`TryFrom`] trait, which offers greater flexibility and
364 /// provides an equivalent `TryInto` implementation for free, thanks to a
365 /// blanket implementation in the standard library. For more information on this,
366 /// see the documentation for [`Into`].
367 ///
368 /// [`TryFrom`]: trait.TryFrom.html
369 /// [`Into`]: trait.Into.html
370 #[unstable(feature = "try_from", issue = "33417")]
371 pub trait TryInto<T>: Sized {
372     /// The type returned in the event of a conversion error.
373     type Error;
374
375     /// Performs the conversion.
376     fn try_into(self) -> Result<T, Self::Error>;
377 }
378
379 /// Attempt to construct `Self` via a conversion.
380 #[unstable(feature = "try_from", issue = "33417")]
381 pub trait TryFrom<T>: Sized {
382     /// The type returned in the event of a conversion error.
383     type Error;
384
385     /// Performs the conversion.
386     fn try_from(value: T) -> Result<Self, Self::Error>;
387 }
388
389 ////////////////////////////////////////////////////////////////////////////////
390 // GENERIC IMPLS
391 ////////////////////////////////////////////////////////////////////////////////
392
393 // As lifts over &
394 #[stable(feature = "rust1", since = "1.0.0")]
395 impl<T: ?Sized, U: ?Sized> AsRef<U> for &T where T: AsRef<U>
396 {
397     fn as_ref(&self) -> &U {
398         <T as AsRef<U>>::as_ref(*self)
399     }
400 }
401
402 // As lifts over &mut
403 #[stable(feature = "rust1", since = "1.0.0")]
404 impl<T: ?Sized, U: ?Sized> AsRef<U> for &mut T where T: AsRef<U>
405 {
406     fn as_ref(&self) -> &U {
407         <T as AsRef<U>>::as_ref(*self)
408     }
409 }
410
411 // FIXME (#45742): replace the above impls for &/&mut with the following more general one:
412 // // As lifts over Deref
413 // impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
414 //     fn as_ref(&self) -> &U {
415 //         self.deref().as_ref()
416 //     }
417 // }
418
419 // AsMut lifts over &mut
420 #[stable(feature = "rust1", since = "1.0.0")]
421 impl<T: ?Sized, U: ?Sized> AsMut<U> for &mut T where T: AsMut<U>
422 {
423     fn as_mut(&mut self) -> &mut U {
424         (*self).as_mut()
425     }
426 }
427
428 // FIXME (#45742): replace the above impl for &mut with the following more general one:
429 // // AsMut lifts over DerefMut
430 // impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
431 //     fn as_mut(&mut self) -> &mut U {
432 //         self.deref_mut().as_mut()
433 //     }
434 // }
435
436 // From implies Into
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl<T, U> Into<U> for T where U: From<T>
439 {
440     fn into(self) -> U {
441         U::from(self)
442     }
443 }
444
445 // From (and thus Into) is reflexive
446 #[stable(feature = "rust1", since = "1.0.0")]
447 impl<T> From<T> for T {
448     fn from(t: T) -> T { t }
449 }
450
451
452 // TryFrom implies TryInto
453 #[unstable(feature = "try_from", issue = "33417")]
454 impl<T, U> TryInto<U> for T where U: TryFrom<T>
455 {
456     type Error = U::Error;
457
458     fn try_into(self) -> Result<U, U::Error> {
459         U::try_from(self)
460     }
461 }
462
463 // Infallible conversions are semantically equivalent to fallible conversions
464 // with an uninhabited error type.
465 #[unstable(feature = "try_from", issue = "33417")]
466 impl<T, U> TryFrom<U> for T where U: Into<T> {
467     type Error = !;
468
469     fn try_from(value: U) -> Result<Self, Self::Error> {
470         Ok(U::into(value))
471     }
472 }
473
474 ////////////////////////////////////////////////////////////////////////////////
475 // CONCRETE IMPLS
476 ////////////////////////////////////////////////////////////////////////////////
477
478 #[stable(feature = "rust1", since = "1.0.0")]
479 impl<T> AsRef<[T]> for [T] {
480     fn as_ref(&self) -> &[T] {
481         self
482     }
483 }
484
485 #[stable(feature = "rust1", since = "1.0.0")]
486 impl<T> AsMut<[T]> for [T] {
487     fn as_mut(&mut self) -> &mut [T] {
488         self
489     }
490 }
491
492 #[stable(feature = "rust1", since = "1.0.0")]
493 impl AsRef<str> for str {
494     #[inline]
495     fn as_ref(&self) -> &str {
496         self
497     }
498 }