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;
7
8use crate::dom::bindings::codegen::Bindings::DOMStringListBinding::DOMStringListMethods;
9use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
10use crate::dom::bindings::root::DomRoot;
11use crate::dom::bindings::str::DOMString;
12use crate::dom::globalscope::GlobalScope;
13use crate::script_runtime::CanGc;
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        global: &GlobalScope,
31        strings: Vec<DOMString>,
32        can_gc: CanGc,
33    ) -> DomRoot<DOMStringList> {
34        reflect_dom_object(
35            Box::new(DOMStringList::new_inherited(strings)),
36            global,
37            can_gc,
38        )
39    }
40
41    /// <https://www.w3.org/TR/IndexedDB-2/#sorted-name-list>
42    pub(crate) fn new_sorted<'a>(
43        global: &GlobalScope,
44        strings: impl IntoIterator<Item = &'a DOMString>,
45        can_gc: CanGc,
46    ) -> DomRoot<DOMStringList> {
47        let sorted = strings
48            .into_iter()
49            .map(|dom_string| dom_string.str().encode_utf16().collect::<Vec<u16>>())
50            .sorted_unstable()
51            .map(|utf16_str| {
52                DOMString::from_string(
53                    String::from_utf16(utf16_str.as_slice())
54                        .expect("can't convert object store name from utf16 back to utf8"),
55                )
56            })
57            .collect();
58        Self::new(global, sorted, can_gc)
59    }
60}
61
62// https://html.spec.whatwg.org/multipage/#domstringlist
63impl DOMStringListMethods<crate::DomTypeHolder> for DOMStringList {
64    /// <https://html.spec.whatwg.org/multipage/#dom-domstringlist-length>
65    fn Length(&self) -> u32 {
66        self.strings.len() as u32
67    }
68
69    /// <https://html.spec.whatwg.org/multipage/#dom-domstringlist-item>
70    fn Item(&self, index: u32) -> Option<DOMString> {
71        self.strings.get(index as usize).cloned()
72    }
73
74    /// <https://html.spec.whatwg.org/multipage/#dom-domstringlist-contains>
75    fn Contains(&self, string: DOMString) -> bool {
76        self.strings.contains(&string)
77    }
78
79    // check-tidy: no specs after this line
80    fn IndexedGetter(&self, index: u32) -> Option<DOMString> {
81        self.Item(index)
82    }
83}