Skip to main content

script/dom/testing/
testbindingpairiterable.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// check-tidy: no specs after this line
6
7use dom_struct::dom_struct;
8use js::context::JSContext;
9use js::rust::HandleObject;
10use script_bindings::cell::DomRefCell;
11use script_bindings::reflector::{Reflector, reflect_dom_object_with_proto};
12
13use crate::dom::bindings::codegen::Bindings::TestBindingPairIterableBinding::TestBindingPairIterableMethods;
14use crate::dom::bindings::error::Fallible;
15use crate::dom::bindings::iterable::Iterable;
16use crate::dom::bindings::root::DomRoot;
17use crate::dom::bindings::str::DOMString;
18use crate::dom::globalscope::GlobalScope;
19
20#[dom_struct]
21pub(crate) struct TestBindingPairIterable {
22    reflector: Reflector,
23    map: DomRefCell<Vec<(DOMString, u32)>>,
24}
25
26impl Iterable for TestBindingPairIterable {
27    type Key = DOMString;
28    type Value = u32;
29
30    fn get_iterable_length(&self, _cx: &mut JSContext) -> u32 {
31        self.map.borrow().len() as u32
32    }
33    fn get_value_at_index(&self, _cx: &mut JSContext, index: u32) -> u32 {
34        *self.map.borrow().get(index as usize).map(|a| &a.1).unwrap()
35    }
36    fn get_key_at_index(&self, _cx: &mut JSContext, index: u32) -> DOMString {
37        self.map
38            .borrow()
39            .get(index as usize)
40            .map(|a| &a.0)
41            .unwrap()
42            .clone()
43    }
44}
45
46impl TestBindingPairIterable {
47    fn new(
48        cx: &mut JSContext,
49        global: &GlobalScope,
50        proto: Option<HandleObject>,
51    ) -> DomRoot<TestBindingPairIterable> {
52        reflect_dom_object_with_proto(
53            cx,
54            Box::new(TestBindingPairIterable {
55                reflector: Reflector::new(),
56                map: DomRefCell::new(vec![]),
57            }),
58            global,
59            proto,
60        )
61    }
62}
63
64impl TestBindingPairIterableMethods<crate::DomTypeHolder> for TestBindingPairIterable {
65    fn Constructor(
66        cx: &mut JSContext,
67        global: &GlobalScope,
68        proto: Option<HandleObject>,
69    ) -> Fallible<DomRoot<TestBindingPairIterable>> {
70        Ok(TestBindingPairIterable::new(cx, global, proto))
71    }
72
73    fn Add(&self, key: DOMString, value: u32) {
74        self.map.borrow_mut().push((key, value));
75    }
76}