Skip to main content

script_bindings/
record.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
5//! The `Record` (open-ended dictionary) type.
6
7use std::cmp::Eq;
8use std::hash::Hash;
9use std::marker::Sized;
10use std::ops::{Deref, DerefMut};
11
12use indexmap::IndexMap;
13use js::context::{JSContext, RawJSContext};
14use js::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible};
15use js::jsapi::{
16    JSITER_HIDDEN, JSITER_OWNONLY, JSITER_SYMBOLS, JSPROP_ENUMERATE, PropertyDescriptor,
17};
18use js::jsval::{ObjectValue, UndefinedValue};
19use js::rust::wrappers2::{
20    GetPropertyKeys, JS_DefineUCProperty2, JS_GetOwnPropertyDescriptorById, JS_GetPropertyById,
21    JS_IdToValue, JS_NewPlainObject,
22};
23use js::rust::{HandleId, HandleValue, IdVector, MutableHandleValue};
24
25use crate::conversions::jsid_to_string;
26use crate::str::{ByteString, DOMString, USVString};
27
28pub trait RecordKey: Eq + Hash + Sized {
29    fn to_utf16_vec(&self) -> Vec<u16>;
30
31    /// Attempt to extract a key from a JS id.
32    #[allow(clippy::result_unit_err)]
33    fn from_id(cx: &mut JSContext, id: HandleId) -> Result<ConversionResult<Self>, ()>;
34}
35
36impl RecordKey for DOMString {
37    fn to_utf16_vec(&self) -> Vec<u16> {
38        self.str().encode_utf16().collect::<Vec<_>>()
39    }
40
41    fn from_id(cx: &mut JSContext, id: HandleId) -> Result<ConversionResult<Self>, ()> {
42        match jsid_to_string(cx, id) {
43            Some(s) => Ok(ConversionResult::Success(s)),
44            None => Ok(ConversionResult::Failure(c"Failed to get DOMString".into())),
45        }
46    }
47}
48
49impl RecordKey for USVString {
50    fn to_utf16_vec(&self) -> Vec<u16> {
51        self.0.encode_utf16().collect::<Vec<_>>()
52    }
53
54    fn from_id(cx: &mut JSContext, id: HandleId) -> Result<ConversionResult<Self>, ()> {
55        rooted!(&in(cx) let mut jsid_value = UndefinedValue());
56        unsafe { JS_IdToValue(cx, *id.as_ref(cx), jsid_value.handle_mut()) };
57
58        USVString::safe_from_jsval(cx, jsid_value.handle(), ())
59    }
60}
61
62impl RecordKey for ByteString {
63    fn to_utf16_vec(&self) -> Vec<u16> {
64        self.iter().map(|&x| x as u16).collect::<Vec<u16>>()
65    }
66
67    fn from_id(cx: &mut JSContext, id: HandleId) -> Result<ConversionResult<Self>, ()> {
68        rooted!(&in(cx) let mut jsid_value = UndefinedValue());
69        unsafe { JS_IdToValue(cx, *id.as_ref(cx), jsid_value.handle_mut()) };
70
71        ByteString::safe_from_jsval(cx, jsid_value.handle(), ())
72    }
73}
74
75/// The `Record` (open-ended dictionary) type.
76#[derive(Clone, JSTraceable)]
77pub struct Record<K: RecordKey, V> {
78    #[custom_trace]
79    map: IndexMap<K, V>,
80}
81
82impl<K: RecordKey, V> Record<K, V> {
83    /// Create an empty `Record`.
84    pub fn new() -> Self {
85        Record {
86            map: IndexMap::new(),
87        }
88    }
89}
90
91impl<K: RecordKey, V> Deref for Record<K, V> {
92    type Target = IndexMap<K, V>;
93
94    fn deref(&self) -> &Self::Target {
95        &self.map
96    }
97}
98
99impl<K: RecordKey, V> DerefMut for Record<K, V> {
100    fn deref_mut(&mut self) -> &mut Self::Target {
101        &mut self.map
102    }
103}
104
105impl<K, V, C> FromJSValConvertible for Record<K, V>
106where
107    K: RecordKey,
108    V: FromJSValConvertible<Config = C>,
109    C: Clone,
110{
111    type Config = C;
112
113    fn safe_from_jsval(
114        cx: &mut JSContext,
115        value: HandleValue,
116        config: C,
117    ) -> Result<ConversionResult<Self>, ()> {
118        if !value.is_object() {
119            return Ok(ConversionResult::Failure(
120                c"Record value was not an object".into(),
121            ));
122        }
123
124        rooted!(&in(cx) let object = value.to_object());
125        let mut ids = unsafe { IdVector::new(cx.raw_cx()) };
126        if unsafe {
127            !GetPropertyKeys(
128                cx,
129                object.handle(),
130                JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS,
131                ids.handle_mut(),
132            )
133        } {
134            return Err(());
135        }
136
137        let mut map = IndexMap::new();
138        for id in &*ids {
139            rooted!(&in(cx) let id = *id);
140            rooted!(&in(cx) let mut desc = PropertyDescriptor::default());
141
142            let mut is_none = false;
143            if unsafe {
144                !JS_GetOwnPropertyDescriptorById(
145                    cx,
146                    object.handle(),
147                    id.handle(),
148                    desc.handle_mut(),
149                    &mut is_none,
150                )
151            } {
152                return Err(());
153            }
154
155            if !desc.enumerable_() {
156                continue;
157            }
158
159            let key = match K::from_id(cx, id.handle())? {
160                ConversionResult::Success(key) => key,
161                ConversionResult::Failure(message) => {
162                    return Ok(ConversionResult::Failure(message));
163                },
164            };
165
166            rooted!(&in(cx) let mut property = UndefinedValue());
167            if unsafe {
168                !JS_GetPropertyById(cx, object.handle(), id.handle(), property.handle_mut())
169            } {
170                return Err(());
171            }
172
173            let property = match V::safe_from_jsval(cx, property.handle(), config.clone())? {
174                ConversionResult::Success(property) => property,
175                ConversionResult::Failure(message) => {
176                    return Ok(ConversionResult::Failure(message));
177                },
178            };
179            map.insert(key, property);
180        }
181
182        Ok(ConversionResult::Success(Record { map }))
183    }
184}
185
186impl<K, V> ToJSValConvertible for Record<K, V>
187where
188    K: RecordKey,
189    V: ToJSValConvertible,
190{
191    #[inline]
192    unsafe fn to_jsval(&self, _cx: *mut RawJSContext, rval: MutableHandleValue) {
193        // TODO: https://github.com/servo/mozjs/issues/764
194        // This is needed until the `RawJSContext` version is removed from the trait.
195        let mut cx = unsafe { crate::script_runtime::temp_cx() };
196        ToJSValConvertible::safe_to_jsval(self, &mut cx, rval);
197    }
198
199    fn safe_to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
200        rooted!(&in(cx) let js_object = unsafe { JS_NewPlainObject(cx) });
201        assert!(!js_object.handle().is_null());
202
203        rooted!(&in(cx) let mut js_value = UndefinedValue());
204        for (key, value) in &self.map {
205            let key = key.to_utf16_vec();
206            value.safe_to_jsval(cx, js_value.handle_mut());
207
208            assert!(unsafe {
209                JS_DefineUCProperty2(
210                    cx,
211                    js_object.handle(),
212                    key.as_ptr(),
213                    key.len(),
214                    js_value.handle(),
215                    JSPROP_ENUMERATE as u32,
216                )
217            });
218        }
219
220        rval.set(ObjectValue(js_object.handle().get()));
221    }
222}
223
224impl<K: RecordKey, V> Default for Record<K, V> {
225    fn default() -> Self {
226        Self::new()
227    }
228}