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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// Copyright 2018 Vladimir Iftodi <Vladimir.Iftodi@gmail.com>. 
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::io::Cursor;
use std::cell::RefCell;
use std::collections::HashMap;

mod wasm_ffi;
mod rust_exports;
mod js_ser;
mod ser_constants;

use ser_constants::TypeTag;
pub use js_ser::JsSerializable;

#[macro_use]
extern crate num_derive;
extern crate num_traits;
extern crate byteorder;

use byteorder::{LittleEndian, ReadBytesExt,};
use num_traits::FromPrimitive;

#[no_mangle]
pub extern "C" fn wasm_val_rust_alloc(capacity: u32) -> *mut u8 {
    rust_exports::rust_alloc(capacity)
}

#[no_mangle]
pub extern "C" fn wasm_val_get_api_version() -> u32 {
    rust_exports::get_api_version()
}

thread_local! {
    static CALLBACKS_KEY: RefCell<HashMap<u32, Box<dyn Fn()>>> = RefCell::new(HashMap::new());
    static CALLBACKS_ARG_KEY: RefCell<HashMap<u32, Box<dyn Fn(JsValue)>>> = RefCell::new(HashMap::new());
    static LAST_CALLBACK_ID_KEY: RefCell<u32> = RefCell::new(1);
}

#[no_mangle]
pub extern "C" fn wasm_val_call_registered_callback(key: u32) -> () {
    CALLBACKS_KEY.with(|callbacks_cell| {
        (callbacks_cell.borrow()[&key])()
    })
}

#[no_mangle]
pub extern "C" fn wasm_val_call_registered_callback_arg(key: u32, ptr: *mut u8) -> () {
    let vec = unsafe { Vec::from_raw_parts(ptr, wasm_ffi::SINGLE_VAL_VEC_LEN, wasm_ffi::SINGLE_VAL_VEC_LEN) };
    let val = JsValue::get_single_val(vec);
    
    CALLBACKS_ARG_KEY.with(|callbacks_cell| {
        (callbacks_cell.borrow()[&key])(val)
    })
}

fn get_next_callback_id() -> u32 {
    LAST_CALLBACK_ID_KEY.with(|last_callback_id_cell| {
        let id = *last_callback_id_cell.borrow();

        last_callback_id_cell.replace(id + 1);

        id
    })
}

fn register_callback(callback:  &'static Fn() -> ()) -> u32  {
        CALLBACKS_KEY.with(|callbacks_cell| {
            let id = get_next_callback_id();
            callbacks_cell.borrow_mut().insert(id, Box::new(callback));

            id
        })
}

fn register_callback_arg(callback:  &'static Fn(JsValue) -> ()) -> u32  {
        CALLBACKS_ARG_KEY.with(|callbacks_cell| {
            let id = get_next_callback_id();
            callbacks_cell.borrow_mut().insert(id, Box::new(callback));

            id
        })
}

pub struct JsValue {
    pub js_type: Type,
    val: Val,
}

impl Drop for JsValue {
    fn drop(&mut self) {
        match self.val {
            Val::Ref(ref_id) => wasm_ffi::drop_var(ref_id),
            _ => (),
        }
    }
}

impl JsValue {

     fn get_single_val(vec: Vec<u8>) -> JsValue {
        let mut curs = Cursor::new(vec);
        let tag = curs.read_u8().unwrap();
        let type_tag = TypeTag::from_u8(tag).unwrap();

        match type_tag {
            TypeTag::Empty => JsValue{js_type: Type::Empty, val: Val::None},
            TypeTag::BoolFalse => JsValue{js_type: Type::Boolean, val: Val::Boolean(false)},
            TypeTag::BoolTrue => JsValue{js_type: Type::Boolean, val: Val::Boolean(true)},
            TypeTag::F64 => JsValue{js_type: Type::Number, val: Val::Number(curs.read_f64::<LittleEndian>().unwrap())},
            TypeTag::String => {
                let str_len = curs.read_u32::<LittleEndian>().unwrap();
                let str_ptr = curs.read_u32::<LittleEndian>().unwrap() as *mut u8;
                
                let s = unsafe { String::from_raw_parts(str_ptr, str_len as usize, str_len as usize) };

                JsValue{js_type: Type::String, val: Val::String(s)}
            },
            TypeTag::Object => {
                let ref_id = curs.read_u32::<LittleEndian>().unwrap();

                JsValue{js_type: Type::Object, val: Val::Ref(ref_id)}
            },
            TypeTag::Function => {
                let ref_id = curs.read_u32::<LittleEndian>().unwrap();

                JsValue{js_type: Type::Function, val: Val::Ref(ref_id)}
            }
            _ => panic!()
        }
    }

    pub fn get_global(name: &str) -> JsValue {
        let vec = wasm_ffi::get_val_global(name);

        JsValue::get_single_val(vec)
    }


    pub fn get_val(&self, name: &str) -> Option<JsValue> {
        match self.val {
            Val::Ref(ref_id)  => {
                let vec = wasm_ffi::get_val(ref_id, name);

                Some(JsValue::get_single_val(vec))
            },
            _ => None
        }
    }

