]> git.lizzy.rs Git - rust.git/blob - tests/run-pass/async-fn.rs
rustup
[rust.git] / tests / run-pass / async-fn.rs
1 #![feature(never_type)]
2
3 use std::future::Future;
4
5 // See if we can run a basic `async fn`
6 pub async fn foo(x: &u32, y: u32) -> u32 {
7     let y = &y;
8     let z = 9;
9     let z = &z;
10     let y = async { *y + *z }.await;
11     let a = 10;
12     let a = &a;
13     *x + y + *a
14 }
15
16 async fn add(x: u32, y: u32) -> u32 {
17     let a = async { x + y };
18     a.await
19 }
20
21 async fn build_aggregate(a: u32, b: u32, c: u32, d: u32) -> u32 {
22     let x = (add(a, b).await, add(c, d).await);
23     x.0 + x.1
24 }
25
26 enum Never {}
27 fn never() -> Never {
28     panic!()
29 }
30
31 async fn includes_never(crash: bool, x: u32) -> u32 {
32     let result = async { x * x }.await;
33     if !crash {
34         return result;
35     }
36     #[allow(unused)]
37     let bad = never();
38     result *= async { x + x }.await;
39     drop(bad);
40     result
41 }
42
43 async fn partial_init(x: u32) -> u32 {
44     #[allow(unreachable_code)]
45     let _x: (String, !) = (String::new(), return async { x + x }.await);
46 }
47
48 async fn read_exact(_from: &mut &[u8], _to: &mut [u8]) -> Option<()> {
49     Some(())
50 }
51
52 async fn hello_world() {
53     let data = [0u8; 1];
54     let mut reader = &data[..];
55
56     let mut marker = [0u8; 1];
57     read_exact(&mut reader, &mut marker).await.unwrap();
58 }
59
60 fn run_fut<T>(fut: impl Future<Output = T>) -> T {
61     use std::sync::Arc;
62     use std::task::{Context, Poll, Wake, Waker};
63
64     struct MyWaker;
65     impl Wake for MyWaker {
66         fn wake(self: Arc<Self>) {
67             unimplemented!()
68         }
69     }
70
71     let waker = Waker::from(Arc::new(MyWaker));
72     let mut context = Context::from_waker(&waker);
73
74     let mut pinned = Box::pin(fut);
75     loop {
76         match pinned.as_mut().poll(&mut context) {
77             Poll::Pending => continue,
78             Poll::Ready(v) => return v,
79         }
80     }
81 }
82
83 fn main() {
84     let x = 5;
85     assert_eq!(run_fut(foo(&x, 7)), 31);
86     assert_eq!(run_fut(build_aggregate(1, 2, 3, 4)), 10);
87     assert_eq!(run_fut(includes_never(false, 4)), 16);
88     assert_eq!(run_fut(partial_init(4)), 8);
89     run_fut(hello_world());
90 }