aboutsummaryrefslogtreecommitdiffstats
path: root/components/script/dom/bindings/root.rs
blob: 417d4b9de52ba490dca31da72119d780863ed163 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Smart pointers for the JS-managed DOM objects.
//!
//! The DOM is made up of DOM objects whose lifetime is entirely controlled by
//! the whims of the SpiderMonkey garbage collector. The types in this module
//! are designed to ensure that any interactions with said Rust types only
//! occur on values that will remain alive the entire time.
//!
//! Here is a brief overview of the important types:
//!
//! - `Root<T>`: a stack-based reference to a rooted DOM object.
//! - `Dom<T>`: a reference to a DOM object that can automatically be traced by
//!   the GC when encountered as a field of a Rust structure.
//!
//! `Dom<T>` does not allow access to their inner value without explicitly
//! creating a stack-based root via the `root` method. This returns a `Root<T>`,
//! which causes the JS-owned value to be uncollectable for the duration of the
//! `Root` object's lifetime. A reference to the object can then be obtained
//! from the `Root` object. These references are not allowed to outlive their
//! originating `Root<T>`.
//!

use core::nonzero::NonZero;
use dom::bindings::conversions::DerivedFrom;
use dom::bindings::inheritance::Castable;
use dom::bindings::reflector::{DomObject, Reflector};
use dom::bindings::trace::JSTraceable;
use dom::bindings::trace::trace_reflector;
use dom::node::Node;
use heapsize::HeapSizeOf;
use js::jsapi::{JSObject, JSTracer, Heap};
use js::rust::GCMethods;
use mitochondria::OnceCell;
use script_layout_interface::TrustedNodeAddress;
use script_thread::STACK_ROOTS;
use std::cell::UnsafeCell;
use std::default::Default;
use std::hash::{Hash, Hasher};
#[cfg(debug_assertions)]
use std::intrinsics::type_name;
use std::mem;
use std::ops::Deref;
use std::ptr;
use std::rc::Rc;
use style::thread_state;

/// A traced reference to a DOM object
///
/// This type is critical to making garbage collection work with the DOM,
/// but it is very dangerous; if garbage collection happens with a `Dom<T>`
/// on the stack, the `Dom<T>` can point to freed memory.
///
/// This should only be used as a field in other DOM objects.
#[must_root]
pub struct Dom<T> {
    ptr: NonZero<*const T>,
}

// Dom<T> is similar to Rc<T>, in that it's not always clear how to avoid double-counting.
// For now, we choose not to follow any such pointers.
impl<T> HeapSizeOf for Dom<T> {
    fn heap_size_of_children(&self) -> usize {
        0
    }
}

impl<T> Dom<T> {
    /// Returns `LayoutDom<T>` containing the same pointer.
    pub unsafe fn to_layout(&self) -> LayoutDom<T> {
        debug_assert!(thread_state::get().is_layout());
        LayoutDom {
            ptr: self.ptr.clone(),
        }
    }
}

impl<T: DomObject> Dom<T> {
    /// Create a Dom<T> from a &T
    #[allow(unrooted_must_root)]
    pub fn from_ref(obj: &T) -> Dom<T> {
        debug_assert!(thread_state::get().is_script());
        Dom {
            ptr: unsafe { NonZero::new_unchecked(&*obj) },
        }
    }
}

impl<'root, T: DomObject + 'root> RootedReference<'root> for Dom<T> {
    type Ref = &'root T;
    fn r(&'root self) -> &'root T {
        &self
    }
}

impl<T: DomObject> Deref for Dom<T> {
    type Target = T;

    fn deref(&self) -> &T {
        debug_assert!(thread_state::get().is_script());
        // We can only have &Dom<T> from a rooted thing, so it's safe to deref
        // it to &T.
        unsafe { &*self.ptr.get() }
    }
}

unsafe impl<T: DomObject> JSTraceable for Dom<T> {
    unsafe fn trace(&self, trc: *mut JSTracer) {
        #[cfg(debug_assertions)]
        let trace_str = format!("for {} on heap", type_name::<T>());
        #[cfg(debug_assertions)]
        let trace_info = &trace_str[..];
        #[cfg(not(debug_assertions))]
        let trace_info = "for DOM object on heap";

        trace_reflector(trc,
                        trace_info,
                        (*self.ptr.get()).reflector());
    }
}

