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