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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
extern crate lazy_static;

use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};

use serde::Deserialize;
use serde_json;

extern "C" {
    fn __asml_abi_poll(id: u32) -> i32;
    fn __asml_abi_event_ptr(id: u32) -> u32;
    fn __asml_abi_event_len(id: u32) -> u32;

    fn __asml_abi_console_log(ptr: *const u8, len: usize);
}

const MAX_EVENTS: usize = 50;
const EVENT_SIZE_BYTES: usize = 512;
const EVENT_BUFFER_SIZE_BYTES: usize = MAX_EVENTS * EVENT_SIZE_BYTES;

// Raw buffer holding serialized Event-Future data
pub static mut EVENT_BUFFER: [u8; EVENT_BUFFER_SIZE_BYTES] = [0; EVENT_BUFFER_SIZE_BYTES];

#[no_mangle]
pub fn __asml_get_event_buffer_pointer() -> *const u8 {
    unsafe { EVENT_BUFFER.as_ptr() }
}

fn console_log(message: String) {
    unsafe { __asml_abi_console_log(message.as_ptr(), message.len()) }
}

#[derive(Clone)]
pub struct Event<'a, R> {
    pub id: u32,
    waker: Box<Option<Waker>>,
    _phantom: PhantomData<&'a R>,
}

impl<'a, R: Deserialize<'a>> Event<'_, R> {
    pub fn new(id: u32) -> Self {
        Event {
            id,
            waker: Box::new(None),
            _phantom: PhantomData,
        }
    }
}

impl<'a, R: Deserialize<'a>> Future for Event<'_, R> {
    type Output = R;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match unsafe { __asml_abi_poll(self.id) } {
            1 => Poll::Ready(unsafe { read_response::<Self::Output>(self.id).unwrap() }),
            _ => {
                self.waker = Box::new(Some(cx.waker().clone()));
                Poll::Pending
            }
        }
    }
}

#[derive(Deserialize)]
pub struct Test {}

unsafe fn read_response<'a, R: Deserialize<'a>>(id: u32) -> Option<R> {
    let ptr = __asml_abi_event_ptr(id) as usize;
    let end = __asml_abi_event_len(id) as usize + ptr;

    match serde_json::from_slice::<R>(&EVENT_BUFFER[ptr..end]) {
        Ok(response) => Some(response),
        Err(why) => {
            console_log(why.to_string());
            None
        }
    }
}