/// An unrooted reference to a DOM object for use in layout. `Layout*Helpers`
/// traits must be implemented on this.
#[allow_unrooted_interior]
pub struct LayoutDom<T> {
    ptr: NonZero<*const T>,
}

impl<T: Castable> LayoutDom<T> {
    /// Cast a DOM object root upwards to one of the interfaces it derives from.
    pub fn upcast<U>(&self) -> LayoutDom<U>
        where U: Castable,
              T: DerivedFrom<U>
    {
        debug_assert!(thread_state::get().is_layout());
        let ptr: *const T = self.ptr.get();
        LayoutDom {
            ptr: unsafe { NonZero::new_unchecked(ptr as *const U) },
        }
    }

    /// Cast a DOM object downwards to one of the interfaces it might implement.
    pub fn downcast<U>(&self) -> Option<LayoutDom<U>>
        where U: DerivedFrom<T>
    {
        debug_assert!(thread_state::get().is_layout());
        unsafe {
            if (*self.unsafe_get()).is::<U>() {
                let ptr: *const T = self.ptr.get();
                Some(LayoutDom {
                    ptr: NonZero::new_unchecked(ptr as *const U),
                })
            } else {
                None
            }
        }
    }
}

impl<T: DomObject> LayoutDom<T> {
    /// Get the reflector.
    pub unsafe fn get_jsobject(&self) -> *mut JSObject {
        debug_assert!(thread_state::get().is_layout());
        (*self.ptr.get()).reflector().get_jsobject().get()
    }
}

impl<T> Copy for LayoutDom<T> {}

impl<T> PartialEq for Dom<T> {
    fn eq(&self, other: &Dom<T>) -> bool {
        self.ptr == other.ptr
    }
}

impl<T> Eq for Dom<T> {}

impl<T> PartialEq for LayoutDom<T> {
    fn eq(&self, other: &LayoutDom<T>) -> bool {
        self.ptr == other.ptr
    }
}

impl<T> Eq for LayoutDom<T> {}

impl<T> Hash for Dom<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.ptr.hash(state)
    }
}

impl<T> Hash for LayoutDom<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.ptr.hash(state)
    }
}

impl <T> Clone for Dom<T> {
    #[inline]
    #[allow(unrooted_must_root)]
    fn clone(&self) -> Dom<T> {
        debug_assert!(thread_state::get().is_script());
        Dom {
            ptr: self.ptr.clone(),
        }
    }
}

impl <T> Clone for LayoutDom<T> {
    #[inline]
    fn clone(&self) -> LayoutDom<T> {
        debug_assert!(thread_state::get().is_layout());
        LayoutDom {
            ptr: self.ptr.clone(),
        }
    }
}

impl LayoutDom<Node> {
    /// Create a new JS-owned value wrapped from an address known to be a
    /// `Node` pointer.
    pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> LayoutDom<Node> {
        debug_assert!(thread_state::get().is_layout());
        let TrustedNodeAddress(addr) = inner;
        LayoutDom {
            ptr: NonZero::new_unchecked(addr as *const Node),
        }
    }
}

/// A holder that provides interior mutability for GC-managed values such as
/// `Dom<T>`.  Essentially a `Cell<Dom<T>>`, but safer.
///
/// This should only be used as a field in other DOM objects; see warning
/// on `Dom<T>`.
#[must_root]
#[derive(JSTraceable)]
pub struct MutDom<T: DomObject> {
    val: UnsafeCell<Dom<T>>,
}

impl<T: DomObject> MutDom<T> {
    /// Create a new `MutDom`.
    pub fn new(initial: &T) -> MutDom<T> {
        debug_assert!(thread_state::get().is_script());
        MutDom {
            val: UnsafeCell::new(Dom::from_ref(initial)),
        }
    }

    /// Set this `MutDom` to the given value.
    pub fn set(&self, val: &T) {
        debug_assert!(thread_state::get().is_script());
        unsafe {
            *self.val.get() = Dom::from_ref(val);
        }
    }

    /// Get the value in this `MutDom`.
    pub fn get(&self) -> Root<T> {
        debug_assert!(thread_state::get().is_script());
        unsafe {
            Root::from_ref(&*ptr::read(self.val.get()))
        }
    }
}

impl<T: DomObject> HeapSizeOf for MutDom<T> {
    fn heap_size_of_children(&self) -> usize {
        // See comment on HeapSizeOf for Dom<T>.
        0
    }
}

