]> git.lizzy.rs Git - rust.git/blob - src/libcore/convert.rs
Removal pass for anonymous parameters
[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 str::FromStr;
52
53 /// A cheap reference-to-reference conversion. Used to convert a value to a
54 /// reference value within generic code.
55 ///
56 /// `AsRef` is very similar to, but serves a slightly different purpose than,
57 /// [`Borrow`].
58 ///
59 /// `AsRef` is to be used when wishing to convert to a reference of another
60 /// type.
61 /// `Borrow` is more related to the notion of taking the reference. It is
62 /// useful when wishing to abstract over the type of reference
63 /// (`&T`, `&mut T`) or allow both the referenced and owned type to be treated
64 /// in the same manner.
65 ///
66 /// The key difference between the two traits is the intention:
67 ///
68 /// - Use `AsRef` when goal is to simply convert into a reference
69 /// - Use `Borrow` when goal is related to writing code that is agnostic to the
70 ///   type of borrow and if is reference or value
71 ///
72 /// See [the book][book] for a more detailed comparison.
73 ///
74 /// [book]: ../../book/borrow-and-asref.html
75 /// [`Borrow`]: ../../std/borrow/trait.Borrow.html
76 ///
77 /// **Note: this trait must not fail**. If the conversion can fail, use a
78 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
79 ///
80 /// [`Option<T>`]: ../../std/option/enum.Option.html
81 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
82 ///
83 /// # Generic Implementations
84 ///
85 /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
86 ///   reference (e.g.: `foo.as_ref()` will work the same if `foo` has type
87 ///   `&mut Foo` or `&&mut Foo`)
88 ///
89 /// # Examples
90 ///
91 /// Both [`String`] and `&str` implement `AsRef<str>`:
92 ///
93 /// [`String`]: ../../std/string/struct.String.html
94 ///
95 /// ```
96 /// fn is_hello<T: AsRef<str>>(s: T) {
97 ///    assert_eq!("hello", s.as_ref());
98 /// }
99 ///
100 /// let s = "hello";
101 /// is_hello(s);
102 ///
103 /// let s = "hello".to_string();
104 /// is_hello(s);
105 /// ```
106 ///
107 #[stable(feature = "rust1", since = "1.0.0")]
108 pub trait AsRef<T: ?Sized> {
109     /// Performs the conversion.
110     #[stable(feature = "rust1", since = "1.0.0")]
111     fn as_ref(&self) -> &T;
112 }
113
114 /// A cheap, mutable reference-to-mutable reference conversion.
115 ///
116 /// This trait is similar to `AsRef` but used for converting between mutable
117 /// references.
118 ///
119 /// **Note: this trait must not fail**. If the conversion can fail, use a
120 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
121 ///
122 /// [`Option<T>`]: ../../std/option/enum.Option.html
123 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
124 ///
125 /// # Generic Implementations
126 ///
127 /// - `AsMut` auto-dereferences if the inner type is a reference or a mutable
128 ///   reference (e.g.: `foo.as_ref()` will work the same if `foo` has type
129 ///   `&mut Foo` or `&&mut Foo`)
130 ///
131 /// # Examples
132 ///
133 /// [`Box<T>`] implements `AsMut<T>`:
134 ///
135 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
136 ///
137 /// ```
138 /// fn add_one<T: AsMut<u64>>(num: &mut T) {
139 ///     *num.as_mut() += 1;
140 /// }
141 ///
142 /// let mut boxed_num = Box::new(0);
143 /// add_one(&mut boxed_num);
144 /// assert_eq!(*boxed_num, 1);
145 /// ```
146 ///
147 ///
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub trait AsMut<T: ?Sized> {
150     /// Performs the conversion.
151     #[stable(feature = "rust1", since = "1.0.0")]
152     fn as_mut(&mut self) -> &mut T;
153 }
154
155 /// A conversion that consumes `self`, which may or may not be expensive. The
156 /// reciprocal of [`From`][From].
157 ///
158 /// **Note: this trait must not fail**. If the conversion can fail, use
159 /// [`TryInto`] or a dedicated method which returns an [`Option<T>`] or a
160 /// [`Result<T, E>`].
161 ///
162 /// Library authors should not directly implement this trait, but should prefer
163 /// implementing the [`From`][From] trait, which offers greater flexibility and
164 /// provides an equivalent `Into` implementation for free, thanks to a blanket
165 /// implementation in the standard library.
166 ///
167 /// # Generic Implementations
168 ///
169 /// - [`From<T>`][From]` for U` implies `Into<U> for T`
170 /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
171 ///
172 /// # Examples
173 ///
174 /// [`String`] implements `Into<Vec<u8>>`:
175 ///
176 /// ```
177 /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
178 ///    let bytes = b"hello".to_vec();
179 ///    assert_eq!(bytes, s.into());
180 /// }
181 ///
182 /// let s = "hello".to_string();
183 /// is_hello(s);
184 /// ```
185 ///
186 /// [`TryInto`]: trait.TryInto.html
187 /// [`Option<T>`]: ../../std/option/enum.Option.html
188 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
189 /// [`String`]: ../../std/string/struct.String.html
190 /// [From]: trait.From.html
191 /// [`into`]: trait.Into.html#tymethod.into
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub trait Into<T>: Sized {
194     /// Performs the conversion.
195     #[stable(feature = "rust1", since = "1.0.0")]
196     fn into(self) -> T;
197 }
198
199 /// Simple and safe type conversions in to `Self`. It is the reciprocal of
200 /// `Into`.
201 ///
202 /// This trait is useful when performing error handling as described by
203 /// [the book][book] and is closely related to the `?` operator.
204 ///
205 /// When constructing a function that is capable of failing the return type
206 /// will generally be of the form `Result<T, E>`.
207 ///
208 /// The `From` trait allows for simplification of error handling by providing a
209 /// means of returning a single error type that encapsulates numerous possible
210 /// erroneous situations.
211 ///
212 /// This trait is not limited to error handling, rather the general case for
213 /// this trait would be in any type conversions to have an explicit definition
214 /// of how they are performed.
215 ///
216 /// **Note: this trait must not fail**. If the conversion can fail, use
217 /// [`TryFrom`] or a dedicated method which returns an [`Option<T>`] or a
218 /// [`Result<T, E>`].
219 ///
220 /// # Generic Implementations
221 ///
222 /// - `From<T> for U` implies [`Into<U>`]` for T`
223 /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
224 ///
225 /// # Examples
226 ///
227 /// [`String`] implements `From<&str>`:
228 ///
229 /// ```
230 /// let string = "hello".to_string();
231 /// let other_string = String::from("hello");
232 ///
233 /// assert_eq!(string, other_string);
234 /// ```
235 ///
236 /// An example usage for error handling:
237 ///
238 /// ```
239 /// use std::io::{self, Read};
240 /// use std::num;
241 ///
242 /// enum CliError {
243 ///     IoError(io::Error),
244 ///     ParseError(num::ParseIntError),
245 /// }
246 ///
247 /// impl From<io::Error> for CliError {
248 ///     fn from(error: io::Error) -> Self {
249 ///         CliError::IoError(error)
250 ///     }
251 /// }
252 ///
253 /// impl From<num::ParseIntError> for CliError {
254 ///     fn from(error: num::ParseIntError) -> Self {
255 ///         CliError::ParseError(error)
256 ///     }
257 /// }
258 ///
259 /// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
260 ///     let mut file = std::fs::File::open("test")?;
261 ///     let mut contents = String::new();
262 ///     file.read_to_string(&mut contents)?;
263 ///     let num: i32 = contents.trim().parse()?;
264 ///     Ok(num)
265 /// }
266 /// ```
267 ///
268 /// [`TryFrom`]: trait.TryFrom.html
269 /// [`Option<T>`]: ../../std/option/enum.Option.html
270 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
271 /// [`String`]: ../../std/string/struct.String.html
272 /// [`Into<U>`]: trait.Into.html
273 /// [`from`]: trait.From.html#tymethod.from
274 /// [book]: ../../book/error-handling.html
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub trait From<T>: Sized {
277     /// Performs the conversion.
278     #[stable(feature = "rust1", since = "1.0.0")]
279     fn from(t: T) -> Self;
280 }
281
282 /// An attempted conversion that consumes `self`, which may or may not be
283 /// expensive.
284 ///
285 /// Library authors should not directly implement this trait, but should prefer
286 /// implementing the [`TryFrom`] trait, which offers greater flexibility and
287 /// provides an equivalent `TryInto` implementation for free, thanks to a
288 /// blanket implementation in the standard library.
289 ///
290 /// [`TryFrom`]: trait.TryFrom.html
291 #[unstable(feature = "try_from", issue = "33417")]
292 pub trait TryInto<T>: Sized {
293     /// The type returned in the event of a conversion error.
294     type Error;
295
296     /// Performs the conversion.
297     fn try_into(self) -> Result<T, Self::Error>;
298 }
299
300 /// Attempt to construct `Self` via a conversion.
301 #[unstable(feature = "try_from", issue = "33417")]
302 pub trait TryFrom<T>: Sized {
303     /// The type returned in the event of a conversion error.
304     type Error;
305
306     /// Performs the conversion.
307     fn try_from(value: T) -> Result<Self, Self::Error>;
308 }
309
310 ////////////////////////////////////////////////////////////////////////////////
311 // GENERIC IMPLS
312 ////////////////////////////////////////////////////////////////////////////////
313
314 // As lifts over &
315 #[stable(feature = "rust1", since = "1.0.0")]
316 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U>
317 {
318     fn as_ref(&self) -> &U {
319         <T as AsRef<U>>::as_ref(*self)
320     }
321 }
322
323 // As lifts over &mut
324 #[stable(feature = "rust1", since = "1.0.0")]
325 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U>
326 {
327     fn as_ref(&self) -> &U {
328         <T as AsRef<U>>::as_ref(*self)
329     }
330 }
331
332 // FIXME (#23442): replace the above impls for &/&mut with the following more general one:
333 // // As lifts over Deref
334 // impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
335 //     fn as_ref(&self) -> &U {
336 //         self.deref().as_ref()
337 //     }
338 // }
339
340 // AsMut lifts over &mut
341 #[stable(feature = "rust1", since = "1.0.0")]
342 impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U>
343 {
344     fn as_mut(&mut self) -> &mut U {
345         (*self).as_mut()
346     }
347 }
348
349 // FIXME (#23442): replace the above impl for &mut with the following more general one:
350 // // AsMut lifts over DerefMut
351 // impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
352 //     fn as_mut(&mut self) -> &mut U {
353 //         self.deref_mut().as_mut()
354 //     }
355 // }
356
357 // From implies Into
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl<T, U> Into<U> for T where U: From<T>
360 {
361     fn into(self) -> U {
362         U::from(self)
363     }
364 }
365
366 // From (and thus Into) is reflexive
367 #[stable(feature = "rust1", since = "1.0.0")]
368 impl<T> From<T> for T {
369     fn from(t: T) -> T { t }
370 }
371
372
373 // TryFrom implies TryInto
374 #[unstable(feature = "try_from", issue = "33417")]
375 impl<T, U> TryInto<U> for T where U: TryFrom<T>
376 {
377     type Error = U::Error;
378
379     fn try_into(self) -> Result<U, U::Error> {
380         U::try_from(self)
381     }
382 }
383
384 ////////////////////////////////////////////////////////////////////////////////
385 // CONCRETE IMPLS
386 ////////////////////////////////////////////////////////////////////////////////
387
388 #[stable(feature = "rust1", since = "1.0.0")]
389 impl<T> AsRef<[T]> for [T] {
390     fn as_ref(&self) -> &[T] {
391         self
392     }
393 }
394
395 #[stable(feature = "rust1", since = "1.0.0")]
396 impl<T> AsMut<[T]> for [T] {
397     fn as_mut(&mut self) -> &mut [T] {
398         self
399     }
400 }
401
402 #[stable(feature = "rust1", since = "1.0.0")]
403 impl AsRef<str> for str {
404     #[inline]
405     fn as_ref(&self) -> &str {
406         self
407     }
408 }
409
410 // FromStr implies TryFrom<&str>
411 #[unstable(feature = "try_from", issue = "33417")]
412 impl<'a, T> TryFrom<&'a str> for T where T: FromStr
413 {
414     type Error = <T as FromStr>::Err;
415
416     fn try_from(s: &'a str) -> Result<T, Self::Error> {
417         FromStr::from_str(s)
418     }
419 }