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