impl<T: DomObject> PartialEq for MutDom<T> {
   fn eq(&self, other: &Self) -> bool {
        unsafe {
            *self.val.get() == *other.val.get()
        }
    }
}

impl<T: DomObject + PartialEq> PartialEq<T> for MutDom<T> {
    fn eq(&self, other: &T) -> bool {
        unsafe {
            **self.val.get() == *other
        }
    }
}

/// A holder that provides interior mutability for GC-managed values such as
/// `Dom<T>`, with nullability represented by an enclosing Option wrapper.
/// Essentially a `Cell<Option<Dom<T>>>`, but safer.
///
/// This should only be used as a field in other DOM objects; see warning
/// on `Dom<T>`.
#[must_root]
#[derive(JSTraceable)]
pub struct MutNullableDom<T: DomObject> {
    ptr: UnsafeCell<Option<Dom<T>>>,
}

impl<T: DomObject> MutNullableDom<T> {
    /// Create a new `MutNullableDom`.
    pub fn new(initial: Option<&T>) -> MutNullableDom<T> {
        debug_assert!(thread_state::get().is_script());
        MutNullableDom {
            ptr: UnsafeCell::new(initial.map(Dom::from_ref)),
        }
    }

    /// Retrieve a copy of the current inner value. If it is `None`, it is
    /// initialized with the result of `cb` first.
    pub fn or_init<F>(&self, cb: F) -> Root<T>
        where F: FnOnce() -> Root<T>
    {
        debug_assert!(thread_state::get().is_script());
        match self.get() {
            Some(inner) => inner,
            None => {
                let inner = cb();
                self.set(Some(&inner));
                inner
            },
        }
    }

    /// Retrieve a copy of the inner optional `Dom<T>` as `LayoutDom<T>`.
    /// For use by layout, which can't use safe types like Temporary.
    #[allow(unrooted_must_root)]
    pub unsafe fn get_inner_as_layout(&self) -> Option<LayoutDom<T>> {
        debug_assert!(thread_state::get().is_layout());
        ptr::read(self.ptr.get()).map(|js| js.to_layout())
    }

    /// Get a rooted value out of this object
    #[allow(unrooted_must_root)]
    pub fn get(&self) -> Option<Root<T>> {
        debug_assert!(thread_state::get().is_script());
        unsafe {
            ptr::read(self.ptr.get()).map(|o| Root::from_ref(&*o))
        }
    }

    /// Set this `MutNullableDom` to the given value.
    pub fn set(&self, val: Option<&T>) {
        debug_assert!(thread_state::get().is_script());
        unsafe {
            *self.ptr.get() = val.map(|p| Dom::from_ref(p));
        }
    }

    /// Gets the current value out of this object and sets it to `None`.
    pub fn take(&self) -> Option<Root<T>> {
        let value = self.get();
        self.set(None);
        value
    }
}

impl<T: DomObject> PartialEq for MutNullableDom<T> {
    fn eq(&self, other: &Self) -> bool {
        unsafe {
            *self.ptr.get() == *other.ptr.get()
        }
    }
}

impl<'a, T: DomObject> PartialEq<Option<&'a T>> for MutNullableDom<T> {
    fn eq(&self, other: &Option<&T>) -> bool {
        unsafe {
            *self.ptr.get() == other.map(Dom::from_ref)
        }
    }
}

impl<T: DomObject> Default for MutNullableDom<T> {
    #[allow(unrooted_must_root)]
    fn default() -> MutNullableDom<T> {
        debug_assert!(thread_state::get().is_script());
        MutNullableDom {
            ptr: UnsafeCell::new(None),
        }
    }
}

impl<T: DomObject> HeapSizeOf for MutNullableDom<T> {
    fn heap_size_of_children(&self) -> usize {
        // See comment on HeapSizeOf for Dom<T>.
        0
    }
}

/// A holder that allows to lazily initialize the value only once
/// `Dom<T>`, using OnceCell
/// Essentially a `OnceCell<Dom<T>>`.
///
/// This should only be used as a field in other DOM objects; see warning
/// on `Dom<T>`.
#[must_root]
pub struct DomOnceCell<T: DomObject> {
    ptr: OnceCell<Dom<T>>,
}

