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;
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::{JS_DefineUCProperty2, JS_NewPlainObject};
20use js::rust::{HandleId, HandleValue, IdVector, MutableHandleValue};
21
22use crate::conversions::jsid_to_string;
23use crate::js::{
24    GetPropertyKeys, JS_GetOwnPropertyDescriptorById, JS_GetPropertyById, JS_IdToValue,
25};
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        JS_IdToValue(cx, *id.as_ref(cx), jsid_value.handle_mut());
57
58        USVString::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        JS_IdToValue(cx, *id.as_ref(cx), jsid_value.handle_mut());
70
71        ByteString::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 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 = IdVector::new(cx);
126        if !GetPropertyKeys(
127            cx,
128            object.handle(),
129            JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS,
130            ids.handle_mut(),
131        ) {
132            return Err(());
133        }
134
135        let mut map = IndexMap::new();
136        for id in &*ids {
137            rooted!(&in(cx) let id = *id);
138            rooted!(&in(cx) let mut desc = PropertyDescriptor::default());
139
140            let mut is_none = false;
141            if !JS_GetOwnPropertyDescriptorById(
142                cx,
143                object.handle(),
144                id.handle(),
145                desc.handle_mut(),
146                &mut is_none,
147            ) {
148                return Err(());
149            }
150
151            if !desc.enumerable_() {
152                continue;
153            }
154
155            let key = match K::from_id(cx, id.handle())? {
156                ConversionResult::Success(key) => key,
157                ConversionResult::Failure(message) => {
158                    return Ok(ConversionResult::Failure(message));
159                },
160            };
161
162            rooted!(&in(cx) let mut property = UndefinedValue());
163            if !JS_GetPropertyById(cx, object.handle(), id.handle(), property.handle_mut()) {
164                return Err(());
165            }
166
167            let property = match V::from_jsval(cx, property.handle(), config.clone())? {
168                ConversionResult::Success(property) => property,
169                ConversionResult::Failure(message) => {
170                    return Ok(ConversionResult::Failure(message));
171                },
172            };
173            map.insert(key, property);
174        }
175
176        Ok(ConversionResult::Success(Record { map }))
177    }
178}
179
180impl<K, V> ToJSValConvertible for Record<K, V>
181where
182    K: RecordKey,
183    V: ToJSValConvertible,
184{
185    #[inline]
186    fn to_jsval(&self, cx: &mut JSContext, mut rval: MutableHandleValue) {
187        rooted!(&in(cx) let js_object = unsafe { JS_NewPlainObject(cx) });
188        assert!(!js_object.handle().is_null());
189
190        rooted!(&in(cx) let mut js_value = UndefinedValue());
191        for (key, value) in &self.map {
192            let key = key.to_utf16_vec();
193            value.to_jsval(cx, js_value.handle_mut());
194
195            assert!(unsafe {
196                JS_DefineUCProperty2(
197                    cx,
198                    js_object.handle(),
199                    key.as_ptr(),
200                    key.len(),
201                    js_value.handle(),
202                    JSPROP_ENUMERATE as u32,
203                )
204            });
205        }
206
207        rval.set(ObjectValue(js_object.handle().get()));
208    }
209}
210
211impl<K: RecordKey, V> Default for Record<K, V> {
212    fn default() -> Self {
213        Self::new()
214    }
215}