]> git.lizzy.rs Git - rust.git/blob - tests/ui/fallible_impl_from.rs
Add license header to Rust files
[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
11 #![feature(tool_lints)]
12
13 #![deny(clippy::fallible_impl_from)]
14
15 // docs example
16 struct Foo(i32);
17 impl From<String> for Foo {
18     fn from(s: String) -> Self {
19         Foo(s.parse().unwrap())
20     }
21 }
22
23
24 struct Valid(Vec<u8>);
25
26 impl<'a> From<&'a str> for Valid {
27     fn from(s: &'a str) -> Valid {
28         Valid(s.to_owned().into_bytes())
29     }
30 }
31 impl From<usize> for Valid {
32     fn from(i: usize) -> Valid {
33         Valid(Vec::with_capacity(i))
34     }
35 }
36
37
38 struct Invalid;
39
40 impl From<usize> for Invalid {
41     fn from(i: usize) -> Invalid {
42         if i != 42 {
43             panic!();
44         }
45         Invalid
46     }
47 }
48
49 impl From<Option<String>> for Invalid {
50     fn from(s: Option<String>) -> Invalid {
51         let s = s.unwrap();
52         if !s.is_empty() {
53             panic!(42);
54         } else if s.parse::<u32>().unwrap() != 42 {
55             panic!("{:?}", s);
56         }
57         Invalid
58     }
59 }
60
61 trait ProjStrTrait {
62     type ProjString;
63 }
64 impl<T> ProjStrTrait for Box<T> {
65     type ProjString = String;
66 }
67 impl<'a> From<&'a mut <Box<u32> as ProjStrTrait>::ProjString> for Invalid {
68     fn from(s: &'a mut <Box<u32> as ProjStrTrait>::ProjString) -> Invalid {
69         if s.parse::<u32>().ok().unwrap() != 42 {
70             panic!("{:?}", s);
71         }
72         Invalid
73     }
74 }
75
76 struct Unreachable;
77
78 impl From<String> for Unreachable {
79     fn from(s: String) -> Unreachable {
80         if s.is_empty() {
81             return Unreachable;
82         }
83         match s.chars().next() {
84             Some(_) => Unreachable,
85             None => unreachable!(), // do not lint the unreachable macro
86         }
87     }
88 }
89
90 fn main() {}