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