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