Skip to main content

webbluetooth_node/
object.rs

1//! JavaScript objects that own a Rust value.
2//!
3//! The Web Bluetooth API is an object graph — a device has a `gatt`, a server
4//! hands out services, a service hands out characteristics — and each of those
5//! objects has to carry the Rust handle it stands for.
6//!
7//! `napi_wrap` is how: an ordinary object gets an owned `Box<T>` attached, and
8//! a finalizer frees it when the object is collected. Methods go on the
9//! instance rather than a prototype, because there is no class here to hang a
10//! prototype from and an instance property is what `napi_create_function`
11//! produces anyway.
12//!
13//! The alternative — returning plain records and rebuilding the graph in a
14//! JavaScript wrapper — means the shape of the API lives in two places and
15//! only one of them is checked by a compiler.
16
17use crate::napi::*;
18use crate::value::{self, Result, Thrown};
19use std::ffi::c_void;
20
21/// Free the `Box<T>` a [`wrap`] attached.
22///
23/// # Safety
24/// Called by the runtime with the pointer given to `napi_wrap`.
25unsafe extern "C" fn finalize<T>(_env: napi_env, data: *mut c_void, _hint: *mut c_void) {
26    if !data.is_null() {
27        drop(unsafe { Box::from_raw(data as *mut T) });
28    }
29}
30
31/// A new object owning `value`, with `methods` on it.
32///
33/// Each method is handed the same `T` when it runs: the callback reads it back
34/// with [`unwrap`]. Nothing is shared between objects, so two devices cannot
35/// see each other's state.
36pub fn wrap<T: 'static>(
37    env: napi_env,
38    value_of: T,
39    methods: &[(&'static std::ffi::CStr, napi_callback)],
40) -> Result<napi_value> {
41    wrap_with(env, value_of, methods, &[])
42}
43
44/// As [`wrap`], with properties whose value is computed on each read.
45///
46/// `gatt.connected` has to be a getter rather than a stored field: it changes
47/// under the caller, and a value copied in at construction would be a lie the
48/// moment the link dropped.
49pub fn wrap_with<T: 'static>(
50    env: napi_env,
51    value_of: T,
52    methods: &[(&'static std::ffi::CStr, napi_callback)],
53    getters: &[(&'static std::ffi::CStr, napi_callback)],
54) -> Result<napi_value> {
55    let object = value::object(env)?;
56    let boxed = Box::into_raw(Box::new(value_of)) as *mut c_void;
57
58    // Attached before the methods, so a method that somehow ran during
59    // construction would still find its value.
60    value::ok(
61        unsafe {
62            napi_wrap(
63                env,
64                object,
65                boxed,
66                Some(finalize::<T>),
67                std::ptr::null_mut(),
68                std::ptr::null_mut(),
69            )
70        },
71        "napi_wrap",
72    )
73    .inspect_err(|_| {
74        // The runtime did not take ownership, so this side still has it.
75        drop(unsafe { Box::from_raw(boxed as *mut T) });
76    })?;
77
78    for (name, callback) in methods {
79        let mut function = std::ptr::null_mut();
80        value::ok(
81            unsafe {
82                napi_create_function(
83                    env,
84                    name.as_ptr(),
85                    // `NAPI_AUTO_LENGTH`: the name is NUL-terminated.
86                    usize::MAX,
87                    *callback,
88                    std::ptr::null_mut(),
89                    &mut function,
90                )
91            },
92            "napi_create_function",
93        )?;
94        let name = name
95            .to_str()
96            .map_err(|_| Thrown("a method name was not UTF-8".into()))?;
97        value::set(env, object, name, function)?;
98    }
99
100    for (name, getter) in getters {
101        let descriptor = napi_property_descriptor {
102            utf8name: name.as_ptr(),
103            name: std::ptr::null_mut(),
104            method: None,
105            getter: Some(*getter),
106            setter: None,
107            value: std::ptr::null_mut(),
108            // Enumerable, so it shows up the way a plain field would.
109            attributes: 2,
110            data: std::ptr::null_mut(),
111        };
112        value::ok(
113            unsafe { napi_define_properties(env, object, 1, &descriptor) },
114            "napi_define_properties",
115        )?;
116    }
117    Ok(object)
118}
119
120/// The value a [`wrap`] attached to `this`.
121///
122/// # Safety
123/// `object` must be one this module wrapped with the same `T`. A method
124/// reached through the object it was defined on always is; one detached and
125/// called on something else is not, which is why this checks the status rather
126/// than casting blind.
127pub unsafe fn unwrap<T: 'static>(env: napi_env, object: napi_value) -> Result<&'static T> {
128    let mut data: *mut c_void = std::ptr::null_mut();
129    value::ok(
130        unsafe { napi_unwrap(env, object, &mut data) },
131        "napi_unwrap",
132    )?;
133    if data.is_null() {
134        return Err(Thrown(
135            "this method was called on something that is not the object it belongs to".into(),
136        ));
137    }
138    // SAFETY: the box is owned by the object and freed only by the finalizer,
139    // which runs after the last reference to the object is gone — so it
140    // outlives any call made through it.
141    Ok(unsafe { &*(data as *const T) })
142}
143
144/// The `this` of a call, and its arguments.
145///
146/// # Safety
147/// `info` must be the callback info the runtime passed to this callback.
148pub unsafe fn this_and_args(
149    env: napi_env,
150    info: napi_callback_info,
151    count: usize,
152) -> Result<(napi_value, Vec<napi_value>)> {
153    let mut argc = count;
154    let mut argv = vec![std::ptr::null_mut(); count.max(1)];
155    let mut this = std::ptr::null_mut();
156    value::ok(
157        unsafe {
158            napi_get_cb_info(
159                env,
160                info,
161                &mut argc,
162                argv.as_mut_ptr(),
163                &mut this,
164                std::ptr::null_mut(),
165            )
166        },
167        "napi_get_cb_info",
168    )?;
169    argv.truncate(count);
170    Ok((this, argv))
171}
172
173/// Hold a JavaScript value past the call that produced it.
174///
175/// An event listener is registered once and called later, so it cannot live in
176/// the handle scope it arrived in.
177pub struct Held {
178    reference: napi_ref,
179}
180
181// SAFETY: a `napi_ref` is an opaque handle the runtime owns. It is created and
182// read on the runtime's thread; this type only carries it between them.
183unsafe impl Send for Held {}
184unsafe impl Sync for Held {}
185
186// The reference is deliberately never deleted by hand. A listener lives as
187// long as the characteristic that owns it: when that object is collected the
188// `Held` goes with it, and the runtime reclaims the reference with the object
189// it points into. Releasing earlier would mean tracking, from a background
190// pump, whether JavaScript still holds the callback — which is the question
191// the collector already answers.
192impl Held {
193    pub fn new(env: napi_env, value: napi_value) -> Result<Self> {
194        let mut reference = std::ptr::null_mut();
195        value::ok(
196            unsafe { napi_create_reference(env, value, 1, &mut reference) },
197            "napi_create_reference",
198        )?;
199        Ok(Self { reference })
200    }
201
202    /// The value, valid for this turn of the event loop.
203    ///
204    /// # Safety
205    /// Must be called on the runtime's thread.
206    pub unsafe fn get(&self, env: napi_env) -> Result<napi_value> {
207        let mut out = std::ptr::null_mut();
208        value::ok(
209            unsafe { napi_get_reference_value(env, self.reference, &mut out) },
210            "napi_get_reference_value",
211        )?;
212        Ok(out)
213    }
214
215    /// Call it with one argument, discarding the result.
216    ///
217    /// # Safety
218    /// Must be called on the runtime's thread.
219    pub unsafe fn call(&self, env: napi_env, argument: napi_value) -> Result<()> {
220        let function = unsafe { self.get(env) }?;
221        let undefined = value::undefined(env)?;
222        let args = [argument];
223        value::ok(
224            unsafe {
225                napi_call_function(
226                    env,
227                    undefined,
228                    function,
229                    args.len(),
230                    args.as_ptr(),
231                    std::ptr::null_mut(),
232                )
233            },
234            "napi_call_function",
235        )
236    }
237}
238
239/// A method name and the callback behind it.
240///
241/// Spelled out so a table of methods reads as a table rather than as a tuple
242/// whose halves you have to remember the order of.
243#[macro_export]
244macro_rules! methods {
245    ($($name:literal => $callback:path),* $(,)?) => {
246        &[$((
247            // A C string, checked at compile time.
248            match std::ffi::CStr::from_bytes_with_nul(concat!($name, "\0").as_bytes()) {
249                Ok(s) => s,
250                Err(_) => panic!("a method name held a NUL"),
251            },
252            $callback as $crate::napi::napi_callback,
253        )),*]
254    };
255}
256
257#[cfg(test)]
258mod tests {
259    /// Every method name is a `c"..."` literal, so a NUL inside one is a
260    /// compile error rather than a property registered under a truncated name
261    /// that every call site then misses.
262    #[test]
263    fn method_names_are_nul_terminated_at_compile_time() {
264        assert_eq!(c"readValue".to_bytes(), b"readValue");
265        assert_eq!(c"readValue".to_bytes_with_nul().last(), Some(&0));
266    }
267
268    /// `NAPI_AUTO_LENGTH` is `usize::MAX` — the runtime's signal to measure a
269    /// NUL-terminated string itself. Passing a real length here would be a
270    /// byte count, and getting it wrong truncates the method name silently.
271    #[test]
272    fn auto_length_is_the_sentinel_the_runtime_expects() {
273        const NAPI_AUTO_LENGTH: usize = usize::MAX;
274        assert_eq!(NAPI_AUTO_LENGTH, usize::MAX);
275    }
276}