    pub fn set_val<S>(&self, name: &str, val: S) -> () where S: JsSerializable {
        match self.val {
            Val::Ref(ref_id) => {
                let mut vec = Vec::with_capacity(wasm_ffi::SINGLE_VAL_VEC_LEN);
                let mut cursor = Cursor::new(vec);

                val.ser(&mut cursor);

                wasm_ffi::set_val(ref_id, name, cursor.into_inner());

            }
            _ => ()
        }
    }

    pub fn call(&self) -> Option<JsValue> {
        match self {
            JsValue{js_type: Type::Function, val: Val::Ref(ref_id)} => {
                let ret_vec = wasm_ffi::call_0(*ref_id);

                Some(JsValue::get_single_val(ret_vec))
            },
            _ => None
        }
    }

    pub fn call_with_arg<S>(&self, arg: S) -> Option<JsValue> where S: JsSerializable {
        match self {
            JsValue{js_type: Type::Function, val: Val::Ref(ref_id)} => {
                let vec = Vec::with_capacity(9);
                let mut cursor = Cursor::new(vec);

                arg.ser(&mut cursor);

                let ret_vec = wasm_ffi::call_1(*ref_id, cursor.into_inner());

                Some(JsValue::get_single_val(ret_vec))
            },
            _ => None
        }
    }

    pub fn call_with_args(&self, args: &[&JsSerializable]) -> Option<JsValue> {
        match self {
            JsValue{js_type: Type::Function, val: Val::Ref(ref_id)} => {
                let alloc_size = args.iter().fold(0_u32, |acc, val| acc + val.size());
                let vec: Vec<u8> = Vec::with_capacity(alloc_size as usize);
                let mut cursor = Cursor::new(vec);

                for arg in args {
                    arg.ser(&mut cursor);
                }

                let ret_vec = wasm_ffi::call_args(*ref_id, args.len() as u32, cursor.into_inner());

                Some(JsValue::get_single_val(ret_vec))
            },
            _ => None
        }
    }

    pub fn call_method(&self, name: &str) -> Option<JsValue> {
        match self.val {
            Val::Ref(ref_id)  => {
                let ret_vec = wasm_ffi::call_method_0(ref_id, name);

                Some(JsValue::get_single_val(ret_vec))
            },
            _ => None
        }
    }

    pub fn call_method_with_arg<S>(&self, name: &str, arg: S) -> Option<JsValue> where S: JsSerializable {
        match self.val {
            Val::Ref(ref_id)  => {
                let vec = Vec::with_capacity(9);
                let mut cursor = Cursor::new(vec);

                arg.ser(&mut cursor);

                let ret_vec = wasm_ffi::call_method_1(ref_id, name, cursor.into_inner());

                Some(JsValue::get_single_val(ret_vec))
            },
            _ => None
        }
    }

    pub fn call_method_with_args(&self, name: &str, args: &[&JsSerializable]) -> Option<JsValue> {
        match self.val {
            Val::Ref(ref_id)  => {
                let alloc_size = args.iter().fold(0_u32, |acc, val| acc + val.size());
                let vec: Vec<u8> = Vec::with_capacity(alloc_size as usize);
                let mut cursor = Cursor::new(vec);

                for arg in args {
                    arg.ser(&mut cursor);
                }

                let ret_vec = wasm_ffi::call_method_args(ref_id, name, args.len() as u32, cursor.into_inner());

                Some(JsValue::get_single_val(ret_vec))
            },
            _ => None
        }
    }

    pub fn new(&self) -> Option<JsValue> {
        match self {
            JsValue{js_type: Type::Function, val: Val::Ref(ref_id)} => {
                let vec = wasm_ffi::new_0(*ref_id);

                Some(JsValue::get_single_val(vec))
            },
            _ => None,
        }
    }

    pub fn new_with_arg<S>(&self, arg: S) -> Option<JsValue> where S: JsSerializable {
        match self.val {
            Val::Ref(ref_id) => {
                let mut vec = Vec::with_capacity(9);
                let mut cursor = Cursor::new(vec);

                arg.ser(&mut cursor);

                let ret_vec = wasm_ffi::new_1(ref_id, cursor.into_inner());

                Some(JsValue::get_single_val(ret_vec))
            },
            _ => None
        }
    }

    pub fn new_with_args(&self, args: &[&JsSerializable]) -> Option<JsValue> {
        match self.val {
            Val::Ref(ref_id) => {
                let mut vec = Vec::with_capacity(9);
                let mut cursor = Cursor::new(vec);

                for arg in args {
                    arg.ser(&mut cursor);
                }

                let ret_vec = wasm_ffi::new_args(ref_id, args.len() as u32, cursor.into_inner());

                Some(JsValue::get_single_val(ret_vec))
            },
            _ => None
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self.val {
            Val::Boolean(b) => Some(b),
            _ => None
        }
    }

    pub fn as_number(&self) -> Option<f64> {
        match self.val {
            Val::Number(f) => Some(f),
            _ => None
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        match self.val {
            Val::String(ref s) => Some(s.as_str()),
            _ => None
        }
    }
}

pub enum Type {
    Empty,
    Boolean,
    Number,
    String,
    Array,
    TypedArray(ArrayType),
    Object,
    Function,
    Error,
}

pub enum ArrayType {
    I8,
    U8,
    I16,
    U16,
    I32,
    U32,
    F32,
    F64,
}

enum Val {
    None,
    Boolean(bool),
    Number(f64),
    String(String),
    Ref(u32),
}