]> git.lizzy.rs Git - rust.git/blob - src/libcore/convert.rs
constify parts of libcore.
[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 /// An identity function.
52 ///
53 /// Two things are important to note about this function:
54 ///
55 /// - It is not always equivalent to a closure like `|x| x` since the
56 ///   closure may coerce `x` into a different type.
57 ///
58 /// - It moves the input `x` passed to the function.
59 ///
60 /// While it might seem strange to have a function that just returns back the
61 /// input, there are some interesting uses.
62 ///
63 /// # Examples
64 ///
65 /// Using `identity` to do nothing among other interesting functions:
66 ///
67 /// ```rust
68 /// #![feature(convert_id)]
69 /// use std::convert::identity;
70 ///
71 /// fn manipulation(x: u32) -> u32 {
72 ///     // Let's assume that this function does something interesting.
73 ///     x + 1
74 /// }
75 ///
76 /// let _arr = &[identity, manipulation];
77 /// ```
78 ///
79 /// Using `identity` to get a function that changes nothing in a conditional:
80 ///
81 /// ```rust
82 /// #![feature(convert_id)]
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 /// #![feature(convert_id)]
100 /// use std::convert::identity;
101 ///
102 /// let iter = vec![Some(1), None, Some(3)].into_iter();
103 /// let filtered = iter.filter_map(identity).collect::<Vec<_>>();
104 /// assert_eq!(vec![1, 3], filtered);
105 /// ```
106 #[unstable(feature = "convert_id", issue = "53500")]
107 #[inline]
108 pub const fn identity<T>(x: T) -> T { x }
109
110 /// A cheap reference-to-reference conversion. Used to convert a value to a
111 /// reference value within generic code.
112 ///
113 /// `AsRef` is very similar to, but serves a slightly different purpose than,
114 /// [`Borrow`].
115 ///
116 /// `AsRef` is to be used when wishing to convert to a reference of another
117 /// type.
118 /// `Borrow` is more related to the notion of taking the reference. It is
119 /// useful when wishing to abstract over the type of reference
120 /// (`&T`, `&mut T`) or allow both the referenced and owned type to be treated
121 /// in the same manner.
122 ///
123 /// The key difference between the two traits is the intention:
124 ///
125 /// - Use `AsRef` when the goal is to simply convert into a reference
126 /// - Use `Borrow` when the goal is related to writing code that is agnostic to
127 ///   the type of borrow and whether it is a reference or value
128 ///
129 /// See [the book][book] for a more detailed comparison.
130 ///
131 /// [book]: ../../book/first-edition/borrow-and-asref.html
132 /// [`Borrow`]: ../../std/borrow/trait.Borrow.html
133 ///
134 /// **Note: this trait must not fail**. If the conversion can fail, use a
135 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
136 ///
137 /// [`Option<T>`]: ../../std/option/enum.Option.html
138 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
139 ///
140 /// # Generic Implementations
141 ///
142 /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
143 ///   reference (e.g.: `foo.as_ref()` will work the same if `foo` has type
144 ///   `&mut Foo` or `&&mut Foo`)
145 ///
146 /// # Examples
147 ///
148 /// Both [`String`] and `&str` implement `AsRef<str>`:
149 ///
150 /// [`String`]: ../../std/string/struct.String.html
151 ///
152 /// ```
153 /// fn is_hello<T: AsRef<str>>(s: T) {
154 ///    assert_eq!("hello", s.as_ref());
155 /// }
156 ///
157 /// let s = "hello";
158 /// is_hello(s);
159 ///
160 /// let s = "hello".to_string();
161 /// is_hello(s);
162 /// ```
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 /// A cheap, mutable reference-to-mutable reference conversion.
172 ///
173 /// This trait is similar to `AsRef` but used for converting between mutable
174 /// references.
175 ///
176 /// **Note: this trait must not fail**. If the conversion can fail, use a
177 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
178 ///
179 /// [`Option<T>`]: ../../std/option/enum.Option.html
180 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
181 ///
182 /// # Generic Implementations
183 ///
184 /// - `AsMut` auto-dereferences if the inner type is a mutable reference
185 ///   (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo`
186 ///   or `&mut &mut Foo`)
187 ///
188 /// # Examples
189 ///
190 /// [`Box<T>`] implements `AsMut<T>`:
191 ///
192 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
193 ///
194 /// ```
195 /// fn add_one<T: AsMut<u64>>(num: &mut T) {
196 ///     *num.as_mut() += 1;
197 /// }
198 ///
199 /// let mut boxed_num = Box::new(0);
200 /// add_one(&mut boxed_num);
201 /// assert_eq!(*boxed_num, 1);
202 /// ```
203 ///
204 ///
205 #[stable(feature = "rust1", since = "1.0.0")]
206 pub trait AsMut<T: ?Sized> {
207     /// Performs the conversion.
208     #[stable(feature = "rust1", since = "1.0.0")]
209     fn as_mut(&mut self) -> &mut T;
210 }
211
212 /// A conversion that consumes `self`, which may or may not be expensive. The
213 /// reciprocal of [`From`][From].
214 ///
215 /// **Note: this trait must not fail**. If the conversion can fail, use
216 /// [`TryInto`] or a dedicated method which returns an [`Option<T>`] or a
217 /// [`Result<T, E>`].
218 ///
219 /// Library authors should not directly implement this trait, but should prefer
220 /// implementing the [`From`][From] trait, which offers greater flexibility and
221 /// provides an equivalent `Into` implementation for free, thanks to a blanket
222 /// implementation in the standard library.
223 ///
224 /// # Generic Implementations
225 ///
226 /// - [`From<T>`][From]` for U` implies `Into<U> for T`
227 /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
228 ///
229 /// # Implementing `Into`
230 ///
231 /// There is one exception to implementing `Into`, and it's kind of esoteric.
232 /// If the destination type is not part of the current crate, and it uses a
233 /// generic variable, then you can't implement `From` directly.  For example,
234 /// take this crate:
235 ///
236 /// ```compile_fail
237 /// struct Wrapper<T>(Vec<T>);
238 /// impl<T> From<Wrapper<T>> for Vec<T> {
239 ///     fn from(w: Wrapper<T>) -> Vec<T> {
240 ///         w.0
241 ///     }
242 /// }
243 /// ```
244 ///
245 /// To fix this, you can implement `Into` directly:
246 ///
247 /// ```
248 /// struct Wrapper<T>(Vec<T>);
249 /// impl<T> Into<Vec<T>> for Wrapper<T> {
250 ///     fn into(self) -> Vec<T> {
251 ///         self.0
252 ///     }
253 /// }
254 /// ```
255 ///
256 /// This won't always allow the conversion: for example, `try!` and `?`
257 /// always use `From`. However, in most cases, people use `Into` to do the
258 /// conversions, and this will allow that.
259 ///
260 /// In almost all cases, you should try to implement `From`, then fall back
261 /// to `Into` if `From` can't be implemented.
262 ///
263 /// # Examples
264 ///
265 /// [`String`] implements `Into<Vec<u8>>`:
266 ///
267 /// ```
268 /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
269 ///    let bytes = b"hello".to_vec();
270 ///    assert_eq!(bytes, s.into());
271 /// }
272 ///
273 /// let s = "hello".to_string();
274 /// is_hello(s);
275 /// ```
276 ///
277 /// [`TryInto`]: trait.TryInto.html
278 /// [`Option<T>`]: ../../std/option/enum.Option.html
279 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
280 /// [`String`]: ../../std/string/struct.String.html
281 /// [From]: trait.From.html
282 /// [`into`]: trait.Into.html#tymethod.into
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 /// Simple and safe type conversions in to `Self`. It is the reciprocal of
291 /// `Into`.
292 ///
293 /// This trait is useful when performing error handling as described by
294 /// [the book][book] and is closely related to the `?` operator.
295 ///
296 /// When constructing a function that is capable of failing the return type
297 /// will generally be of the form `Result<T, E>`.
298 ///
299 /// The `From` trait allows for simplification of error handling by providing a
300 /// means of returning a single error type that encapsulates numerous possible
301 /// erroneous situations.
302 ///
303 /// This trait is not limited to error handling, rather the general case for
304 /// this trait would be in any type conversions to have an explicit definition
305 /// of how they are performed.
306 ///
307 /// **Note: this trait must not fail**. If the conversion can fail, use
308 /// [`TryFrom`] or a dedicated method which returns an [`Option<T>`] or a
309 /// [`Result<T, E>`].
310 ///
311 /// # Generic Implementations
312 ///
313 /// - `From<T> for U` implies [`Into<U>`]` for T`
314 /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
315 ///
316 /// # Examples
317 ///
318 /// [`String`] implements `From<&str>`:
319 ///
320 /// ```
321 /// let string = "hello".to_string();
322 /// let other_string = String::from("hello");
323 ///
324 /// assert_eq!(string, other_string);
325 /// ```
326 ///
327 /// An example usage for error handling:
328 ///
329 /// ```
330 /// use std::io::{self, Read};
331 /// use std::num;
332 ///
333 /// enum CliError {
334 ///     IoError(io::Error),
335 ///     ParseError(num::ParseIntError),
336 /// }
337 ///
338 /// impl From<io::Error> for CliError {
339 ///     fn from(error: io::Error) -> Self {
340 ///         CliError::IoError(error)
341 ///     }
342 /// }
343 ///
344 /// impl From<num::ParseIntError> for CliError {
345 ///     fn from(error: num::ParseIntError) -> Self {
346 ///         CliError::ParseError(error)
347 ///     }
348 /// }
349 ///
350 /// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
351 ///     let mut file = std::fs::File::open("test")?;
352 ///     let mut contents = String::new();
353 ///     file.read_to_string(&mut contents)?;
354 ///     let num: i32 = contents.trim().parse()?;
355 ///     Ok(num)
356 /// }
357 /// ```
358 ///
359 /// [`TryFrom`]: trait.TryFrom.html
360 /// [`Option<T>`]: ../../std/option/enum.Option.html
361 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
362 /// [`String`]: ../../std/string/struct.String.html
363 /// [`Into<U>`]: trait.Into.html
364 /// [`from`]: trait.From.html#tymethod.from
365 /// [book]: ../../book/first-edition/error-handling.html
366 #[stable(feature = "rust1", since = "1.0.0")]
367 pub trait From<T>: Sized {
368     /// Performs the conversion.
369     #[stable(feature = "rust1", since = "1.0.0")]
370     fn from(_: T) -> Self;
371 }
372
373 /// An attempted conversion that consumes `self`, which may or may not be
374 /// expensive.
375 ///
376 /// Library authors should not directly implement this trait, but should prefer
377 /// implementing the [`TryFrom`] trait, which offers greater flexibility and
378 /// provides an equivalent `TryInto` implementation for free, thanks to a
379 /// blanket implementation in the standard library. For more information on this,
380 /// see the documentation for [`Into`].
381 ///
382 /// [`TryFrom`]: trait.TryFrom.html
383 /// [`Into`]: trait.Into.html
384 #[unstable(feature = "try_from", issue = "33417")]
385 pub trait TryInto<T>: Sized {
386     /// The type returned in the event of a conversion error.
387     type Error;
388
389     /// Performs the conversion.
390     fn try_into(self) -> Result<T, Self::Error>;
391 }
392
393 /// Attempt to construct `Self` via a conversion.
394 #[unstable(feature = "try_from", issue = "33417")]
395 pub trait TryFrom<T>: Sized {
396     /// The type returned in the event of a conversion error.
397     type Error;
398
399     /// Performs the conversion.
400     fn try_from(value: T) -> Result<Self, Self::Error>;
401 }
402
403 ////////////////////////////////////////////////////////////////////////////////
404 // GENERIC IMPLS
405 ////////////////////////////////////////////////////////////////////////////////
406
407 // As lifts over &
408 #[stable(feature = "rust1", since = "1.0.0")]
409 impl<T: ?Sized, U: ?Sized> AsRef<U> for &T where T: AsRef<U>
410 {
411     fn as_ref(&self) -> &U {
412         <T as AsRef<U>>::as_ref(*self)
413     }
414 }
415
416 // As lifts over &mut
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl<T: ?Sized, U: ?Sized> AsRef<U> for &mut T where T: AsRef<U>
419 {
420     fn as_ref(&self) -> &U {
421         <T as AsRef<U>>::as_ref(*self)
422     }
423 }
424
425 // FIXME (#45742): replace the above impls for &/&mut with the following more general one:
426 // // As lifts over Deref
427 // impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
428 //     fn as_ref(&self) -> &U {
429 //         self.deref().as_ref()
430 //     }
431 // }
432
433 // AsMut lifts over &mut
434 #[stable(feature = "rust1", since = "1.0.0")]
435 impl<T: ?Sized, U: ?Sized> AsMut<U> for &mut T where T: AsMut<U>
436 {
437     fn as_mut(&mut self) -> &mut U {
438         (*self).as_mut()
439     }
440 }
441
442 // FIXME (#45742): replace the above impl for &mut with the following more general one:
443 // // AsMut lifts over DerefMut
444 // impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
445 //     fn as_mut(&mut self) -> &mut U {
446 //         self.deref_mut().as_mut()
447 //     }
448 // }
449
450 // From implies Into
451 #[stable(feature = "rust1", since = "1.0.0")]
452 impl<T, U> Into<U> for T where U: From<T>
453 {
454     fn into(self) -> U {
455         U::from(self)
456     }
457 }
458
459 // From (and thus Into) is reflexive
460 #[stable(feature = "rust1", since = "1.0.0")]
461 impl<T> From<T> for T {
462     fn from(t: T) -> T { t }
463 }
464
465
466 // TryFrom implies TryInto
467 #[unstable(feature = "try_from", issue = "33417")]
468 impl<T, U> TryInto<U> for T where U: TryFrom<T>
469 {
470     type Error = U::Error;
471
472     fn try_into(self) -> Result<U, U::Error> {
473         U::try_from(self)
474     }
475 }
476
477 // Infallible conversions are semantically equivalent to fallible conversions
478 // with an uninhabited error type.
479 #[unstable(feature = "try_from", issue = "33417")]
480 impl<T, U> TryFrom<U> for T where T: From<U> {
481     type Error = !;
482
483     fn try_from(value: U) -> Result<Self, Self::Error> {
484         Ok(T::from(value))
485     }
486 }
487
488 ////////////////////////////////////////////////////////////////////////////////
489 // CONCRETE IMPLS
490 ////////////////////////////////////////////////////////////////////////////////
491
492 #[stable(feature = "rust1", since = "1.0.0")]
493 impl<T> AsRef<[T]> for [T] {
494     fn as_ref(&self) -> &[T] {
495         self
496     }
497 }
498
499 #[stable(feature = "rust1", since = "1.0.0")]
500 impl<T> AsMut<[T]> for [T] {
501     fn as_mut(&mut self) -> &mut [T] {
502         self
503     }
504 }
505
506 #[stable(feature = "rust1", since = "1.0.0")]
507 impl AsRef<str> for str {
508     #[inline]
509     fn as_ref(&self) -> &str {
510         self
511     }
512 }