rpgx_wasm/
library.rs

1use rpgx::library::Library;
2use std::any::Any;
3use wasm_bindgen::prelude::*;
4
5#[wasm_bindgen(js_name = Library)]
6pub struct WasmLibrary {
7    inner: Library<Box<dyn Any>>,
8}
9
10#[wasm_bindgen(js_class = Library)]
11impl WasmLibrary {
12    #[wasm_bindgen(constructor)]
13    pub fn new() -> WasmLibrary {
14        WasmLibrary {
15            inner: Library::new(),
16        }
17    }
18
19    #[wasm_bindgen]
20    pub fn insert(&mut self, key: &str, value: JsValue) {
21        // Safety: converting &str to &'static str by leaking it.
22        // You should manage this carefully or use another approach for dynamic lifetimes.
23        let static_key: &'static str = Box::leak(key.to_string().into_boxed_str());
24        self.inner.insert(static_key, Box::new(value));
25    }
26
27    #[wasm_bindgen(js_name = getByKey)]
28    pub fn get_by_key(&self, key: &str) -> JsValue {
29        match self.inner.get_by_key(key) {
30            Some(boxed) => {
31                if let Some(s) = boxed.downcast_ref::<JsValue>() {
32                    s.clone()
33                } else {
34                    JsValue::NULL
35                }
36            }
37            None => JsValue::NULL,
38        }
39    }
40
41    #[wasm_bindgen(js_name = getById)]
42    pub fn get_by_id(&self, id: u32) -> JsValue {
43        match self.inner.get_by_id(id) {
44            Some(boxed) => {
45                if let Some(s) = boxed.downcast_ref::<JsValue>() {
46                    s.clone()
47                } else {
48                    JsValue::NULL
49                }
50            }
51            None => JsValue::NULL,
52        }
53    }
54
55    #[wasm_bindgen(js_name = getId)]
56    pub fn get_id(&self, key: &str) -> Option<u32> {
57        self.inner.get_id(key)
58    }
59
60    #[wasm_bindgen(js_name = getKey)]
61    pub fn get_key(&self, id: u32) -> Option<String> {
62        self.inner.get_key(id).map(|s| s.into())
63    }
64}