ion/root/
heap.rs

1/*
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 */
6
7use std::marker::PhantomPinned;
8
9use mozjs::gc::{GCMethods, RootKind, RootedTraceableSet, Traceable};
10use mozjs::jsapi::Heap;
11
12use crate::Local;
13
14#[derive(Debug)]
15pub struct TracedHeap<T: GCMethods + Copy + 'static>
16where
17	Heap<T>: Traceable,
18{
19	heap: Box<Heap<T>>,
20	_pin: PhantomPinned,
21}
22
23impl<T: GCMethods + Copy + 'static> TracedHeap<T>
24where
25	Heap<T>: Traceable + Default,
26{
27	pub fn new(value: T) -> TracedHeap<T> {
28		let heap = Heap::boxed(value);
29		unsafe { RootedTraceableSet::add(&*heap) };
30		TracedHeap { heap, _pin: PhantomPinned }
31	}
32}
33
34impl<T: GCMethods + Copy + 'static> TracedHeap<T>
35where
36	Heap<T>: Traceable,
37{
38	pub fn get(&self) -> T {
39		self.heap.get()
40	}
41
42	pub fn set(&self, value: T) {
43		self.heap.set(value);
44	}
45}
46
47impl<T: GCMethods + RootKind + Copy + 'static> TracedHeap<T>
48where
49	Heap<T>: Traceable,
50{
51	pub fn to_local(&self) -> Local<'_, T> {
52		unsafe { Local::from_heap(&self.heap) }
53	}
54}
55
56impl<T: GCMethods + Copy + 'static> Drop for TracedHeap<T>
57where
58	Heap<T>: Traceable,
59{
60	fn drop(&mut self) {
61		unsafe { RootedTraceableSet::remove(&*self.heap) }
62	}
63}