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