]> git.lizzy.rs Git - rust.git/blob - tests/ui/fallible_impl_from.rs
Merge branch 'master' into rustfmt_tests
[rust.git] / tests / ui / fallible_impl_from.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 #![deny(clippy::fallible_impl_from)]
11
12 // docs example
13 struct Foo(i32);
14 impl From<String> for Foo {
15     fn from(s: String) -> Self {
16         Foo(s.parse().unwrap())
17     }
18 }
19
20 struct Valid(Vec<u8>);
21
22 impl<'a> From<&'a str> for Valid {
23     fn from(s: &'a str) -> Valid {
24         Valid(s.to_owned().into_bytes())
25     }
26 }
27 impl From<usize> for Valid {
28     fn from(i: usize) -> Valid {
29         Valid(Vec::with_capacity(i))
30     }
31 }
32
33 struct Invalid;
34
35 impl From<usize> for Invalid {
36     fn from(i: usize) -> Invalid {
37         if i != 42 {
38             panic!();
39         }
40         Invalid
41     }
42 }
43
44 impl From<Option<String>> for Invalid {
45     fn from(s: Option<String>) -> Invalid {
46         let s = s.unwrap();
47         if !s.is_empty() {
48             panic!(42);
49         } else if s.parse::<u32>().unwrap() != 42 {
50             panic!("{:?}", s);
51         }
52         Invalid
53     }
54 }
55
56 trait ProjStrTrait {
57     type ProjString;
58 }
59 impl<T> ProjStrTrait for Box<T> {
60     type ProjString = String;
61 }
62 impl<'a> From<&'a mut <Box<u32> as ProjStrTrait>::ProjString> for Invalid {
63     fn from(s: &'a mut <Box<u32> as ProjStrTrait>::ProjString) -> Invalid {
64         if s.parse::<u32>().ok().unwrap() != 42 {
65             panic!("{:?}", s);
66         }
67         Invalid
68     }
69 }
70
71 struct Unreachable;
72
73 impl From<String> for Unreachable {
74     fn from(s: String) -> Unreachable {
75         if s.is_empty() {
76             return Unreachable;
77         }
78         match s.chars().next() {
79             Some(_) => Unreachable,
80             None => unreachable!(), // do not lint the unreachable macro
81         }
82     }
83 }
84
85 fn main() {}