try_from/
lib.rs

1#![cfg_attr(feature = "no_std", no_std)]
2
3#[macro_use]
4extern crate cfg_if;
5
6cfg_if! (
7    if #[cfg(feature="no_std")] {
8        use core::str::FromStr;
9    } else {
10        use std::str::FromStr;
11    }
12);
13mod char;
14mod int;
15
16pub use char::TryFromIntToCharError;
17pub use int::TryFromIntError;
18
19pub trait TryFrom<T>: Sized {
20    type Err;
21    fn try_from(T) -> Result<Self, Self::Err>;
22}
23
24pub trait TryInto<T>: Sized {
25    type Err;
26    fn try_into(self) -> Result<T, Self::Err>;
27}
28
29impl<T, U> TryInto<U> for T
30where
31    U: TryFrom<T>,
32{
33    type Err = U::Err;
34    fn try_into(self) -> Result<U, U::Err> {
35        U::try_from(self)
36    }
37}
38
39impl<'a, T> TryFrom<&'a str> for T
40where
41    T: FromStr,
42{
43    type Err = T::Err;
44    fn try_from(string: &'a str) -> Result<Self, Self::Err> {
45        T::from_str(string)
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn should_have_try_from_impl_for_from_str() {
55        let result = u32::try_from("3");
56        assert_eq!(result.unwrap(), 3)
57    }
58
59    #[test]
60    fn should_have_try_from_impl_for_from_str_that_handles_err() {
61        let result = u32::try_from("hello");
62        assert_eq!(
63            format!("{}", result.unwrap_err()),
64            "invalid digit found in string"
65        )
66    }
67
68    #[test]
69    fn should_have_try_into_impl_for_from_str() {
70        let result: Result<u32, _> = "3".try_into();
71        assert_eq!(result.unwrap(), 3)
72    }
73}
74
75/// Error type used when conversion is infallible.
76/// The never type (`!`) will replace this when it is available in stable Rust.
77#[derive(Debug, Eq, PartialEq)]
78pub enum Void {}