]> git.lizzy.rs Git - rust.git/blob - tests/ui/try-trait/try-operator-custom.rs
Rollup merge of #103236 - tspiteri:redoc-int-adc-sbb, r=m-ou-se
[rust.git] / tests / ui / try-trait / try-operator-custom.rs
1 // run-pass
2
3 #![feature(control_flow_enum)]
4 #![feature(try_trait_v2)]
5
6 use std::ops::{ControlFlow, FromResidual, Try};
7
8 enum MyResult<T, U> {
9     Awesome(T),
10     Terrible(U)
11 }
12
13 enum Never {}
14
15 impl<U, V> Try for MyResult<U, V> {
16     type Output = U;
17     type Residual = MyResult<Never, V>;
18
19     fn from_output(u: U) -> MyResult<U, V> {
20         MyResult::Awesome(u)
21     }
22
23     fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
24         match self {
25             MyResult::Awesome(u) => ControlFlow::Continue(u),
26             MyResult::Terrible(e) => ControlFlow::Break(MyResult::Terrible(e)),
27         }
28     }
29 }
30
31 impl<U, V, W> FromResidual<MyResult<Never, V>> for MyResult<U, W> where V: Into<W> {
32     fn from_residual(x: MyResult<Never, V>) -> Self {
33         match x {
34             MyResult::Awesome(u) => match u {},
35             MyResult::Terrible(e) => MyResult::Terrible(e.into()),
36         }
37     }
38 }
39
40 type ResultResidual<E> = Result<std::convert::Infallible, E>;
41
42 impl<U, V, W> FromResidual<ResultResidual<V>> for MyResult<U, W> where V: Into<W> {
43     fn from_residual(x: ResultResidual<V>) -> Self {
44         match x {
45             Ok(v) => match v {}
46             Err(e) => MyResult::Terrible(e.into()),
47         }
48     }
49 }
50
51 impl<U, V, W> FromResidual<MyResult<Never, V>> for Result<U, W> where V: Into<W> {
52     fn from_residual(x: MyResult<Never, V>) -> Self {
53         match x {
54             MyResult::Awesome(u) => match u {},
55             MyResult::Terrible(e) => Err(e.into()),
56         }
57     }
58 }
59
60 fn f(x: i32) -> Result<i32, String> {
61     if x == 0 {
62         Ok(42)
63     } else {
64         let y = g(x)?;
65         Ok(y)
66     }
67 }
68
69 fn g(x: i32) -> MyResult<i32, String> {
70     let _y = f(x - 1)?;
71     MyResult::Terrible("Hello".to_owned())
72 }
73
74 fn h() -> MyResult<i32, String> {
75     let a: Result<i32, &'static str> = Err("Hello");
76     let b = a?;
77     MyResult::Awesome(b)
78 }
79
80 fn i() -> MyResult<i32, String> {
81     let a: MyResult<i32, &'static str> = MyResult::Terrible("Hello");
82     let b = a?;
83     MyResult::Awesome(b)
84 }
85
86 fn main() {
87     assert!(f(0) == Ok(42));
88     assert!(f(10) == Err("Hello".to_owned()));
89     let _ = h();
90     let _ = i();
91 }