File: async_fn.rs

package info (click to toggle)
rust-multiversion 0.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 168 kB
  • sloc: makefile: 2
file content (54 lines) | stat: -rw-r--r-- 1,695 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#[rustversion::since(1.39)]
#[multiversion::multiversion(targets("x86_64+avx", "x86_64+sse", "aarch64+neon",))]
async fn async_add(a: &mut [f32], b: &[f32]) {
    a.iter_mut().zip(b.iter()).for_each(|(a, b)| *a += b);
}

mod test {

    // Adapted from David Tolnay's async-trait.
    // Provided under Apache License, Version 2.0 or MIT license.
    #[rustversion::since(1.39)]
    pub fn block_on<F: std::future::Future>(mut fut: F) -> F::Output {
        use std::pin::Pin;
        use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};

        unsafe fn clone(_null: *const ()) -> RawWaker {
            unimplemented!()
        }

        unsafe fn wake(_null: *const ()) {
            unimplemented!()
        }

        unsafe fn wake_by_ref(_null: *const ()) {
            unimplemented!()
        }

        unsafe fn drop(_null: *const ()) {}

        let data = std::ptr::null();
        let vtable = &RawWakerVTable::new(clone, wake, wake_by_ref, drop);
        let raw_waker = RawWaker::new(data, vtable);
        let waker = unsafe { Waker::from_raw(raw_waker) };
        let mut cx = Context::from_waker(&waker);

        // fut does not move until it gets dropped.
        let fut = unsafe { Pin::new_unchecked(&mut fut) };

        match fut.poll(&mut cx) {
            Poll::Ready(output) => output,
            Poll::Pending => panic!("future did not resolve immediately"),
        }
    }

    #[rustversion::since(1.39)]
    #[test]
    fn async_fn() {
        let mut a = vec![0f32, 2f32, 4f32];
        let b = vec![1f32, 1f32, 1f32];
        let fut = super::async_add(&mut a, &b);
        block_on(fut);
        assert_eq!(a, vec![1f32, 3f32, 5f32]);
    }
}