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