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