Skip to main content

quickjs_jit_stdlib/llrt/llrt_stream_web/utils/
mod.rs

1// Vendored from LLRT d9fd873e793c (modules/llrt_stream_web/src/utils/mod.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3use crate::utils::option::Undefined;
4use rquickjs::{
5    class::{JsClass, OwnedBorrowMut},
6    Class, Ctx, FromJs, IntoAtom, Object, Result, Value,
7};
8
9pub mod promise;
10pub mod queue;
11
12// the trait used elsewhere in this repo accepts null values as 'None', which causes many web platform tests to fail as they
13// like to check that undefined is accepted and null isn't.
14pub trait ValueOrUndefined<'js> {
15    fn get_value_or_undefined<K: IntoAtom<'js> + Clone, V: FromJs<'js>>(
16        &self,
17        k: K,
18    ) -> Result<Option<V>>;
19}
20
21impl<'js> ValueOrUndefined<'js> for Object<'js> {
22    fn get_value_or_undefined<K: IntoAtom<'js> + Clone, V: FromJs<'js> + Sized>(
23        &self,
24        k: K,
25    ) -> Result<Option<V>> {
26        let value = self.get::<K, Value<'js>>(k)?;
27        Ok(Undefined::from_js(self.ctx(), value)?.0)
28    }
29}
30
31impl<'js> ValueOrUndefined<'js> for Value<'js> {
32    fn get_value_or_undefined<K: IntoAtom<'js> + Clone, V: FromJs<'js>>(
33        &self,
34        k: K,
35    ) -> Result<Option<V>> {
36        if let Some(obj) = self.as_object() {
37            return obj.get_value_or_undefined(k);
38        }
39        Ok(None)
40    }
41}
42
43pub trait UnwrapOrUndefined<'js> {
44    fn unwrap_or_undefined(self, ctx: &Ctx<'js>) -> Value<'js>;
45}
46
47impl<'js> UnwrapOrUndefined<'js> for Option<Value<'js>> {
48    fn unwrap_or_undefined(self, ctx: &Ctx<'js>) -> Value<'js> {
49        self.unwrap_or_else(|| Value::new_undefined(ctx.clone()))
50    }
51}
52
53pub fn class_from_owned_borrow_mut<'js, T: JsClass<'js>>(
54    borrow: OwnedBorrowMut<'js, T>,
55) -> (Class<'js, T>, OwnedBorrowMut<'js, T>) {
56    let class = borrow.into_inner();
57    let borrow = OwnedBorrowMut::from_class(class.clone());
58    (class, borrow)
59}