wsdom_core/js/
value.rs

1use crate::js_cast::JsCast;
2use crate::link::Browser;
3use crate::protocol::{DEL, GET, SET};
4use std::fmt::Write;
5
6/// Represents a value that exists on the JavaScript side.
7/// Value can be anything - number, string, object, undefined, null, ...
8pub struct JsValue {
9    pub(crate) id: u64,
10    pub(crate) browser: Browser,
11}
12
13impl Drop for JsValue {
14    fn drop(&mut self) {
15        let self_id = self.id;
16        let mut link = self.browser.0.lock().unwrap();
17        writeln!(link.raw_commands_buf(), "{DEL}({self_id});",).unwrap();
18        link.wake_outgoing_lazy();
19    }
20}
21
22impl Clone for JsValue {
23    fn clone(&self) -> Self {
24        let self_id = self.id;
25        let out_id = {
26            let mut link = self.browser.0.lock().unwrap();
27            let out_id = link.get_new_id();
28            writeln!(link.raw_commands_buf(), "{SET}({out_id},{GET}({self_id}));").unwrap();
29            link.wake_outgoing_lazy();
30            out_id
31        };
32        Self {
33            id: out_id,
34            browser: self.browser.clone(),
35        }
36    }
37}
38
39impl JsValue {
40    // const MAX_ID: u64 = (1 << 53) - 1;
41    pub fn browser(&self) -> &Browser {
42        &self.browser
43    }
44}
45
46impl AsRef<JsValue> for JsValue {
47    fn as_ref(&self) -> &JsValue {
48        self
49    }
50}
51
52impl JsCast for JsValue {
53    fn unchecked_from_js(val: JsValue) -> Self {
54        val
55    }
56
57    fn unchecked_from_js_ref(val: &JsValue) -> &Self {
58        val
59    }
60}