script/dom/
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::rust::HandleObject;
9
10use crate::dom::bindings::cell::DomRefCell;
11use crate::dom::bindings::codegen::Bindings::TestBindingPairIterableBinding::TestBindingPairIterableMethods;
12use crate::dom::bindings::error::Fallible;
13use crate::dom::bindings::iterable::Iterable;
14use crate::dom::bindings::reflector::{Reflector, reflect_dom_object_with_proto};
15use crate::dom::bindings::root::DomRoot;
16use crate::dom::bindings::str::DOMString;
17use crate::dom::globalscope::GlobalScope;
18use crate::script_runtime::CanGc;
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    fn get_iterable_length(&self) -> u32 {
30        self.map.borrow().len() as u32
31    }
32    fn get_value_at_index(&self, index: u32) -> u32 {
33        *self.map.borrow().get(index as usize).map(|a| &a.1).unwrap()
34    }
35    fn get_key_at_index(&self, index: u32) -> DOMString {
36        self.map
37            .borrow()
38            .get(index as usize)
39            .map(|a| &a.0)
40            .unwrap()
41            .clone()
42    }
43}
44
45impl TestBindingPairIterable {
46    fn new(
47        global: &GlobalScope,
48        proto: Option<HandleObject>,
49        can_gc: CanGc,
50    ) -> DomRoot<TestBindingPairIterable> {
51        reflect_dom_object_with_proto(
52            Box::new(TestBindingPairIterable {
53                reflector: Reflector::new(),
54                map: DomRefCell::new(vec![]),
55            }),
56            global,
57            proto,
58            can_gc,
59        )
60    }
61}
62
63impl TestBindingPairIterableMethods<crate::DomTypeHolder> for TestBindingPairIterable {
64    fn Constructor(
65        global: &GlobalScope,
66        proto: Option<HandleObject>,
67        can_gc: CanGc,
68    ) -> Fallible<DomRoot<TestBindingPairIterable>> {
69        Ok(TestBindingPairIterable::new(global, proto, can_gc))
70    }
71
72    fn Add(&self, key: DOMString, value: u32) {
73        self.map.borrow_mut().push((key, value));
74    }
75}