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