impl<T: DomObject> DomOnceCell<T> {
    /// Retrieve a copy of the current inner value. If it is `None`, it is
    /// initialized with the result of `cb` first.
    #[allow(unrooted_must_root)]
    pub fn init_once<F>(&self, cb: F) -> &T
        where F: FnOnce() -> Root<T>
    {
        debug_assert!(thread_state::get().is_script());
        &self.ptr.init_once(|| Dom::from_ref(&cb()))
    }
}

impl<T: DomObject> Default for DomOnceCell<T> {
    #[allow(unrooted_must_root)]
    fn default() -> DomOnceCell<T> {
        debug_assert!(thread_state::get().is_script());
        DomOnceCell {
            ptr: OnceCell::new(),
        }
    }
}

impl<T: DomObject> HeapSizeOf for DomOnceCell<T> {
    fn heap_size_of_children(&self) -> usize {
        // See comment on HeapSizeOf for Dom<T>.
        0
    }
}

#[allow(unrooted_must_root)]
unsafe impl<T: DomObject> JSTraceable for DomOnceCell<T> {
    unsafe fn trace(&self, trc: *mut JSTracer) {
        if let Some(ptr) = self.ptr.as_ref() {
            ptr.trace(trc);
        }
    }
}

impl<T: DomObject> LayoutDom<T> {
    /// Returns an unsafe pointer to the interior of this JS object. This is
    /// the only method that be safely accessed from layout. (The fact that
    /// this is unsafe is what necessitates the layout wrappers.)
    pub unsafe fn unsafe_get(&self) -> *const T {
        debug_assert!(thread_state::get().is_layout());
        self.ptr.get()
    }

    /// Returns a reference to the interior of this JS object. This method is
    /// safe to call because it originates from the layout thread, and it cannot
    /// mutate DOM nodes.
    pub fn get_for_script(&self) -> &T {
        debug_assert!(thread_state::get().is_script());
        unsafe { &*self.ptr.get() }
    }
}

/// Get a reference out of a rooted value.
pub trait RootedReference<'root> {
    /// The type of the reference.
    type Ref: 'root;
    /// Obtain a reference out of the rooted value.
    fn r(&'root self) -> Self::Ref;
}

impl<'root, T: JSTraceable + DomObject + 'root> RootedReference<'root> for [Dom<T>] {
    type Ref = &'root [&'root T];
    fn r(&'root self) -> &'root [&'root T] {
        unsafe { mem::transmute(self) }
    }
}

impl<'root, T: DomObject + 'root> RootedReference<'root> for Rc<T> {
    type Ref = &'root T;
    fn r(&'root self) -> &'root T {
        self
    }
}

impl<'root, T: RootedReference<'root> + 'root> RootedReference<'root> for Option<T> {
    type Ref = Option<T::Ref>;
    fn r(&'root self) -> Option<T::Ref> {
        self.as_ref().map(RootedReference::r)
    }
}

/// A rooting mechanism for reflectors on the stack.
/// LIFO is not required.
///
/// See also [*Exact Stack Rooting - Storing a GCPointer on the CStack*]
/// (https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals/GC/Exact_Stack_Rooting).
pub struct RootCollection {
    roots: UnsafeCell<Vec<*const Reflector>>,
}

/// A pointer to a RootCollection, for use in global variables.
pub struct RootCollectionPtr(pub *const RootCollection);

impl Copy for RootCollectionPtr {}
impl Clone for RootCollectionPtr {
    fn clone(&self) -> RootCollectionPtr {
        *self
    }
}

impl RootCollection {
    /// Create an empty collection of roots
    pub fn new() -> RootCollection {
        debug_assert!(thread_state::get().is_script());
        RootCollection {
            roots: UnsafeCell::new(vec![]),
        }
    }

    /// Start tracking a stack-based root
    unsafe fn root(&self, untracked_reflector: *const Reflector) {
        debug_assert!(thread_state::get().is_script());
        let roots = &mut *self.roots.get();
        roots.push(untracked_reflector);
        assert!(!(*untracked_reflector).get_jsobject().is_null())
    }

    /// Stop tracking a stack-based reflector, asserting if it isn't found.
    unsafe fn unroot(&self, tracked_reflector: *const Reflector) {
        assert!(!tracked_reflector.is_null());
        assert!(!(*tracked_reflector).get_jsobject().is_null());
        debug_assert!(thread_state::get().is_script());
        let roots = &mut *self.roots.get();
        match roots.iter().rposition(|r| *r == tracked_reflector) {
            Some(idx) => {
                roots.remove(idx);
            },
            None => panic!("Can't remove a root that was never rooted!"),
        }
    }
}

