]> git.lizzy.rs Git - rust.git/blob - src/libcore/convert/mod.rs
Auto merge of #69898 - spastorino:rename-rustc-guide2, r=Xanewok
[rust.git] / src / libcore / 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. Only implement [`Into`] or [`TryInto`]
22 //! when a conversion to a type outside the current crate is required.
23 //!
24 //! # Generic Implementations
25 //!
26 //! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference
27 //! - [`From`]`<U> for T` implies [`Into`]`<T> for U`
28 //! - [`TryFrom`]`<U> for T` implies [`TryInto`]`<T> for U`
29 //! - [`From`] and [`Into`] are reflexive, which means that all types can
30 //!   `into` themselves and `from` themselves
31 //!
32 //! See each trait for usage examples.
33 //!
34 //! [`Into`]: trait.Into.html
35 //! [`From`]: trait.From.html
36 //! [`TryFrom`]: trait.TryFrom.html
37 //! [`TryInto`]: trait.TryInto.html
38 //! [`AsRef`]: trait.AsRef.html
39 //! [`AsMut`]: trait.AsMut.html
40
41 #![stable(feature = "rust1", since = "1.0.0")]
42
43 use crate::fmt;
44 use crate::hash::{Hash, Hasher};
45
46 mod num;
47
48 #[unstable(feature = "convert_float_to_int", issue = "67057")]
49 pub use num::FloatToInt;
50
51 /// The identity function.
52 ///
53 /// Two things are important to note about this function:
54 ///
55 /// - It is not always equivalent to a closure like `|x| x`, since the
56 ///   closure may coerce `x` into a different type.
57 ///
58 /// - It moves the input `x` passed to the function.
59 ///
60 /// While it might seem strange to have a function that just returns back the
61 /// input, there are some interesting uses.
62 ///
63 /// # Examples
64 ///
65 /// Using `identity` to do nothing in a sequence of other, interesting,
66 /// functions:
67 ///
68 /// ```rust
69 /// use std::convert::identity;
70 ///
71 /// fn manipulation(x: u32) -> u32 {
72 ///     // Let's pretend that adding one is an interesting function.
73 ///     x + 1
74 /// }
75 ///
76 /// let _arr = &[identity, manipulation];
77 /// ```
78 ///
79 /// Using `identity` as a "do nothing" base case in a conditional:
80 ///
81 /// ```rust
82 /// use std::convert::identity;
83 ///
84 /// # let condition = true;
85 /// #
86 /// # fn manipulation(x: u32) -> u32 { x + 1 }
87 /// #
88 /// let do_stuff = if condition { manipulation } else { identity };
89 ///
90 /// // Do more interesting stuff...
91 ///
92 /// let _results = do_stuff(42);
93 /// ```
94 ///
95 /// Using `identity` to keep the `Some` variants of an iterator of `Option<T>`:
96 ///
97 /// ```rust
98 /// use std::convert::identity;
99 ///
100 /// let iter = vec![Some(1), None, Some(3)].into_iter();
101 /// let filtered = iter.filter_map(identity).collect::<Vec<_>>();
102 /// assert_eq!(vec![1, 3], filtered);
103 /// ```
104 #[stable(feature = "convert_id", since = "1.33.0")]
105 #[rustc_const_stable(feature = "const_identity", since = "1.33.0")]
106 #[inline]
107 pub const fn identity<T>(x: T) -> T {
108     x
109 }
110
111 /// Used to do a cheap reference-to-reference conversion.
112 ///
113 /// This trait is similar to [`AsMut`] which is used for converting between mutable references.
114 /// If you need to do a costly conversion it is better to implement [`From`] with type
115 /// `&T` or write a custom function.
116 ///
117 /// `AsRef` has the same signature as [`Borrow`], but [`Borrow`] is different in 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.
121 /// - [`Borrow`] also requires that [`Hash`], [`Eq`] and [`Ord`] for 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
131 ///   reference (e.g.: `foo.as_ref()` will work the same if `foo` has type
132 ///   `&mut Foo` or `&&mut Foo`)
133 ///
134 /// # Examples
135 ///
136 /// By using trait bounds we can accept arguments of different types as long as they can be
137 /// converted to the specified type `T`.
138 ///
139 /// For example: By creating a generic function that takes an `AsRef<str>` we express that we
140 /// want to accept all references that can be converted to [`&str`] as an argument.
141 /// Since both [`String`] and [`&str`] implement `AsRef<str>` we can accept both as input argument.
142 ///
143 /// [`Option<T>`]: ../../std/option/enum.Option.html
144 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
145 /// [`Borrow`]: ../../std/borrow/trait.Borrow.html
146 /// [`Hash`]: ../../std/hash/trait.Hash.html
147 /// [`Eq`]: ../../std/cmp/trait.Eq.html
148 /// [`Ord`]: ../../std/cmp/trait.Ord.html
149 /// [`&str`]: ../../std/primitive.str.html
150 /// [`String`]: ../../std/string/struct.String.html
151 ///
152 /// ```
153 /// fn is_hello<T: AsRef<str>>(s: T) {
154 ///    assert_eq!("hello", s.as_ref());
155 /// }
156 ///
157 /// let s = "hello";
158 /// is_hello(s);
159 ///
160 /// let s = "hello".to_string();
161 /// is_hello(s);
162 /// ```
163 #[stable(feature = "rust1", since = "1.0.0")]
164 pub trait AsRef<T: ?Sized> {
165     /// Performs the conversion.
166     #[stable(feature = "rust1", since = "1.0.0")]
167     fn as_ref(&self) -> &T;
168 }
169
170 /// Used to do a cheap mutable-to-mutable reference conversion.
171 ///
172 /// This trait is similar to [`AsRef`] but used for converting between mutable
173 /// references. If you need to do a costly conversion it is better to
174 /// implement [`From`] with type `&mut T` or write a custom function.
175 ///
176 /// **Note: This trait must not fail**. If the conversion can fail, use a
177 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
178 ///
179 /// [`Option<T>`]: ../../std/option/enum.Option.html
180 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
181 ///
182 /// # Generic Implementations
183 ///
184 /// - `AsMut` auto-dereferences if the inner type is a mutable reference
185 ///   (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo`
186 ///   or `&mut &mut Foo`)
187 ///
188 /// # Examples
189 ///
190 /// Using `AsMut` as trait bound for a generic function we can accept all mutable references
191 /// that can be converted to type `&mut T`. Because [`Box<T>`] implements `AsMut<T>` we can
192 /// write a function `add_one` that takes all arguments that can be converted to `&mut u64`.
193 /// Because [`Box<T>`] implements `AsMut<T>`, `add_one` accepts arguments of type
194 /// `&mut Box<u64>` as well:
195 ///
196 /// ```
197 /// fn add_one<T: AsMut<u64>>(num: &mut T) {
198 ///     *num.as_mut() += 1;
199 /// }
200 ///
201 /// let mut boxed_num = Box::new(0);
202 /// add_one(&mut boxed_num);
203 /// assert_eq!(*boxed_num, 1);
204 /// ```
205 ///
206 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
207 #[stable(feature = "rust1", since = "1.0.0")]
208 pub trait AsMut<T: ?Sized> {
209     /// Performs the conversion.
210     #[stable(feature = "rust1", since = "1.0.0")]
211     fn as_mut(&mut self) -> &mut T;
212 }
213
214 /// A value-to-value conversion that consumes the input value. The
215 /// opposite of [`From`].
216 ///
217 /// One should avoid implementing [`Into`] and implement [`From`] instead.
218 /// Implementing [`From`] automatically provides one with an implementation of [`Into`]
219 /// thanks to the blanket implementation in the standard library.
220 ///
221 /// Prefer using [`Into`] over [`From`] when specifying trait bounds on a generic function
222 /// to ensure that types that only implement [`Into`] can be used as well.
223 ///
224 /// **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`].
225 ///
226 /// # Generic Implementations
227 ///
228 /// - [`From`]`<T> for U` implies `Into<U> for T`
229 /// - [`Into`] is reflexive, which means that `Into<T> for T` is implemented
230 ///
231 /// # Implementing [`Into`] for conversions to external types in old versions of Rust
232 ///
233 /// Prior to Rust 1.41, if the destination type was not part of the current crate
234 /// then you couldn't implement [`From`] directly.
235 /// For example, take this code:
236 ///
237 /// ```
238 /// struct Wrapper<T>(Vec<T>);
239 /// impl<T> From<Wrapper<T>> for Vec<T> {
240 ///     fn from(w: Wrapper<T>) -> Vec<T> {
241 ///         w.0
242 ///     }
243 /// }
244 /// ```
245 /// This will fail to compile in older versions of the language because Rust's orphaning rules
246 /// used to be a little bit more strict. To bypass this, you could implement [`Into`] directly:
247 ///
248 /// ```
249 /// struct Wrapper<T>(Vec<T>);
250 /// impl<T> Into<Vec<T>> for Wrapper<T> {
251 ///     fn into(self) -> Vec<T> {
252 ///         self.0
253 ///     }
254 /// }
255 /// ```
256 ///
257 /// It is important to understand that [`Into`] does not provide a [`From`] implementation
258 /// (as [`From`] does with [`Into`]). Therefore, you should always try to implement [`From`]
259 /// and then fall back to [`Into`] if [`From`] can't be implemented.
260 ///
261 /// # Examples
262 ///
263 /// [`String`] implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>`:
264 ///
265 /// In order to express that we want a generic function to take all arguments that can be
266 /// converted to a specified type `T`, we can use a trait bound of [`Into`]`<T>`.
267 /// For example: The function `is_hello` takes all arguments that can be converted into a
268 /// [`Vec`]`<`[`u8`]`>`.
269 ///
270 /// ```
271 /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
272 ///    let bytes = b"hello".to_vec();
273 ///    assert_eq!(bytes, s.into());
274 /// }
275 ///
276 /// let s = "hello".to_string();
277 /// is_hello(s);
278 /// ```
279 ///
280 /// [`TryInto`]: trait.TryInto.html
281 /// [`Option<T>`]: ../../std/option/enum.Option.html
282 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
283 /// [`String`]: ../../std/string/struct.String.html
284 /// [`From`]: trait.From.html
285 /// [`Into`]: trait.Into.html
286 /// [`Vec`]: ../../std/vec/struct.Vec.html
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub trait Into<T>: Sized {
289     /// Performs the conversion.
290     #[stable(feature = "rust1", since = "1.0.0")]
291     fn into(self) -> T;
292 }
293
294 /// Used to do value-to-value conversions while consuming the input value. It is the reciprocal of
295 /// [`Into`].
296 ///
297 /// One should always prefer implementing `From` over [`Into`]
298 /// because implementing `From` automatically provides one with an implementation of [`Into`]
299 /// thanks to the blanket implementation in the standard library.
300 ///
301 /// Only implement [`Into`] if a conversion to a type outside the current crate is required.
302 /// `From` cannot do these type of conversions because of Rust's orphaning rules.
303 /// See [`Into`] for more details.
304 ///
305 /// Prefer using [`Into`] over using `From` when specifying trait bounds on a generic function.
306 /// This way, types that directly implement [`Into`] can be used as arguments as well.
307 ///
308 /// The `From` is also very useful when performing error handling. When constructing a function
309 /// that is capable of failing, the return type will generally be of the form `Result<T, E>`.
310 /// The `From` trait simplifies error handling by allowing a function to return a single error type
311 /// that encapsulate multiple error types. See the "Examples" section and [the book][book] for more
312 /// details.
313 ///
314 /// **Note: This trait must not fail**. If the conversion can fail, use [`TryFrom`].
315 ///
316 /// # Generic Implementations
317 ///
318 /// - `From<T> for U` implies [`Into`]`<U> for T`
319 /// - `From` is reflexive, which means that `From<T> for T` is implemented
320 ///
321 /// # Examples
322 ///
323 /// [`String`] implements `From<&str>`:
324 ///
325 /// An explicit conversion from a `&str` to a String is done as follows:
326 ///
327 /// ```
328 /// let string = "hello".to_string();
329 /// let other_string = String::from("hello");
330 ///
331 /// assert_eq!(string, other_string);
332 /// ```
333 ///
334 /// While performing error handling it is often useful to implement `From` for your own error type.
335 /// By converting underlying error types to our own custom error type that encapsulates the
336 /// underlying error type, we can return a single error type without losing information on the
337 /// underlying cause. The '?' operator automatically converts the underlying error type to our
338 /// custom error type by calling `Into<CliError>::into` which is automatically provided when
339 /// implementing `From`. The compiler then infers which implementation of `Into` should be used.
340 ///
341 /// ```
342 /// use std::fs;
343 /// use std::io;
344 /// use std::num;
345 ///
346 /// enum CliError {
347 ///     IoError(io::Error),
348 ///     ParseError(num::ParseIntError),
349 /// }
350 ///
351 /// impl From<io::Error> for CliError {
352 ///     fn from(error: io::Error) -> Self {
353 ///         CliError::IoError(error)
354 ///     }
355 /// }
356 ///
357 /// impl From<num::ParseIntError> for CliError {
358 ///     fn from(error: num::ParseIntError) -> Self {
359 ///         CliError::ParseError(error)
360 ///     }
361 /// }
362 ///
363 /// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
364 ///     let mut contents = fs::read_to_string(&file_name)?;
365 ///     let num: i32 = contents.trim().parse()?;
366 ///     Ok(num)
367 /// }
368 /// ```
369 ///
370 /// [`TryFrom`]: trait.TryFrom.html
371 /// [`Option<T>`]: ../../std/option/enum.Option.html
372 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
373 /// [`String`]: ../../std/string/struct.String.html
374 /// [`Into`]: trait.Into.html
375 /// [`from`]: trait.From.html#tymethod.from
376 /// [book]: ../../book/ch09-00-error-handling.html
377 #[stable(feature = "rust1", since = "1.0.0")]
378 #[rustc_on_unimplemented(on(
379     all(_Self = "&str", T = "std::string::String"),
380     note = "to coerce a `{T}` into a `{Self}`, use `&*` as a prefix",
381 ))]
382 pub trait From<T>: Sized {
383     /// Performs the conversion.
384     #[stable(feature = "rust1", since = "1.0.0")]
385     fn from(_: T) -> Self;
386 }
387
388 /// An attempted conversion that consumes `self`, which may or may not be
389 /// expensive.
390 ///
391 /// Library authors should usually not directly implement this trait,
392 /// but should prefer implementing the [`TryFrom`] trait, which offers
393 /// greater flexibility and provides an equivalent `TryInto`
394 /// implementation for free, thanks to a blanket implementation in the
395 /// standard library. For more information on this, see the
396 /// documentation for [`Into`].
397 ///
398 /// # Implementing `TryInto`
399 ///
400 /// This suffers the same restrictions and reasoning as implementing
401 /// [`Into`], see there for details.
402 ///
403 /// [`TryFrom`]: trait.TryFrom.html
404 /// [`Into`]: trait.Into.html
405 #[stable(feature = "try_from", since = "1.34.0")]
406 pub trait TryInto<T>: Sized {
407     /// The type returned in the event of a conversion error.
408     #[stable(feature = "try_from", since = "1.34.0")]
409     type Error;
410
411     /// Performs the conversion.
412     #[stable(feature = "try_from", since = "1.34.0")]
413     fn try_into(self) -> Result<T, Self::Error>;
414 }
415
416 /// Simple and safe type conversions that may fail in a controlled
417 /// way under some circumstances. It is the reciprocal of [`TryInto`].
418 ///
419 /// This is useful when you are doing a type conversion that may
420 /// trivially succeed but may also need special handling.
421 /// For example, there is no way to convert an [`i64`] into an [`i32`]
422 /// using the [`From`] trait, because an [`i64`] may contain a value
423 /// that an [`i32`] cannot represent and so the conversion would lose data.
424 /// This might be handled by truncating the [`i64`] to an [`i32`] (essentially
425 /// giving the [`i64`]'s value modulo [`i32::MAX`]) or by simply returning
426 /// [`i32::MAX`], or by some other method.  The [`From`] trait is intended
427 /// for perfect conversions, so the `TryFrom` trait informs the
428 /// programmer when a type conversion could go bad and lets them
429 /// decide how to handle it.
430 ///
431 /// # Generic Implementations
432 ///
433 /// - `TryFrom<T> for U` implies [`TryInto`]`<U> for T`
434 /// - [`try_from`] is reflexive, which means that `TryFrom<T> for T`
435 /// is implemented and cannot fail -- the associated `Error` type for
436 /// calling `T::try_from()` on a value of type `T` is [`Infallible`].
437 /// When the [`!`] type is stabilized [`Infallible`] and [`!`] will be
438 /// equivalent.
439 ///
440 /// `TryFrom<T>` can be implemented as follows:
441 ///
442 /// ```
443 /// use std::convert::TryFrom;
444 ///
445 /// struct GreaterThanZero(i32);
446 ///
447 /// impl TryFrom<i32> for GreaterThanZero {
448 ///     type Error = &'static str;
449 ///
450 ///     fn try_from(value: i32) -> Result<Self, Self::Error> {
451 ///         if value <= 0 {
452 ///             Err("GreaterThanZero only accepts value superior than zero!")
453 ///         } else {
454 ///             Ok(GreaterThanZero(value))
455 ///         }
456 ///     }
457 /// }
458 /// ```
459 ///
460 /// # Examples
461 ///
462 /// As described, [`i32`] implements `TryFrom<`[`i64`]`>`:
463 ///
464 /// ```
465 /// use std::convert::TryFrom;
466 ///
467 /// let big_number = 1_000_000_000_000i64;
468 /// // Silently truncates `big_number`, requires detecting
469 /// // and handling the truncation after the fact.
470 /// let smaller_number = big_number as i32;
471 /// assert_eq!(smaller_number, -727379968);
472 ///
473 /// // Returns an error because `big_number` is too big to
474 /// // fit in an `i32`.
475 /// let try_smaller_number = i32::try_from(big_number);
476 /// assert!(try_smaller_number.is_err());
477 ///
478 /// // Returns `Ok(3)`.
479 /// let try_successful_smaller_number = i32::try_from(3);
480 /// assert!(try_successful_smaller_number.is_ok());
481 /// ```
482 ///
483 /// [`try_from`]: trait.TryFrom.html#tymethod.try_from
484 /// [`TryInto`]: trait.TryInto.html
485 /// [`i32::MAX`]: ../../std/i32/constant.MAX.html
486 /// [`!`]: ../../std/primitive.never.html
487 /// [`Infallible`]: enum.Infallible.html
488 #[stable(feature = "try_from", since = "1.34.0")]
489 pub trait TryFrom<T>: Sized {
490     /// The type returned in the event of a conversion error.
491     #[stable(feature = "try_from", since = "1.34.0")]
492     type Error;
493
494     /// Performs the conversion.
495     #[stable(feature = "try_from", since = "1.34.0")]
496     fn try_from(value: T) -> Result<Self, Self::Error>;
497 }
498
499 ////////////////////////////////////////////////////////////////////////////////
500 // GENERIC IMPLS
501 ////////////////////////////////////////////////////////////////////////////////
502
503 // As lifts over &
504 #[stable(feature = "rust1", since = "1.0.0")]
505 impl<T: ?Sized, U: ?Sized> AsRef<U> for &T
506 where
507     T: AsRef<U>,
508 {
509     fn as_ref(&self) -> &U {
510         <T as AsRef<U>>::as_ref(*self)
511     }
512 }
513
514 // As lifts over &mut
515 #[stable(feature = "rust1", since = "1.0.0")]
516 impl<T: ?Sized, U: ?Sized> AsRef<U> for &mut T
517 where
518     T: AsRef<U>,
519 {
520     fn as_ref(&self) -> &U {
521         <T as AsRef<U>>::as_ref(*self)
522     }
523 }
524
525 // FIXME (#45742): replace the above impls for &/&mut with the following more general one:
526 // // As lifts over Deref
527 // impl<D: ?Sized + Deref<Target: AsRef<U>>, U: ?Sized> AsRef<U> for D {
528 //     fn as_ref(&self) -> &U {
529 //         self.deref().as_ref()
530 //     }
531 // }
532
533 // AsMut lifts over &mut
534 #[stable(feature = "rust1", since = "1.0.0")]
535 impl<T: ?Sized, U: ?Sized> AsMut<U> for &mut T
536 where
537     T: AsMut<U>,
538 {
539     fn as_mut(&mut self) -> &mut U {
540         (*self).as_mut()
541     }
542 }
543
544 // FIXME (#45742): replace the above impl for &mut with the following more general one:
545 // // AsMut lifts over DerefMut
546 // impl<D: ?Sized + Deref<Target: AsMut<U>>, U: ?Sized> AsMut<U> for D {
547 //     fn as_mut(&mut self) -> &mut U {
548 //         self.deref_mut().as_mut()
549 //     }
550 // }
551
552 // From implies Into
553 #[stable(feature = "rust1", since = "1.0.0")]
554 impl<T, U> Into<U> for T
555 where
556     U: From<T>,
557 {
558     fn into(self) -> U {
559         U::from(self)
560     }
561 }
562
563 // From (and thus Into) is reflexive
564 #[stable(feature = "rust1", since = "1.0.0")]
565 impl<T> From<T> for T {
566     fn from(t: T) -> T {
567         t
568     }
569 }
570
571 /// **Stability note:** This impl does not yet exist, but we are
572 /// "reserving space" to add it in the future. See
573 /// [rust-lang/rust#64715][#64715] for details.
574 ///
575 /// [#64715]: https://github.com/rust-lang/rust/issues/64715
576 #[stable(feature = "convert_infallible", since = "1.34.0")]
577 #[allow(unused_attributes)] // FIXME(#58633): do a principled fix instead.
578 #[rustc_reservation_impl = "permitting this impl would forbid us from adding \
579                             `impl<T> From<!> for T` later; see rust-lang/rust#64715 for details"]
580 impl<T> From<!> for T {
581     fn from(t: !) -> T {
582         t
583     }
584 }
585
586 // TryFrom implies TryInto
587 #[stable(feature = "try_from", since = "1.34.0")]
588 impl<T, U> TryInto<U> for T
589 where
590     U: TryFrom<T>,
591 {
592     type Error = U::Error;
593
594     fn try_into(self) -> Result<U, U::Error> {
595         U::try_from(self)
596     }
597 }
598
599 // Infallible conversions are semantically equivalent to fallible conversions
600 // with an uninhabited error type.
601 #[stable(feature = "try_from", since = "1.34.0")]
602 impl<T, U> TryFrom<U> for T
603 where
604     U: Into<T>,
605 {
606     type Error = Infallible;
607
608     fn try_from(value: U) -> Result<Self, Self::Error> {
609         Ok(U::into(value))
610     }
611 }
612
613 ////////////////////////////////////////////////////////////////////////////////
614 // CONCRETE IMPLS
615 ////////////////////////////////////////////////////////////////////////////////
616
617 #[stable(feature = "rust1", since = "1.0.0")]
618 impl<T> AsRef<[T]> for [T] {
619     fn as_ref(&self) -> &[T] {
620         self
621     }
622 }
623
624 #[stable(feature = "rust1", since = "1.0.0")]
625 impl<T> AsMut<[T]> for [T] {
626     fn as_mut(&mut self) -> &mut [T] {
627         self
628     }
629 }
630
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl AsRef<str> for str {
633     #[inline]
634     fn as_ref(&self) -> &str {
635         self
636     }
637 }
638
639 ////////////////////////////////////////////////////////////////////////////////
640 // THE NO-ERROR ERROR TYPE
641 ////////////////////////////////////////////////////////////////////////////////
642
643 /// The error type for errors that can never happen.
644 ///
645 /// Since this enum has no variant, a value of this type can never actually exist.
646 /// This can be useful for generic APIs that use [`Result`] and parameterize the error type,
647 /// to indicate that the result is always [`Ok`].
648 ///
649 /// For example, the [`TryFrom`] trait (conversion that returns a [`Result`])
650 /// has a blanket implementation for all types where a reverse [`Into`] implementation exists.
651 ///
652 /// ```ignore (illustrates std code, duplicating the impl in a doctest would be an error)
653 /// impl<T, U> TryFrom<U> for T where U: Into<T> {
654 ///     type Error = Infallible;
655 ///
656 ///     fn try_from(value: U) -> Result<Self, Infallible> {
657 ///         Ok(U::into(value))  // Never returns `Err`
658 ///     }
659 /// }
660 /// ```
661 ///
662 /// # Future compatibility
663 ///
664 /// This enum has the same role as [the `!` “never” type][never],
665 /// which is unstable in this version of Rust.
666 /// When `!` is stabilized, we plan to make `Infallible` a type alias to it:
667 ///
668 /// ```ignore (illustrates future std change)
669 /// pub type Infallible = !;
670 /// ```
671 ///
672 /// … and eventually deprecate `Infallible`.
673 ///
674 ///
675 /// However there is one case where `!` syntax can be used
676 /// before `!` is stabilized as a full-fleged type: in the position of a function’s return type.
677 /// Specifically, it is possible implementations for two different function pointer types:
678 ///
679 /// ```
680 /// trait MyTrait {}
681 /// impl MyTrait for fn() -> ! {}
682 /// impl MyTrait for fn() -> std::convert::Infallible {}
683 /// ```
684 ///
685 /// With `Infallible` being an enum, this code is valid.
686 /// However when `Infallible` becomes an alias for the never type,
687 /// the two `impl`s will start to overlap
688 /// and therefore will be disallowed by the language’s trait coherence rules.
689 ///
690 /// [`Ok`]: ../result/enum.Result.html#variant.Ok
691 /// [`Result`]: ../result/enum.Result.html
692 /// [`TryFrom`]: trait.TryFrom.html
693 /// [`Into`]: trait.Into.html
694 /// [never]: ../../std/primitive.never.html
695 #[stable(feature = "convert_infallible", since = "1.34.0")]
696 #[derive(Copy)]
697 pub enum Infallible {}
698
699 #[stable(feature = "convert_infallible", since = "1.34.0")]
700 impl Clone for Infallible {
701     fn clone(&self) -> Infallible {
702         match *self {}
703     }
704 }
705
706 #[stable(feature = "convert_infallible", since = "1.34.0")]
707 impl fmt::Debug for Infallible {
708     fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
709         match *self {}
710     }
711 }
712
713 #[stable(feature = "convert_infallible", since = "1.34.0")]
714 impl fmt::Display for Infallible {
715     fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
716         match *self {}
717     }
718 }
719
720 #[stable(feature = "convert_infallible", since = "1.34.0")]
721 impl PartialEq for Infallible {
722     fn eq(&self, _: &Infallible) -> bool {
723         match *self {}
724     }
725 }
726
727 #[stable(feature = "convert_infallible", since = "1.34.0")]
728 impl Eq for Infallible {}
729
730 #[stable(feature = "convert_infallible", since = "1.34.0")]
731 impl PartialOrd for Infallible {
732     fn partial_cmp(&self, _other: &Self) -> Option<crate::cmp::Ordering> {
733         match *self {}
734     }
735 }
736
737 #[stable(feature = "convert_infallible", since = "1.34.0")]
738 impl Ord for Infallible {
739     fn cmp(&self, _other: &Self) -> crate::cmp::Ordering {
740         match *self {}
741     }
742 }
743
744 #[stable(feature = "convert_infallible", since = "1.34.0")]
745 impl From<!> for Infallible {
746     fn from(x: !) -> Self {
747         x
748     }
749 }
750
751 #[stable(feature = "convert_infallible_hash", since = "1.44.0")]
752 impl Hash for Infallible {
753     fn hash<H: Hasher>(&self, _: &mut H) {
754         match *self {}
755     }
756 }