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
use std::any::TypeId;

use boa_macros::{Finalize, Trace};
use hashbrown::hash_map::HashMap;

use crate::object::NativeObject;

/// This represents a `ECMASCript` specification \[`HostDefined`\] field.
///
/// This allows storing types which are mapped by their [`TypeId`].
#[derive(Default, Trace, Finalize)]
#[allow(missing_debug_implementations)]
pub struct HostDefined {
    // INVARIANT: All key-value pairs `(id, obj)` satisfy:
    //  `id == TypeId::of::<T>() && obj.is::<T>()`
    // for some type `T : NativeObject`.
    types: HashMap<TypeId, Box<dyn NativeObject>>,
}

// TODO: Track https://github.com/rust-lang/rust/issues/65991 and
// https://github.com/rust-lang/rust/issues/90850 to remove this
// when those are stabilized.
fn downcast_boxed_native_object_unchecked<T: NativeObject>(obj: Box<dyn NativeObject>) -> Box<T> {
    let raw: *mut dyn NativeObject = Box::into_raw(obj);

    // SAFETY: We know that `obj` is of type `T` (due to the INVARIANT of `HostDefined`).
    // See `HostDefined::insert`, `HostDefined::insert_default` and `HostDefined::remove`.
    unsafe { Box::from_raw(raw.cast::<T>()) }
}

impl HostDefined {
    /// Insert a type into the [`HostDefined`].
    #[track_caller]
    pub fn insert_default<T: NativeObject + Default>(&mut self) -> Option<Box<T>> {
        self.types
            .insert(TypeId::of::<T>(), Box::<T>::default())
            .map(downcast_boxed_native_object_unchecked)
    }

    /// Insert a type into the [`HostDefined`].
    #[track_caller]
    pub fn insert<T: NativeObject>(&mut self, value: T) -> Option<Box<T>> {
        self.types
            .insert(TypeId::of::<T>(), Box::new(value))
            .map(downcast_boxed_native_object_unchecked)
    }

    /// Check if the [`HostDefined`] has type T.
    #[must_use]
    #[track_caller]
    pub fn has<T: NativeObject>(&self) -> bool {
        self.types.contains_key(&TypeId::of::<T>())
    }

    /// Remove type T from [`HostDefined`], if it exists.
    ///
    /// Returns [`Some`] with the object if it exits, [`None`] otherwise.
    #[track_caller]
    pub fn remove<T: NativeObject>(&mut self) -> Option<Box<T>> {
        self.types
            .remove(&TypeId::of::<T>())
            .map(downcast_boxed_native_object_unchecked)
    }

    /// Get type T from [`HostDefined`], if it exists.
    #[track_caller]
    pub fn get<T: NativeObject>(&self) -> Option<&T> {
        self.types
            .get(&TypeId::of::<T>())
            .map(Box::as_ref)
            .and_then(<dyn NativeObject>::downcast_ref::<T>)
    }

    /// Get type T from [`HostDefined`], if it exists.
    #[track_caller]
    pub fn get_mut<T: NativeObject>(&mut self) -> Option<&mut T> {
        self.types
            .get_mut(&TypeId::of::<T>())
            .map(Box::as_mut)
            .and_then(<dyn NativeObject>::downcast_mut::<T>)
    }

    /// Get type a tuple of types from [`HostDefined`], if they exist.
    #[track_caller]
    pub fn get_many_mut<T, const SIZE: usize>(&mut self) -> Option<T::NativeTupleMutRef<'_>>
    where
        T: NativeTuple<SIZE>,
    {
        let ids = T::as_type_ids();
        let refs: [&TypeId; SIZE] = std::array::from_fn(|i| &ids[i]);

        self.types.get_many_mut(refs).and_then(T::mut_ref_from_anys)
    }

    /// Clears all the objects.
    #[track_caller]
    pub fn clear(&mut self) {
        self.types.clear();
    }
}

/// This trait represents a tuple of [`NativeObject`]s capable of being
/// used in [`HostDefined`].
///
/// This allows accessing multiple types from [`HostDefined`] at once.
pub trait NativeTuple<const SIZE: usize> {
    type NativeTupleMutRef<'a>;

    fn as_type_ids() -> [TypeId; SIZE];

    fn mut_ref_from_anys(
        anys: [&'_ mut Box<dyn NativeObject>; SIZE],
    ) -> Option<Self::NativeTupleMutRef<'_>>;
}

macro_rules! impl_native_tuple {
    ($size:literal $(,$name:ident)* ) => {
        impl<$($name: NativeObject,)*> NativeTuple<$size> for ($($name,)*) {
            type NativeTupleMutRef<'a> = ($(&'a mut $name,)*);

            fn as_type_ids() -> [TypeId; $size] {
                [$(TypeId::of::<$name>(),)*]
            }

            fn mut_ref_from_anys(
                anys: [&'_ mut Box<dyn NativeObject>; $size],
            ) -> Option<Self::NativeTupleMutRef<'_>> {
                #[allow(unused_variables, unused_mut)]
                let mut anys = anys.into_iter();
                Some(($(
                    anys.next().expect("Expect `anys` to be of length `SIZE`").downcast_mut::<$name>()?,
                )*))
            }
        }
    }
}

impl_native_tuple!(0);
impl_native_tuple!(1, A);
impl_native_tuple!(2, A, B);
impl_native_tuple!(3, A, B, C);
impl_native_tuple!(4, A, B, C, D);
impl_native_tuple!(5, A, B, C, D, E);
impl_native_tuple!(6, A, B, C, D, E, F);
impl_native_tuple!(7, A, B, C, D, E, F, G);
impl_native_tuple!(8, A, B, C, D, E, F, G, H);
impl_native_tuple!(9, A, B, C, D, E, F, G, H, I);
impl_native_tuple!(10, A, B, C, D, E, F, G, H, I, J);
impl_native_tuple!(11, A, B, C, D, E, F, G, H, I, J, K);
impl_native_tuple!(12, A, B, C, D, E, F, G, H, I, J, K, L);