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