Skip to main content

script/dom/
domstringlist.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
5use dom_struct::dom_struct;
6use itertools::Itertools;
7use js::context::JSContext;
8use script_bindings::reflector::{Reflector, reflect_dom_object_with_cx};
9
10use crate::dom::bindings::codegen::Bindings::DOMStringListBinding::DOMStringListMethods;
11use crate::dom::bindings::root::DomRoot;
12use crate::dom::bindings::str::DOMString;
13use crate::dom::globalscope::GlobalScope;
14
15#[dom_struct]
16pub(crate) struct DOMStringList {
17    reflector_: Reflector,
18    strings: Vec<DOMString>,
19}
20
21impl DOMStringList {
22    pub(crate) fn new_inherited(strings: Vec<DOMString>) -> DOMStringList {
23        DOMStringList {
24            reflector_: Reflector::new(),
25            strings,
26        }
27    }
28
29    pub(crate) fn new(
30        cx: &mut JSContext,
31        global: &GlobalScope,
32        strings: Vec<DOMString>,
33    ) -> DomRoot<DOMStringList> {
34        reflect_dom_object_with_cx(Box::new(DOMStringList::new_inherited(strings)), global, cx)
35    }
36
37    /// <https://www.w3.org/TR/IndexedDB-3/#sorted-name-list>
38    pub(crate) fn new_sorted<'a>(
39        cx: &mut JSContext,
40        global: &GlobalScope,
41        strings: impl IntoIterator<Item = &'a DOMString>,
42    ) -> DomRoot<DOMStringList> {
43        let sorted = strings
44            .into_iter()
45            .map(|dom_string| dom_string.str().encode_utf16().collect::<Vec<u16>>())
46            .sorted_unstable()
47            .map(|utf16_str| {
48                String::from_utf16(utf16_str.as_slice())
49                    .expect("can't convert object store name from utf16 back to utf8")
50                    .into()
51            })
52            .collect();
53        Self::new(cx, global, sorted)
54    }
55}
56
57// https://html.spec.whatwg.org/multipage/#domstringlist
58impl DOMStringListMethods<crate::DomTypeHolder> for DOMStringList {
59    /// <https://html.spec.whatwg.org/multipage/#dom-domstringlist-length>
60    fn Length(&self) -> u32 {
61        self.strings.len() as u32
62    }
63
64    /// <https://html.spec.whatwg.org/multipage/#dom-domstringlist-item>
65    fn Item(&self, index: u32) -> Option<DOMString> {
66        self.strings.get(index as usize).cloned()
67    }
68
69    /// <https://html.spec.whatwg.org/multipage/#dom-domstringlist-contains>
70    fn Contains(&self, string: DOMString) -> bool {
71        self.strings.contains(&string)
72    }
73
74    // check-tidy: no specs after this line
75    fn IndexedGetter(&self, index: u32) -> Option<DOMString> {
76        self.Item(index)
77    }
78}