perspective_viewer/utils/
wasm_abi.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
5// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13/// A macro for implementing the `wasm_bindgen` boilerplate for types which
14/// implement `serde::{Serialize, Deserialize}`.
15///
16/// # Examples
17///
18/// ```
19/// struct MyStruct { .. }
20/// derive_wasm_abi!(MyStruct, FromWasmAbi);
21///
22/// #[wasm_bindgen]
23/// pub fn process_my_struct(s: MyStruct) {}
24/// ```
25#[macro_export]
26macro_rules! derive_wasm_abi {
27    ($type:ty) => {
28        impl wasm_bindgen::describe::WasmDescribe for $type {
29            fn describe() {
30                <js_sys::Object as wasm_bindgen::describe::WasmDescribe>::describe()
31            }
32        }
33    };
34
35    ($type:ty, FromWasmAbi $(, $symbols:tt)*) => {
36        impl wasm_bindgen::convert::FromWasmAbi for $type {
37            type Abi = <js_sys::Object as wasm_bindgen::convert::IntoWasmAbi>::Abi;
38            #[inline]
39            unsafe fn from_abi(js: Self::Abi) -> Self {
40                let obj = unsafe { js_sys::Object::from_abi(js) };
41                use ::perspective_js::utils::JsValueSerdeExt;
42                wasm_bindgen::JsValue::from(obj).into_serde_ext().unwrap()
43            }
44        }
45
46        derive_wasm_abi!($type $(, $symbols)*);
47    };
48
49    ($type:ty, IntoWasmAbi $(, $symbols:tt)*) => {
50        impl wasm_bindgen::convert::IntoWasmAbi for $type {
51            type Abi = <js_sys::Object as wasm_bindgen::convert::IntoWasmAbi>::Abi;
52            #[inline]
53            fn into_abi(self) -> Self::Abi {
54                use wasm_bindgen::JsCast;
55                <wasm_bindgen::JsValue as ::perspective_js::utils::JsValueSerdeExt>::from_serde_ext(&self).unwrap().unchecked_into::<js_sys::Object>().into_abi()
56            }
57        }
58
59        derive_wasm_abi!($type $(, $symbols)*);
60    };
61}