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