/// SM Callback that traces the rooted reflectors
pub unsafe fn trace_roots(tracer: *mut JSTracer) {
    debug!("tracing stack roots");
    STACK_ROOTS.with(|ref collection| {
        let RootCollectionPtr(collection) = collection.get().unwrap();
        let collection = &*(*collection).roots.get();
        for root in collection {
            trace_reflector(tracer, "on stack", &**root);
        }
    });
}

/// A rooted reference to a DOM object.
///
/// The JS value is pinned for the duration of this object's lifetime; roots
/// are additive, so this object's destruction will not invalidate other roots
/// for the same JS value. `Root`s cannot outlive the associated
/// `RootCollection` object.
#[allow_unrooted_interior]
pub struct Root<T: DomObject> {
    /// Reference to rooted value that must not outlive this container
    ptr: NonZero<*const T>,
    /// List that ensures correct dynamic root ordering
    root_list: *const RootCollection,
}

impl<T: Castable> Root<T> {
    /// Cast a DOM object root upwards to one of the interfaces it derives from.
    pub fn upcast<U>(root: Root<T>) -> Root<U>
        where U: Castable,
              T: DerivedFrom<U>
    {
        unsafe { mem::transmute(root) }
    }

    /// Cast a DOM object root downwards to one of the interfaces it might implement.
    pub fn downcast<U>(root: Root<T>) -> Option<Root<U>>
        where U: DerivedFrom<T>
    {
        if root.is::<U>() {
            Some(unsafe { mem::transmute(root) })
        } else {
            None
        }
    }
}

impl<T: DomObject> Root<T> {
    /// Create a new stack-bounded root for the provided JS-owned value.
    /// It cannot outlive its associated `RootCollection`, and it gives
    /// out references which cannot outlive this new `Root`.
    pub fn new(unrooted: NonZero<*const T>) -> Root<T> {
        debug_assert!(thread_state::get().is_script());
        STACK_ROOTS.with(|ref collection| {
            let RootCollectionPtr(collection) = collection.get().unwrap();
            unsafe { (*collection).root(&*(*unrooted.get()).reflector()) }
            Root {
                ptr: unrooted,
                root_list: collection,
            }
        })
    }

    /// Generate a new root from a reference
    pub fn from_ref(unrooted: &T) -> Root<T> {
        Root::new(unsafe { NonZero::new_unchecked(unrooted) })
    }
}

impl<'root, T: DomObject + 'root> RootedReference<'root> for Root<T> {
    type Ref = &'root T;
    fn r(&'root self) -> &'root T {
        self
    }
}

impl<T: DomObject> Deref for Root<T> {
    type Target = T;
    fn deref(&self) -> &T {
        debug_assert!(thread_state::get().is_script());
        unsafe { &*self.ptr.get() }
    }
}

impl<T: DomObject + HeapSizeOf> HeapSizeOf for Root<T> {
    fn heap_size_of_children(&self) -> usize {
        (**self).heap_size_of_children()
    }
}

impl<T: DomObject> PartialEq for Root<T> {
    fn eq(&self, other: &Self) -> bool {
        self.ptr == other.ptr
    }
}

impl<T: DomObject> Clone for Root<T> {
    fn clone(&self) -> Root<T> {
        Root::from_ref(&*self)
    }
}

impl<T: DomObject> Drop for Root<T> {
    fn drop(&mut self) {
        unsafe {
            (*self.root_list).unroot(self.reflector());
        }
    }
}

unsafe impl<T: DomObject> JSTraceable for Root<T> {
    unsafe fn trace(&self, _: *mut JSTracer) {
        // Already traced.
    }
}

/// Helper trait for safer manipulations of Option<Heap<T>> values.
pub trait OptionalHeapSetter {
    type Value;
    /// Update this optional heap value with a new value.
    fn set(&mut self, v: Option<Self::Value>);
}

impl<T: GCMethods + Copy> OptionalHeapSetter for Option<Heap<T>> where Heap<T>: Default {
    type Value = T;
    fn set(&mut self, v: Option<T>) {
        let v = match v {
            None => {
                *self = None;
                return;
            }
            Some(v) => v,
        };

        if self.is_none() {
            *self = Some(Heap::default());
        }

        self.as_ref().unwrap().set(v);
    }
}