]> git.lizzy.rs Git - rust.git/blob - src/libcore/convert.rs
Rollup merge of #47846 - roblabla:bugfix-ocaml, r=kennytm
[rust.git] / src / libcore / convert.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Traits for conversions between types.
12 //!
13 //! The traits in this module provide a general way to talk about conversions
14 //! from one type to another. They follow the standard Rust conventions of
15 //! `as`/`into`/`from`.
16 //!
17 //! Like many traits, these are often used as bounds for generic functions, to
18 //! support arguments of multiple types.
19 //!
20 //! - Implement the `As*` traits for reference-to-reference conversions
21 //! - Implement the [`Into`] trait when you want to consume the value in the conversion
22 //! - The [`From`] trait is the most flexible, useful for value _and_ reference conversions
23 //! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], but allow for the
24 //!   conversion to fail
25 //!
26 //! As a library author, you should prefer implementing [`From<T>`][`From`] or
27 //! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
28 //! as [`From`] and [`TryFrom`] provide greater flexibility and offer
29 //! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a
30 //! blanket implementation in the standard library.
31 //!
32 //! # Generic Implementations
33 //!
34 //! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference
35 //! - [`From`]`<U> for T` implies [`Into`]`<T> for U`
36 //! - [`TryFrom`]`<U> for T` implies [`TryInto`]`<T> for U`
37 //! - [`From`] and [`Into`] are reflexive, which means that all types can
38 //!   `into` themselves and `from` themselves
39 //!
40 //! See each trait for usage examples.
41 //!
42 //! [`Into`]: trait.Into.html
43 //! [`From`]: trait.From.html
44 //! [`TryFrom`]: trait.TryFrom.html
45 //! [`TryInto`]: trait.TryInto.html
46 //! [`AsRef`]: trait.AsRef.html
47 //! [`AsMut`]: trait.AsMut.html
48
49 #![stable(feature = "rust1", since = "1.0.0")]
50
51 use fmt;
52
53 /// A type used as the error type for implementations of fallible conversion
54 /// traits in cases where conversions cannot actually fail.
55 ///
56 /// Because `Infallible` has no variants, a value of this type can never exist.
57 /// It is used only to satisfy trait signatures that expect an error type, and
58 /// signals to both the compiler and the user that the error case is impossible.
59 #[unstable(feature = "try_from", issue = "33417")]
60 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
61 pub enum Infallible {}
62
63 #[unstable(feature = "try_from", issue = "33417")]
64 impl fmt::Display for Infallible {
65     fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
66         match *self {
67         }
68     }
69 }
70 /// A cheap reference-to-reference conversion. Used to convert a value to a
71 /// reference value within generic code.
72 ///
73 /// `AsRef` is very similar to, but serves a slightly different purpose than,
74 /// [`Borrow`].
75 ///
76 /// `AsRef` is to be used when wishing to convert to a reference of another
77 /// type.
78 /// `Borrow` is more related to the notion of taking the reference. It is
79 /// useful when wishing to abstract over the type of reference
80 /// (`&T`, `&mut T`) or allow both the referenced and owned type to be treated
81 /// in the same manner.
82 ///
83 /// The key difference between the two traits is the intention:
84 ///
85 /// - Use `AsRef` when goal is to simply convert into a reference
86 /// - Use `Borrow` when goal is related to writing code that is agnostic to the
87 ///   type of borrow and if is reference or value
88 ///
89 /// See [the book][book] for a more detailed comparison.
90 ///
91 /// [book]: ../../book/first-edition/borrow-and-asref.html
92 /// [`Borrow`]: ../../std/borrow/trait.Borrow.html
93 ///
94 /// **Note: this trait must not fail**. If the conversion can fail, use a
95 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
96 ///
97 /// [`Option<T>`]: ../../std/option/enum.Option.html
98 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
99 ///
100 /// # Generic Implementations
101 ///
102 /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
103 ///   reference (e.g.: `foo.as_ref()` will work the same if `foo` has type
104 ///   `&mut Foo` or `&&mut Foo`)
105 ///
106 /// # Examples
107 ///
108 /// Both [`String`] and `&str` implement `AsRef<str>`:
109 ///
110 /// [`String`]: ../../std/string/struct.String.html
111 ///
112 /// ```
113 /// fn is_hello<T: AsRef<str>>(s: T) {
114 ///    assert_eq!("hello", s.as_ref());
115 /// }
116 ///
117 /// let s = "hello";
118 /// is_hello(s);
119 ///
120 /// let s = "hello".to_string();
121 /// is_hello(s);
122 /// ```
123 ///
124 #[stable(feature = "rust1", since = "1.0.0")]
125 pub trait AsRef<T: ?Sized> {
126     /// Performs the conversion.
127     #[stable(feature = "rust1", since = "1.0.0")]
128     fn as_ref(&self) -> &T;
129 }
130
131 /// A cheap, mutable reference-to-mutable reference conversion.
132 ///
133 /// This trait is similar to `AsRef` but used for converting between mutable
134 /// references.
135 ///
136 /// **Note: this trait must not fail**. If the conversion can fail, use a
137 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
138 ///
139 /// [`Option<T>`]: ../../std/option/enum.Option.html
140 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
141 ///
142 /// # Generic Implementations
143 ///
144 /// - `AsMut` auto-dereferences if the inner type is a mutable reference
145 ///   (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo`
146 ///   or `&mut &mut Foo`)
147 ///
148 /// # Examples
149 ///
150 /// [`Box<T>`] implements `AsMut<T>`:
151 ///
152 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
153 ///
154 /// ```
155 /// fn add_one<T: AsMut<u64>>(num: &mut T) {
156 ///     *num.as_mut() += 1;
157 /// }
158 ///
159 /// let mut boxed_num = Box::new(0);
160 /// add_one(&mut boxed_num);
161 /// assert_eq!(*boxed_num, 1);
162 /// ```
163 ///
164 ///
165 #[stable(feature = "rust1", since = "1.0.0")]
166 pub trait AsMut<T: ?Sized> {
167     /// Performs the conversion.
168     #[stable(feature = "rust1", since = "1.0.0")]
169     fn as_mut(&mut self) -> &mut T;
170 }
171
172 /// A conversion that consumes `self`, which may or may not be expensive. The
173 /// reciprocal of [`From`][From].
174 ///
175 /// **Note: this trait must not fail**. If the conversion can fail, use
176 /// [`TryInto`] or a dedicated method which returns an [`Option<T>`] or a
177 /// [`Result<T, E>`].
178 ///
179 /// Library authors should not directly implement this trait, but should prefer
180 /// implementing the [`From`][From] trait, which offers greater flexibility and
181 /// provides an equivalent `Into` implementation for free, thanks to a blanket
182 /// implementation in the standard library.
183 ///
184 /// # Generic Implementations
185 ///
186 /// - [`From<T>`][From]` for U` implies `Into<U> for T`
187 /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
188 ///
189 /// # Implementing `Into`
190 ///
191 /// There is one exception to implementing `Into`, and it's kind of esoteric.
192 /// If the destination type is not part of the current crate, and it uses a
193 /// generic variable, then you can't implement `From` directly.  For example,
194 /// take this crate:
195 ///
196 /// ```compile_fail
197 /// struct Wrapper<T>(Vec<T>);
198 /// impl<T> From<Wrapper<T>> for Vec<T> {
199 ///     fn from(w: Wrapper<T>) -> Vec<T> {
200 ///         w.0
201 ///     }
202 /// }
203 /// ```
204 ///
205 /// To fix this, you can implement `Into` directly:
206 ///
207 /// ```
208 /// struct Wrapper<T>(Vec<T>);
209 /// impl<T> Into<Vec<T>> for Wrapper<T> {
210 ///     fn into(self) -> Vec<T> {
211 ///         self.0
212 ///     }
213 /// }
214 /// ```
215 ///
216 /// This won't always allow the conversion: for example, `try!` and `?`
217 /// always use `From`. However, in most cases, people use `Into` to do the
218 /// conversions, and this will allow that.
219 ///
220 /// In almost all cases, you should try to implement `From`, then fall back
221 /// to `Into` if `From` can't be implemented.
222 ///
223 /// # Examples
224 ///
225 /// [`String`] implements `Into<Vec<u8>>`:
226 ///
227 /// ```
228 /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
229 ///    let bytes = b"hello".to_vec();
230 ///    assert_eq!(bytes, s.into());
231 /// }
232 ///
233 /// let s = "hello".to_string();
234 /// is_hello(s);
235 /// ```
236 ///
237 /// [`TryInto`]: trait.TryInto.html
238 /// [`Option<T>`]: ../../std/option/enum.Option.html
239 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
240 /// [`String`]: ../../std/string/struct.String.html
241 /// [From]: trait.From.html
242 /// [`into`]: trait.Into.html#tymethod.into
243 #[stable(feature = "rust1", since = "1.0.0")]
244 pub trait Into<T>: Sized {
245     /// Performs the conversion.
246     #[stable(feature = "rust1", since = "1.0.0")]
247     fn into(self) -> T;
248 }
249
250 /// Simple and safe type conversions in to `Self`. It is the reciprocal of
251 /// `Into`.
252 ///
253 /// This trait is useful when performing error handling as described by
254 /// [the book][book] and is closely related to the `?` operator.
255 ///
256 /// When constructing a function that is capable of failing the return type
257 /// will generally be of the form `Result<T, E>`.
258 ///
259 /// The `From` trait allows for simplification of error handling by providing a
260 /// means of returning a single error type that encapsulates numerous possible
261 /// erroneous situations.
262 ///
263 /// This trait is not limited to error handling, rather the general case for
264 /// this trait would be in any type conversions to have an explicit definition
265 /// of how they are performed.
266 ///
267 /// **Note: this trait must not fail**. If the conversion can fail, use
268 /// [`TryFrom`] or a dedicated method which returns an [`Option<T>`] or a
269 /// [`Result<T, E>`].
270 ///
271 /// # Generic Implementations
272 ///
273 /// - `From<T> for U` implies [`Into<U>`]` for T`
274 /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
275 ///
276 /// # Examples
277 ///
278 /// [`String`] implements `From<&str>`:
279 ///
280 /// ```
281 /// let string = "hello".to_string();
282 /// let other_string = String::from("hello");
283 ///
284 /// assert_eq!(string, other_string);
285 /// ```
286 ///
287 /// An example usage for error handling:
288 ///
289 /// ```
290 /// use std::io::{self, Read};
291 /// use std::num;
292 ///
293 /// enum CliError {
294 ///     IoError(io::Error),
295 ///     ParseError(num::ParseIntError),
296 /// }
297 ///
298 /// impl From<io::Error> for CliError {
299 ///     fn from(error: io::Error) -> Self {
300 ///         CliError::IoError(error)
301 ///     }
302 /// }
303 ///
304 /// impl From<num::ParseIntError> for CliError {
305 ///     fn from(error: num::ParseIntError) -> Self {
306 ///         CliError::ParseError(error)
307 ///     }
308 /// }
309 ///
310 /// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
311 ///     let mut file = std::fs::File::open("test")?;
312 ///     let mut contents = String::new();
313 ///     file.read_to_string(&mut contents)?;
314 ///     let num: i32 = contents.trim().parse()?;
315 ///     Ok(num)
316 /// }
317 /// ```
318 ///
319 /// [`TryFrom`]: trait.TryFrom.html
320 /// [`Option<T>`]: ../../std/option/enum.Option.html
321 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
322 /// [`String`]: ../../std/string/struct.String.html
323 /// [`Into<U>`]: trait.Into.html
324 /// [`from`]: trait.From.html#tymethod.from
325 /// [book]: ../../book/first-edition/error-handling.html
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub trait From<T>: Sized {
328     /// Performs the conversion.
329     #[stable(feature = "rust1", since = "1.0.0")]
330     fn from(_: T) -> Self;
331 }
332
333 /// An attempted conversion that consumes `self`, which may or may not be
334 /// expensive.
335 ///
336 /// Library authors should not directly implement this trait, but should prefer
337 /// implementing the [`TryFrom`] trait, which offers greater flexibility and
338 /// provides an equivalent `TryInto` implementation for free, thanks to a
339 /// blanket implementation in the standard library. For more information on this,
340 /// see the documentation for [`Into`].
341 ///
342 /// [`TryFrom`]: trait.TryFrom.html
343 /// [`Into`]: trait.Into.html
344 #[unstable(feature = "try_from", issue = "33417")]
345 pub trait TryInto<T>: Sized {
346     /// The type returned in the event of a conversion error.
347     type Error;
348
349     /// Performs the conversion.
350     fn try_into(self) -> Result<T, Self::Error>;
351 }
352
353 /// Attempt to construct `Self` via a conversion.
354 #[unstable(feature = "try_from", issue = "33417")]
355 pub trait TryFrom<T>: Sized {
356     /// The type returned in the event of a conversion error.
357     type Error;
358
359     /// Performs the conversion.
360     fn try_from(value: T) -> Result<Self, Self::Error>;
361 }
362
363 ////////////////////////////////////////////////////////////////////////////////
364 // GENERIC IMPLS
365 ////////////////////////////////////////////////////////////////////////////////
366
367 // As lifts over &
368 #[stable(feature = "rust1", since = "1.0.0")]
369 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U>
370 {
371     fn as_ref(&self) -> &U {
372         <T as AsRef<U>>::as_ref(*self)
373     }
374 }
375
376 // As lifts over &mut
377 #[stable(feature = "rust1", since = "1.0.0")]
378 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U>
379 {
380     fn as_ref(&self) -> &U {
381         <T as AsRef<U>>::as_ref(*self)
382     }
383 }
384
385 // FIXME (#23442): replace the above impls for &/&mut with the following more general one:
386 // // As lifts over Deref
387 // impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
388 //     fn as_ref(&self) -> &U {
389 //         self.deref().as_ref()
390 //     }
391 // }
392
393 // AsMut lifts over &mut
394 #[stable(feature = "rust1", since = "1.0.0")]
395 impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U>
396 {
397     fn as_mut(&mut self) -> &mut U {
398         (*self).as_mut()
399     }
400 }
401
402 // FIXME (#23442): replace the above impl for &mut with the following more general one:
403 // // AsMut lifts over DerefMut
404 // impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
405 //     fn as_mut(&mut self) -> &mut U {
406 //         self.deref_mut().as_mut()
407 //     }
408 // }
409
410 // From implies Into
411 #[stable(feature = "rust1", since = "1.0.0")]
412 impl<T, U> Into<U> for T where U: From<T>
413 {
414     fn into(self) -> U {
415         U::from(self)
416     }
417 }
418
419 // From (and thus Into) is reflexive
420 #[stable(feature = "rust1", since = "1.0.0")]
421 impl<T> From<T> for T {
422     fn from(t: T) -> T { t }
423 }
424
425
426 // TryFrom implies TryInto
427 #[unstable(feature = "try_from", issue = "33417")]
428 impl<T, U> TryInto<U> for T where U: TryFrom<T>
429 {
430     type Error = U::Error;
431
432     fn try_into(self) -> Result<U, U::Error> {
433         U::try_from(self)
434     }
435 }
436
437 // Infallible conversions are semantically equivalent to fallible conversions
438 // with an uninhabited error type.
439 #[unstable(feature = "try_from", issue = "33417")]
440 impl<T, U> TryFrom<U> for T where T: From<U> {
441     type Error = Infallible;
442
443     fn try_from(value: U) -> Result<Self, Self::Error> {
444         Ok(T::from(value))
445     }
446 }
447
448 ////////////////////////////////////////////////////////////////////////////////
449 // CONCRETE IMPLS
450 ////////////////////////////////////////////////////////////////////////////////
451
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl<T> AsRef<[T]> for [T] {
454     fn as_ref(&self) -> &[T] {
455         self
456     }
457 }
458
459 #[stable(feature = "rust1", since = "1.0.0")]
460 impl<T> AsMut<[T]> for [T] {
461     fn as_mut(&mut self) -> &mut [T] {
462         self
463     }
464 }
465
466 #[stable(feature = "rust1", since = "1.0.0")]
467 impl AsRef<str> for str {
468     #[inline]
469     fn as_ref(&self) -> &str {
470         self
471     }
472 }