]>
Commit | Line | Data |
---|---|---|
c34b1796 AL |
1 | //! Traits for conversions between types. |
2 | //! | |
532ac7d7 XL |
3 | //! The traits in this module provide a way to convert from one type to another type. |
4 | //! Each trait serves a different purpose: | |
9346a6ac | 5 | //! |
532ac7d7 XL |
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. | |
9346a6ac | 13 | //! |
532ac7d7 XL |
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. | |
7453a54e | 16 | //! |
532ac7d7 | 17 | //! As a library author, you should always prefer implementing [`From<T>`][`From`] or |
32a655c1 SL |
18 | //! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`], |
19 | //! as [`From`] and [`TryFrom`] provide greater flexibility and offer | |
cc61c64b | 20 | //! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a |
3dfed10e XL |
21 | //! blanket implementation in the standard library. When targeting a version prior to Rust 1.41, it |
22 | //! may be necessary to implement [`Into`] or [`TryInto`] directly when converting to a type | |
23 | //! outside the current crate. | |
7453a54e | 24 | //! |
cc61c64b | 25 | //! # Generic Implementations |
7453a54e | 26 | //! |
32a655c1 SL |
27 | //! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference |
28 | //! - [`From`]`<U> for T` implies [`Into`]`<T> for U` | |
29 | //! - [`TryFrom`]`<U> for T` implies [`TryInto`]`<T> for U` | |
cc61c64b XL |
30 | //! - [`From`] and [`Into`] are reflexive, which means that all types can |
31 | //! `into` themselves and `from` themselves | |
7453a54e | 32 | //! |
9346a6ac | 33 | //! See each trait for usage examples. |
c34b1796 AL |
34 | |
35 | #![stable(feature = "rust1", since = "1.0.0")] | |
36 | ||
48663c56 | 37 | use crate::fmt; |
ba9703b0 | 38 | use crate::hash::{Hash, Hasher}; |
9fa01778 | 39 | |
60c5eb7d XL |
40 | mod num; |
41 | ||
42 | #[unstable(feature = "convert_float_to_int", issue = "67057")] | |
43 | pub use num::FloatToInt; | |
44 | ||
e1599b0c | 45 | /// The identity function. |
b7449926 XL |
46 | /// |
47 | /// Two things are important to note about this function: | |
48 | /// | |
e1599b0c | 49 | /// - It is not always equivalent to a closure like `|x| x`, since the |
b7449926 XL |
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 | /// | |
e1599b0c XL |
59 | /// Using `identity` to do nothing in a sequence of other, interesting, |
60 | /// functions: | |
b7449926 XL |
61 | /// |
62 | /// ```rust | |
b7449926 XL |
63 | /// use std::convert::identity; |
64 | /// | |
65 | /// fn manipulation(x: u32) -> u32 { | |
e1599b0c | 66 | /// // Let's pretend that adding one is an interesting function. |
b7449926 XL |
67 | /// x + 1 |
68 | /// } | |
69 | /// | |
70 | /// let _arr = &[identity, manipulation]; | |
71 | /// ``` | |
72 | /// | |
e1599b0c | 73 | /// Using `identity` as a "do nothing" base case in a conditional: |
b7449926 XL |
74 | /// |
75 | /// ```rust | |
b7449926 XL |
76 | /// use std::convert::identity; |
77 | /// | |
78 | /// # let condition = true; | |
e1599b0c | 79 | /// # |
b7449926 | 80 | /// # fn manipulation(x: u32) -> u32 { x + 1 } |
e1599b0c | 81 | /// # |
b7449926 XL |
82 | /// let do_stuff = if condition { manipulation } else { identity }; |
83 | /// | |
e1599b0c | 84 | /// // Do more interesting stuff... |
b7449926 XL |
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 | |
b7449926 XL |
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 | /// ``` | |
0731742a | 98 | #[stable(feature = "convert_id", since = "1.33.0")] |
dfeec247 | 99 | #[rustc_const_stable(feature = "const_identity", since = "1.33.0")] |
b7449926 | 100 | #[inline] |
60c5eb7d XL |
101 | pub const fn identity<T>(x: T) -> T { |
102 | x | |
103 | } | |
b7449926 | 104 | |
532ac7d7 | 105 | /// Used to do a cheap reference-to-reference conversion. |
cc61c64b | 106 | /// |
532ac7d7 XL |
107 | /// This trait is similar to [`AsMut`] which is used for converting between mutable references. |
108 | /// If you need to do a costly conversion it is better to implement [`From`] with type | |
109 | /// `&T` or write a custom function. | |
cc61c64b | 110 | /// |
e1599b0c | 111 | /// `AsRef` has the same signature as [`Borrow`], but [`Borrow`] is different in few aspects: |
cc61c64b | 112 | /// |
e1599b0c | 113 | /// - Unlike `AsRef`, [`Borrow`] has a blanket impl for any `T`, and can be used to accept either |
532ac7d7 | 114 | /// a reference or a value. |
e1599b0c | 115 | /// - [`Borrow`] also requires that [`Hash`], [`Eq`] and [`Ord`] for borrowed value are |
532ac7d7 | 116 | /// equivalent to those of the owned value. For this reason, if you want to |
e1599b0c | 117 | /// borrow only a single field of a struct you can implement `AsRef`, but not [`Borrow`]. |
d9579d0f | 118 | /// |
532ac7d7 | 119 | /// **Note: This trait must not fail**. If the conversion can fail, use a |
cc61c64b | 120 | /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`]. |
9e0c209e | 121 | /// |
cc61c64b XL |
122 | /// # Generic Implementations |
123 | /// | |
124 | /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable | |
125 | /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type | |
126 | /// `&mut Foo` or `&&mut Foo`) | |
127 | /// | |
9346a6ac AL |
128 | /// # Examples |
129 | /// | |
532ac7d7 | 130 | /// By using trait bounds we can accept arguments of different types as long as they can be |
dc9dc135 | 131 | /// converted to the specified type `T`. |
532ac7d7 XL |
132 | /// |
133 | /// For example: By creating a generic function that takes an `AsRef<str>` we express that we | |
e1599b0c XL |
134 | /// want to accept all references that can be converted to [`&str`] as an argument. |
135 | /// Since both [`String`] and [`&str`] implement `AsRef<str>` we can accept both as input argument. | |
9e0c209e | 136 | /// |
29967ef6 | 137 | /// [`&str`]: primitive@str |
1b1a35ee XL |
138 | /// [`Borrow`]: crate::borrow::Borrow |
139 | /// [`Eq`]: crate::cmp::Eq | |
140 | /// [`Ord`]: crate::cmp::Ord | |
9e0c209e | 141 | /// [`String`]: ../../std/string/struct.String.html |
9346a6ac AL |
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 | /// ``` | |
c34b1796 AL |
154 | #[stable(feature = "rust1", since = "1.0.0")] |
155 | pub trait AsRef<T: ?Sized> { | |
9346a6ac | 156 | /// Performs the conversion. |
c34b1796 AL |
157 | #[stable(feature = "rust1", since = "1.0.0")] |
158 | fn as_ref(&self) -> &T; | |
159 | } | |
160 | ||
532ac7d7 | 161 | /// Used to do a cheap mutable-to-mutable reference conversion. |
7453a54e | 162 | /// |
532ac7d7 XL |
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. | |
cc61c64b | 166 | /// |
532ac7d7 | 167 | /// **Note: This trait must not fail**. If the conversion can fail, use a |
cc61c64b | 168 | /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`]. |
9e0c209e | 169 | /// |
cc61c64b XL |
170 | /// # Generic Implementations |
171 | /// | |
2c00a5a8 XL |
172 | /// - `AsMut` auto-dereferences if the inner type is a mutable reference |
173 | /// (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo` | |
174 | /// or `&mut &mut Foo`) | |
cc61c64b | 175 | /// |
9e0c209e SL |
176 | /// # Examples |
177 | /// | |
532ac7d7 XL |
178 | /// Using `AsMut` as trait bound for a generic function we can accept all mutable references |
179 | /// that can be converted to type `&mut T`. Because [`Box<T>`] implements `AsMut<T>` we can | |
dc9dc135 XL |
180 | /// write a function `add_one` that takes all arguments that can be converted to `&mut u64`. |
181 | /// Because [`Box<T>`] implements `AsMut<T>`, `add_one` accepts arguments of type | |
532ac7d7 | 182 | /// `&mut Box<u64>` as well: |
48663c56 | 183 | /// |
9e0c209e SL |
184 | /// ``` |
185 | /// fn add_one<T: AsMut<u64>>(num: &mut T) { | |
186 | /// *num.as_mut() += 1; | |
187 | /// } | |
188 | /// | |
189 | /// let mut boxed_num = Box::new(0); | |
190 | /// add_one(&mut boxed_num); | |
191 | /// assert_eq!(*boxed_num, 1); | |
192 | /// ``` | |
7453a54e | 193 | /// |
48663c56 | 194 | /// [`Box<T>`]: ../../std/boxed/struct.Box.html |
c34b1796 AL |
195 | #[stable(feature = "rust1", since = "1.0.0")] |
196 | pub trait AsMut<T: ?Sized> { | |
9346a6ac | 197 | /// Performs the conversion. |
c34b1796 AL |
198 | #[stable(feature = "rust1", since = "1.0.0")] |
199 | fn as_mut(&mut self) -> &mut T; | |
200 | } | |
201 | ||
532ac7d7 XL |
202 | /// A value-to-value conversion that consumes the input value. The |
203 | /// opposite of [`From`]. | |
cc61c64b | 204 | /// |
60c5eb7d XL |
205 | /// One should avoid implementing [`Into`] and implement [`From`] instead. |
206 | /// Implementing [`From`] automatically provides one with an implementation of [`Into`] | |
207 | /// thanks to the blanket implementation in the standard library. | |
208 | /// | |
209 | /// Prefer using [`Into`] over [`From`] when specifying trait bounds on a generic function | |
210 | /// to ensure that types that only implement [`Into`] can be used as well. | |
9346a6ac | 211 | /// |
532ac7d7 | 212 | /// **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`]. |
7453a54e | 213 | /// |
cc61c64b XL |
214 | /// # Generic Implementations |
215 | /// | |
48663c56 | 216 | /// - [`From`]`<T> for U` implies `Into<U> for T` |
dc9dc135 | 217 | /// - [`Into`] is reflexive, which means that `Into<T> for T` is implemented |
7453a54e | 218 | /// |
60c5eb7d | 219 | /// # Implementing [`Into`] for conversions to external types in old versions of Rust |
7cac9316 | 220 | /// |
74b04a01 | 221 | /// Prior to Rust 1.41, if the destination type was not part of the current crate |
60c5eb7d | 222 | /// then you couldn't implement [`From`] directly. |
532ac7d7 | 223 | /// For example, take this code: |
7cac9316 | 224 | /// |
60c5eb7d | 225 | /// ``` |
7cac9316 XL |
226 | /// struct Wrapper<T>(Vec<T>); |
227 | /// impl<T> From<Wrapper<T>> for Vec<T> { | |
228 | /// fn from(w: Wrapper<T>) -> Vec<T> { | |
229 | /// w.0 | |
230 | /// } | |
231 | /// } | |
232 | /// ``` | |
60c5eb7d XL |
233 | /// This will fail to compile in older versions of the language because Rust's orphaning rules |
234 | /// used to be a little bit more strict. To bypass this, you could implement [`Into`] directly: | |
7cac9316 XL |
235 | /// |
236 | /// ``` | |
237 | /// struct Wrapper<T>(Vec<T>); | |
238 | /// impl<T> Into<Vec<T>> for Wrapper<T> { | |
239 | /// fn into(self) -> Vec<T> { | |
240 | /// self.0 | |
241 | /// } | |
242 | /// } | |
243 | /// ``` | |
244 | /// | |
dc9dc135 XL |
245 | /// It is important to understand that [`Into`] does not provide a [`From`] implementation |
246 | /// (as [`From`] does with [`Into`]). Therefore, you should always try to implement [`From`] | |
247 | /// and then fall back to [`Into`] if [`From`] can't be implemented. | |
7cac9316 | 248 | /// |
9346a6ac AL |
249 | /// # Examples |
250 | /// | |
416331ca | 251 | /// [`String`] implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>`: |
9346a6ac | 252 | /// |
532ac7d7 | 253 | /// In order to express that we want a generic function to take all arguments that can be |
dc9dc135 | 254 | /// converted to a specified type `T`, we can use a trait bound of [`Into`]`<T>`. |
532ac7d7 | 255 | /// For example: The function `is_hello` takes all arguments that can be converted into a |
416331ca | 256 | /// [`Vec`]`<`[`u8`]`>`. |
532ac7d7 | 257 | /// |
9346a6ac AL |
258 | /// ``` |
259 | /// fn is_hello<T: Into<Vec<u8>>>(s: T) { | |
260 | /// let bytes = b"hello".to_vec(); | |
261 | /// assert_eq!(bytes, s.into()); | |
262 | /// } | |
263 | /// | |
264 | /// let s = "hello".to_string(); | |
265 | /// is_hello(s); | |
266 | /// ``` | |
7453a54e | 267 | /// |
9e0c209e | 268 | /// [`String`]: ../../std/string/struct.String.html |
416331ca | 269 | /// [`Vec`]: ../../std/vec/struct.Vec.html |
5869c6ff | 270 | #[rustc_diagnostic_item = "into_trait"] |
c34b1796 AL |
271 | #[stable(feature = "rust1", since = "1.0.0")] |
272 | pub trait Into<T>: Sized { | |
9346a6ac | 273 | /// Performs the conversion. |
c34b1796 AL |
274 | #[stable(feature = "rust1", since = "1.0.0")] |
275 | fn into(self) -> T; | |
276 | } | |
277 | ||
532ac7d7 XL |
278 | /// Used to do value-to-value conversions while consuming the input value. It is the reciprocal of |
279 | /// [`Into`]. | |
cc61c64b | 280 | /// |
48663c56 | 281 | /// One should always prefer implementing `From` over [`Into`] |
60c5eb7d | 282 | /// because implementing `From` automatically provides one with an implementation of [`Into`] |
532ac7d7 | 283 | /// thanks to the blanket implementation in the standard library. |
9346a6ac | 284 | /// |
3dfed10e XL |
285 | /// Only implement [`Into`] when targeting a version prior to Rust 1.41 and converting to a type |
286 | /// outside the current crate. | |
287 | /// `From` was not able to do these types of conversions in earlier versions because of Rust's | |
288 | /// orphaning rules. | |
532ac7d7 | 289 | /// See [`Into`] for more details. |
cc61c64b | 290 | /// |
48663c56 | 291 | /// Prefer using [`Into`] over using `From` when specifying trait bounds on a generic function. |
532ac7d7 | 292 | /// This way, types that directly implement [`Into`] can be used as arguments as well. |
cc61c64b | 293 | /// |
48663c56 | 294 | /// The `From` is also very useful when performing error handling. When constructing a function |
532ac7d7 XL |
295 | /// that is capable of failing, the return type will generally be of the form `Result<T, E>`. |
296 | /// The `From` trait simplifies error handling by allowing a function to return a single error type | |
297 | /// that encapsulate multiple error types. See the "Examples" section and [the book][book] for more | |
298 | /// details. | |
cc61c64b | 299 | /// |
532ac7d7 | 300 | /// **Note: This trait must not fail**. If the conversion can fail, use [`TryFrom`]. |
cc61c64b XL |
301 | /// |
302 | /// # Generic Implementations | |
303 | /// | |
48663c56 XL |
304 | /// - `From<T> for U` implies [`Into`]`<U> for T` |
305 | /// - `From` is reflexive, which means that `From<T> for T` is implemented | |
7453a54e | 306 | /// |
9346a6ac AL |
307 | /// # Examples |
308 | /// | |
9e0c209e | 309 | /// [`String`] implements `From<&str>`: |
9346a6ac | 310 | /// |
48663c56 XL |
311 | /// An explicit conversion from a `&str` to a String is done as follows: |
312 | /// | |
9346a6ac | 313 | /// ``` |
9346a6ac | 314 | /// let string = "hello".to_string(); |
bd371182 | 315 | /// let other_string = String::from("hello"); |
9346a6ac AL |
316 | /// |
317 | /// assert_eq!(string, other_string); | |
318 | /// ``` | |
7453a54e | 319 | /// |
532ac7d7 XL |
320 | /// While performing error handling it is often useful to implement `From` for your own error type. |
321 | /// By converting underlying error types to our own custom error type that encapsulates the | |
322 | /// underlying error type, we can return a single error type without losing information on the | |
323 | /// underlying cause. The '?' operator automatically converts the underlying error type to our | |
324 | /// custom error type by calling `Into<CliError>::into` which is automatically provided when | |
325 | /// implementing `From`. The compiler then infers which implementation of `Into` should be used. | |
cc61c64b XL |
326 | /// |
327 | /// ``` | |
0731742a XL |
328 | /// use std::fs; |
329 | /// use std::io; | |
cc61c64b XL |
330 | /// use std::num; |
331 | /// | |
332 | /// enum CliError { | |
333 | /// IoError(io::Error), | |
334 | /// ParseError(num::ParseIntError), | |
335 | /// } | |
336 | /// | |
337 | /// impl From<io::Error> for CliError { | |
338 | /// fn from(error: io::Error) -> Self { | |
339 | /// CliError::IoError(error) | |
340 | /// } | |
341 | /// } | |
342 | /// | |
343 | /// impl From<num::ParseIntError> for CliError { | |
344 | /// fn from(error: num::ParseIntError) -> Self { | |
345 | /// CliError::ParseError(error) | |
346 | /// } | |
347 | /// } | |
348 | /// | |
349 | /// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> { | |
0731742a | 350 | /// let mut contents = fs::read_to_string(&file_name)?; |
cc61c64b XL |
351 | /// let num: i32 = contents.trim().parse()?; |
352 | /// Ok(num) | |
353 | /// } | |
354 | /// ``` | |
7453a54e | 355 | /// |
9e0c209e | 356 | /// [`String`]: ../../std/string/struct.String.html |
1b1a35ee | 357 | /// [`from`]: From::from |
9fa01778 | 358 | /// [book]: ../../book/ch09-00-error-handling.html |
f035d41b | 359 | #[rustc_diagnostic_item = "from_trait"] |
c34b1796 | 360 | #[stable(feature = "rust1", since = "1.0.0")] |
60c5eb7d XL |
361 | #[rustc_on_unimplemented(on( |
362 | all(_Self = "&str", T = "std::string::String"), | |
363 | note = "to coerce a `{T}` into a `{Self}`, use `&*` as a prefix", | |
364 | ))] | |
b039eaaf | 365 | pub trait From<T>: Sized { |
9346a6ac | 366 | /// Performs the conversion. |
1b1a35ee | 367 | #[lang = "from"] |
c34b1796 | 368 | #[stable(feature = "rust1", since = "1.0.0")] |
7cac9316 | 369 | fn from(_: T) -> Self; |
c34b1796 AL |
370 | } |
371 | ||
cc61c64b XL |
372 | /// An attempted conversion that consumes `self`, which may or may not be |
373 | /// expensive. | |
a7813a04 | 374 | /// |
9fa01778 XL |
375 | /// Library authors should usually not directly implement this trait, |
376 | /// but should prefer implementing the [`TryFrom`] trait, which offers | |
377 | /// greater flexibility and provides an equivalent `TryInto` | |
378 | /// implementation for free, thanks to a blanket implementation in the | |
379 | /// standard library. For more information on this, see the | |
380 | /// documentation for [`Into`]. | |
381 | /// | |
382 | /// # Implementing `TryInto` | |
383 | /// | |
384 | /// This suffers the same restrictions and reasoning as implementing | |
385 | /// [`Into`], see there for details. | |
5869c6ff | 386 | #[rustc_diagnostic_item = "try_into_trait"] |
9fa01778 | 387 | #[stable(feature = "try_from", since = "1.34.0")] |
a7813a04 XL |
388 | pub trait TryInto<T>: Sized { |
389 | /// The type returned in the event of a conversion error. | |
9fa01778 | 390 | #[stable(feature = "try_from", since = "1.34.0")] |
cc61c64b | 391 | type Error; |
a7813a04 XL |
392 | |
393 | /// Performs the conversion. | |
9fa01778 | 394 | #[stable(feature = "try_from", since = "1.34.0")] |
cc61c64b | 395 | fn try_into(self) -> Result<T, Self::Error>; |
a7813a04 XL |
396 | } |
397 | ||
9fa01778 XL |
398 | /// Simple and safe type conversions that may fail in a controlled |
399 | /// way under some circumstances. It is the reciprocal of [`TryInto`]. | |
400 | /// | |
401 | /// This is useful when you are doing a type conversion that may | |
402 | /// trivially succeed but may also need special handling. | |
416331ca XL |
403 | /// For example, there is no way to convert an [`i64`] into an [`i32`] |
404 | /// using the [`From`] trait, because an [`i64`] may contain a value | |
405 | /// that an [`i32`] cannot represent and so the conversion would lose data. | |
406 | /// This might be handled by truncating the [`i64`] to an [`i32`] (essentially | |
407 | /// giving the [`i64`]'s value modulo [`i32::MAX`]) or by simply returning | |
408 | /// [`i32::MAX`], or by some other method. The [`From`] trait is intended | |
9fa01778 XL |
409 | /// for perfect conversions, so the `TryFrom` trait informs the |
410 | /// programmer when a type conversion could go bad and lets them | |
411 | /// decide how to handle it. | |
412 | /// | |
413 | /// # Generic Implementations | |
414 | /// | |
48663c56 | 415 | /// - `TryFrom<T> for U` implies [`TryInto`]`<U> for T` |
9fa01778 XL |
416 | /// - [`try_from`] is reflexive, which means that `TryFrom<T> for T` |
417 | /// is implemented and cannot fail -- the associated `Error` type for | |
416331ca XL |
418 | /// calling `T::try_from()` on a value of type `T` is [`Infallible`]. |
419 | /// When the [`!`] type is stabilized [`Infallible`] and [`!`] will be | |
9fa01778 XL |
420 | /// equivalent. |
421 | /// | |
532ac7d7 XL |
422 | /// `TryFrom<T>` can be implemented as follows: |
423 | /// | |
424 | /// ``` | |
425 | /// use std::convert::TryFrom; | |
426 | /// | |
60c5eb7d | 427 | /// struct GreaterThanZero(i32); |
532ac7d7 | 428 | /// |
60c5eb7d | 429 | /// impl TryFrom<i32> for GreaterThanZero { |
532ac7d7 XL |
430 | /// type Error = &'static str; |
431 | /// | |
432 | /// fn try_from(value: i32) -> Result<Self, Self::Error> { | |
60c5eb7d XL |
433 | /// if value <= 0 { |
434 | /// Err("GreaterThanZero only accepts value superior than zero!") | |
532ac7d7 | 435 | /// } else { |
60c5eb7d | 436 | /// Ok(GreaterThanZero(value)) |
532ac7d7 XL |
437 | /// } |
438 | /// } | |
439 | /// } | |
440 | /// ``` | |
441 | /// | |
9fa01778 XL |
442 | /// # Examples |
443 | /// | |
416331ca | 444 | /// As described, [`i32`] implements `TryFrom<`[`i64`]`>`: |
9fa01778 XL |
445 | /// |
446 | /// ``` | |
447 | /// use std::convert::TryFrom; | |
448 | /// | |
449 | /// let big_number = 1_000_000_000_000i64; | |
450 | /// // Silently truncates `big_number`, requires detecting | |
451 | /// // and handling the truncation after the fact. | |
452 | /// let smaller_number = big_number as i32; | |
453 | /// assert_eq!(smaller_number, -727379968); | |
454 | /// | |
455 | /// // Returns an error because `big_number` is too big to | |
456 | /// // fit in an `i32`. | |
457 | /// let try_smaller_number = i32::try_from(big_number); | |
458 | /// assert!(try_smaller_number.is_err()); | |
459 | /// | |
460 | /// // Returns `Ok(3)`. | |
461 | /// let try_successful_smaller_number = i32::try_from(3); | |
462 | /// assert!(try_successful_smaller_number.is_ok()); | |
463 | /// ``` | |
464 | /// | |
1b1a35ee | 465 | /// [`try_from`]: TryFrom::try_from |
5869c6ff | 466 | #[rustc_diagnostic_item = "try_from_trait"] |
9fa01778 | 467 | #[stable(feature = "try_from", since = "1.34.0")] |
a7813a04 XL |
468 | pub trait TryFrom<T>: Sized { |
469 | /// The type returned in the event of a conversion error. | |
9fa01778 | 470 | #[stable(feature = "try_from", since = "1.34.0")] |
cc61c64b | 471 | type Error; |
a7813a04 XL |
472 | |
473 | /// Performs the conversion. | |
9fa01778 | 474 | #[stable(feature = "try_from", since = "1.34.0")] |
cc61c64b | 475 | fn try_from(value: T) -> Result<Self, Self::Error>; |
a7813a04 XL |
476 | } |
477 | ||
c34b1796 AL |
478 | //////////////////////////////////////////////////////////////////////////////// |
479 | // GENERIC IMPLS | |
480 | //////////////////////////////////////////////////////////////////////////////// | |
481 | ||
482 | // As lifts over & | |
483 | #[stable(feature = "rust1", since = "1.0.0")] | |
60c5eb7d XL |
484 | impl<T: ?Sized, U: ?Sized> AsRef<U> for &T |
485 | where | |
486 | T: AsRef<U>, | |
cc61c64b | 487 | { |
c34b1796 AL |
488 | fn as_ref(&self) -> &U { |
489 | <T as AsRef<U>>::as_ref(*self) | |
490 | } | |
491 | } | |
492 | ||
493 | // As lifts over &mut | |
494 | #[stable(feature = "rust1", since = "1.0.0")] | |
60c5eb7d XL |
495 | impl<T: ?Sized, U: ?Sized> AsRef<U> for &mut T |
496 | where | |
497 | T: AsRef<U>, | |
cc61c64b | 498 | { |
c34b1796 AL |
499 | fn as_ref(&self) -> &U { |
500 | <T as AsRef<U>>::as_ref(*self) | |
501 | } | |
502 | } | |
503 | ||
0531ce1d | 504 | // FIXME (#45742): replace the above impls for &/&mut with the following more general one: |
c34b1796 | 505 | // // As lifts over Deref |
416331ca | 506 | // impl<D: ?Sized + Deref<Target: AsRef<U>>, U: ?Sized> AsRef<U> for D { |
c34b1796 AL |
507 | // fn as_ref(&self) -> &U { |
508 | // self.deref().as_ref() | |
509 | // } | |
510 | // } | |
511 | ||
512 | // AsMut lifts over &mut | |
513 | #[stable(feature = "rust1", since = "1.0.0")] | |
60c5eb7d XL |
514 | impl<T: ?Sized, U: ?Sized> AsMut<U> for &mut T |
515 | where | |
516 | T: AsMut<U>, | |
cc61c64b | 517 | { |
c34b1796 AL |
518 | fn as_mut(&mut self) -> &mut U { |
519 | (*self).as_mut() | |
520 | } | |
521 | } | |
522 | ||
0531ce1d | 523 | // FIXME (#45742): replace the above impl for &mut with the following more general one: |
c34b1796 | 524 | // // AsMut lifts over DerefMut |
416331ca | 525 | // impl<D: ?Sized + Deref<Target: AsMut<U>>, U: ?Sized> AsMut<U> for D { |
c34b1796 AL |
526 | // fn as_mut(&mut self) -> &mut U { |
527 | // self.deref_mut().as_mut() | |
528 | // } | |
529 | // } | |
530 | ||
531 | // From implies Into | |
532 | #[stable(feature = "rust1", since = "1.0.0")] | |
60c5eb7d XL |
533 | impl<T, U> Into<U> for T |
534 | where | |
535 | U: From<T>, | |
cc61c64b | 536 | { |
c34b1796 AL |
537 | fn into(self) -> U { |
538 | U::from(self) | |
539 | } | |
540 | } | |
541 | ||
542 | // From (and thus Into) is reflexive | |
543 | #[stable(feature = "rust1", since = "1.0.0")] | |
544 | impl<T> From<T> for T { | |
60c5eb7d XL |
545 | fn from(t: T) -> T { |
546 | t | |
547 | } | |
c34b1796 AL |
548 | } |
549 | ||
e74abb32 XL |
550 | /// **Stability note:** This impl does not yet exist, but we are |
551 | /// "reserving space" to add it in the future. See | |
552 | /// [rust-lang/rust#64715][#64715] for details. | |
553 | /// | |
554 | /// [#64715]: https://github.com/rust-lang/rust/issues/64715 | |
555 | #[stable(feature = "convert_infallible", since = "1.34.0")] | |
60c5eb7d XL |
556 | #[allow(unused_attributes)] // FIXME(#58633): do a principled fix instead. |
557 | #[rustc_reservation_impl = "permitting this impl would forbid us from adding \ | |
558 | `impl<T> From<!> for T` later; see rust-lang/rust#64715 for details"] | |
e74abb32 | 559 | impl<T> From<!> for T { |
60c5eb7d XL |
560 | fn from(t: !) -> T { |
561 | t | |
562 | } | |
e74abb32 | 563 | } |
a7813a04 XL |
564 | |
565 | // TryFrom implies TryInto | |
9fa01778 | 566 | #[stable(feature = "try_from", since = "1.34.0")] |
60c5eb7d XL |
567 | impl<T, U> TryInto<U> for T |
568 | where | |
569 | U: TryFrom<T>, | |
cc61c64b XL |
570 | { |
571 | type Error = U::Error; | |
a7813a04 | 572 | |
cc61c64b | 573 | fn try_into(self) -> Result<U, U::Error> { |
a7813a04 XL |
574 | U::try_from(self) |
575 | } | |
576 | } | |
577 | ||
ea8adc8c XL |
578 | // Infallible conversions are semantically equivalent to fallible conversions |
579 | // with an uninhabited error type. | |
9fa01778 | 580 | #[stable(feature = "try_from", since = "1.34.0")] |
60c5eb7d XL |
581 | impl<T, U> TryFrom<U> for T |
582 | where | |
583 | U: Into<T>, | |
584 | { | |
9fa01778 | 585 | type Error = Infallible; |
ea8adc8c XL |
586 | |
587 | fn try_from(value: U) -> Result<Self, Self::Error> { | |
9fa01778 | 588 | Ok(U::into(value)) |
ea8adc8c XL |
589 | } |
590 | } | |
591 | ||
c34b1796 AL |
592 | //////////////////////////////////////////////////////////////////////////////// |
593 | // CONCRETE IMPLS | |
594 | //////////////////////////////////////////////////////////////////////////////// | |
595 | ||
596 | #[stable(feature = "rust1", since = "1.0.0")] | |
597 | impl<T> AsRef<[T]> for [T] { | |
598 | fn as_ref(&self) -> &[T] { | |
599 | self | |
600 | } | |
601 | } | |
602 | ||
603 | #[stable(feature = "rust1", since = "1.0.0")] | |
604 | impl<T> AsMut<[T]> for [T] { | |
605 | fn as_mut(&mut self) -> &mut [T] { | |
606 | self | |
607 | } | |
608 | } | |
609 | ||
610 | #[stable(feature = "rust1", since = "1.0.0")] | |
611 | impl AsRef<str> for str { | |
d9579d0f | 612 | #[inline] |
c34b1796 AL |
613 | fn as_ref(&self) -> &str { |
614 | self | |
615 | } | |
616 | } | |
9fa01778 | 617 | |
5869c6ff XL |
618 | #[stable(feature = "as_mut_str_for_str", since = "1.51.0")] |
619 | impl AsMut<str> for str { | |
620 | #[inline] | |
621 | fn as_mut(&mut self) -> &mut str { | |
622 | self | |
623 | } | |
624 | } | |
625 | ||
9fa01778 XL |
626 | //////////////////////////////////////////////////////////////////////////////// |
627 | // THE NO-ERROR ERROR TYPE | |
628 | //////////////////////////////////////////////////////////////////////////////// | |
629 | ||
630 | /// The error type for errors that can never happen. | |
631 | /// | |
632 | /// Since this enum has no variant, a value of this type can never actually exist. | |
633 | /// This can be useful for generic APIs that use [`Result`] and parameterize the error type, | |
634 | /// to indicate that the result is always [`Ok`]. | |
635 | /// | |
636 | /// For example, the [`TryFrom`] trait (conversion that returns a [`Result`]) | |
637 | /// has a blanket implementation for all types where a reverse [`Into`] implementation exists. | |
638 | /// | |
639 | /// ```ignore (illustrates std code, duplicating the impl in a doctest would be an error) | |
640 | /// impl<T, U> TryFrom<U> for T where U: Into<T> { | |
641 | /// type Error = Infallible; | |
642 | /// | |
643 | /// fn try_from(value: U) -> Result<Self, Infallible> { | |
644 | /// Ok(U::into(value)) // Never returns `Err` | |
645 | /// } | |
646 | /// } | |
647 | /// ``` | |
648 | /// | |
649 | /// # Future compatibility | |
650 | /// | |
651 | /// This enum has the same role as [the `!` “never” type][never], | |
652 | /// which is unstable in this version of Rust. | |
653 | /// When `!` is stabilized, we plan to make `Infallible` a type alias to it: | |
654 | /// | |
655 | /// ```ignore (illustrates future std change) | |
656 | /// pub type Infallible = !; | |
657 | /// ``` | |
658 | /// | |
659 | /// … and eventually deprecate `Infallible`. | |
660 | /// | |
9fa01778 | 661 | /// However there is one case where `!` syntax can be used |
3dfed10e | 662 | /// before `!` is stabilized as a full-fledged type: in the position of a function’s return type. |
9fa01778 XL |
663 | /// Specifically, it is possible implementations for two different function pointer types: |
664 | /// | |
665 | /// ``` | |
666 | /// trait MyTrait {} | |
667 | /// impl MyTrait for fn() -> ! {} | |
668 | /// impl MyTrait for fn() -> std::convert::Infallible {} | |
669 | /// ``` | |
670 | /// | |
671 | /// With `Infallible` being an enum, this code is valid. | |
672 | /// However when `Infallible` becomes an alias for the never type, | |
673 | /// the two `impl`s will start to overlap | |
674 | /// and therefore will be disallowed by the language’s trait coherence rules. | |
9fa01778 XL |
675 | #[stable(feature = "convert_infallible", since = "1.34.0")] |
676 | #[derive(Copy)] | |
677 | pub enum Infallible {} | |
678 | ||
679 | #[stable(feature = "convert_infallible", since = "1.34.0")] | |
680 | impl Clone for Infallible { | |
681 | fn clone(&self) -> Infallible { | |
682 | match *self {} | |
683 | } | |
684 | } | |
685 | ||
686 | #[stable(feature = "convert_infallible", since = "1.34.0")] | |
687 | impl fmt::Debug for Infallible { | |
688 | fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { | |
689 | match *self {} | |
690 | } | |
691 | } | |
692 | ||
693 | #[stable(feature = "convert_infallible", since = "1.34.0")] | |
694 | impl fmt::Display for Infallible { | |
695 | fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { | |
696 | match *self {} | |
697 | } | |
698 | } | |
699 | ||
700 | #[stable(feature = "convert_infallible", since = "1.34.0")] | |
701 | impl PartialEq for Infallible { | |
702 | fn eq(&self, _: &Infallible) -> bool { | |
703 | match *self {} | |
704 | } | |
705 | } | |
706 | ||
707 | #[stable(feature = "convert_infallible", since = "1.34.0")] | |
708 | impl Eq for Infallible {} | |
709 | ||
710 | #[stable(feature = "convert_infallible", since = "1.34.0")] | |
711 | impl PartialOrd for Infallible { | |
712 | fn partial_cmp(&self, _other: &Self) -> Option<crate::cmp::Ordering> { | |
713 | match *self {} | |
714 | } | |
715 | } | |
716 | ||
717 | #[stable(feature = "convert_infallible", since = "1.34.0")] | |
718 | impl Ord for Infallible { | |
719 | fn cmp(&self, _other: &Self) -> crate::cmp::Ordering { | |
720 | match *self {} | |
721 | } | |
722 | } | |
723 | ||
724 | #[stable(feature = "convert_infallible", since = "1.34.0")] | |
725 | impl From<!> for Infallible { | |
726 | fn from(x: !) -> Self { | |
727 | x | |
728 | } | |
729 | } | |
ba9703b0 XL |
730 | |
731 | #[stable(feature = "convert_infallible_hash", since = "1.44.0")] | |
732 | impl Hash for Infallible { | |
733 | fn hash<H: Hasher>(&self, _: &mut H) { | |
734 | match *self {} | |
735 | } | |
736 | } |