Skip to main content

script/dom/bindings/
frozenarray.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use js::context::JSContext;
6use js::conversions::ToJSValConvertible;
7use js::jsapi::Heap;
8use js::jsval::JSVal;
9use js::rust::MutableHandleValue;
10use script_bindings::cell::DomRefCell;
11
12use crate::dom::bindings::utils::to_frozen_array;
13
14#[derive(Default, JSTraceable, MallocSizeOf)]
15#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
16pub(crate) struct CachedFrozenArray {
17    #[ignore_malloc_size_of = "This is a heap value stored in mozjs"]
18    frozen_value: DomRefCell<Option<Heap<JSVal>>>,
19}
20
21impl CachedFrozenArray {
22    pub(crate) fn new() -> CachedFrozenArray {
23        CachedFrozenArray {
24            frozen_value: DomRefCell::new(None),
25        }
26    }
27
28    pub(crate) fn get_or_init<F: FnOnce() -> Vec<T>, T: ToJSValConvertible>(
29        &self,
30        cx: &mut JSContext,
31        f: F,
32        mut retval: MutableHandleValue,
33    ) {
34        if let Some(inner) = &*self.frozen_value.borrow() {
35            retval.set(inner.get());
36            return;
37        }
38
39        let array = f();
40        to_frozen_array(cx, array.as_slice(), retval.reborrow());
41
42        // Safety: need to create the Heap value in its final memory location before setting it.
43        *self.frozen_value.safe_borrow_mut(cx.no_gc()) = Some(Heap::default());
44        self.frozen_value
45            .borrow()
46            .as_ref()
47            .unwrap()
48            .set(retval.get());
49    }
50
51    pub(crate) fn clear(&self) {
52        *self.frozen_value.borrow_mut() = None;
53    }
54}