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
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use std::future::Future;
use std::io::BufReader;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};

use serde::{Deserialize, de::DeserializeOwned};

use assemblylift_core_io_common::constants::{FUNCTION_INPUT_BUFFER_SIZE, IO_BUFFER_SIZE_BYTES};

extern "C" {
    // IO
    fn __asml_abi_io_poll(id: u32) -> i32;
    fn __asml_abi_io_len(id: u32) -> u32;
    fn __asml_abi_io_load(id: u32) -> i32;
    fn __asml_abi_io_next() -> i32;

    // System clock
    fn __asml_abi_clock_time_get() -> u64;

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

    // Input
    fn __asml_abi_input_start() -> i32;
    fn __asml_abi_input_next() -> i32;
    fn __asml_abi_input_length_get() -> u64;

    // Z85
    fn __asml_expabi_z85_encode(ptr: *const u8, len: usize, out_ptr: *const u8) -> i32;
    fn __asml_expabi_z85_decode(ptr: *const u8, len: usize, out_ptr: *const u8) -> i32;
}

// Raw buffer holding serialized IO data
pub static mut IO_BUFFER: [u8; IO_BUFFER_SIZE_BYTES] = [0; IO_BUFFER_SIZE_BYTES];

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

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

pub fn get_time() -> u64 {
    unsafe { __asml_abi_clock_time_get() }
}

pub struct IoDocument {
    bytes_read: usize,
    pages_read: usize,
    length: usize,
}

impl IoDocument {
    pub fn new(ioid: u32) -> Self {
        unsafe { __asml_abi_io_load(ioid) };
        Self {
            bytes_read: 0,
            pages_read: 0,
            length: unsafe { __asml_abi_io_len(ioid) } as usize,
        }
    }

    pub fn len(&self) -> usize {
        self.length
    }
}

impl std::io::Read for IoDocument {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
        let mut bytes_read = 0usize;
        if self.bytes_read < self.length {
            for idx in 0..std::cmp::min(self.length, buf.len()) {
                // unsafe: bytes_read is always positive, mod IO_BUFFER_SIZE_BYTES 
                //         is always less than IO_BUFFER_SIZE_BYTES
                buf[idx] = unsafe { 
                    IO_BUFFER[self.bytes_read % IO_BUFFER_SIZE_BYTES]
                };
                bytes_read += 1;
                self.bytes_read += 1;
                if self.bytes_read % IO_BUFFER_SIZE_BYTES == 0 {
                    unsafe { __asml_abi_io_next() };
                    self.pages_read += 1;
                }
            }
        }
        Ok(bytes_read)
    }
}

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

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

impl<'a, R> Future for Io<'_, R> 
where
    R: DeserializeOwned,
{
    type Output = R;

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

fn read_response<'a, T>(id: u32) -> Option<T>
where
    T: DeserializeOwned,
{
    let doc = IoDocument::new(id);
    let doc = BufReader::with_capacity(doc.len(), doc);
    match serde_json::from_reader::<BufReader<IoDocument>, T>(doc) {
        Ok(response) => Some(response),
        Err(why) => {
            console_log(format!("[ERROR] ioid={} {}", id, why.to_string()));
            None
        }
    }
}

// Function Input Buffer

pub static mut FUNCTION_INPUT_BUFFER: [u8; FUNCTION_INPUT_BUFFER_SIZE] =
    [0; FUNCTION_INPUT_BUFFER_SIZE];

// provided TO the wasm runtime (host)
#[no_mangle]
pub fn __asml_guest_get_function_input_buffer_pointer() -> *const u8 {
    unsafe { FUNCTION_INPUT_BUFFER.as_ptr() }
}

pub struct FunctionInputBuffer {
    bytes_read: usize,
    pages_read: usize,
    length: usize,
}

impl FunctionInputBuffer {
    pub fn new() -> Self {
        unsafe { __asml_abi_input_start() };
        Self {
            bytes_read: 0usize,
            pages_read: 0usize,
            length: unsafe { __asml_abi_input_length_get() as usize },
        }
    }
}

impl std::io::Read for FunctionInputBuffer {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
        let mut bytes_read = 0usize;
        if self.bytes_read < self.length {
            for idx in 0..std::cmp::min(self.length, buf.len()) {
                // unsafe: bytes_read is always positive, mod FUNCTION_INPUT_BUFFER_SIZE
                //         is always less than FUNCTION_INPUT_BUFFER_SIZE
                buf[idx] = unsafe {
                    FUNCTION_INPUT_BUFFER[self.bytes_read % FUNCTION_INPUT_BUFFER_SIZE]
                };
                bytes_read += 1;
                self.bytes_read += 1;
                if self.bytes_read % FUNCTION_INPUT_BUFFER_SIZE == 0 {
                    unsafe { __asml_abi_input_next() };
                    self.pages_read += 1;
                }
            }
        }
        Ok(bytes_read)
    }
}