1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsMethods;
use crate::dom::bindings::codegen::UnionTypes::USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString;
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::iterable::Iterable;
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::bindings::weakref::MutableWeakRef;
use crate::dom::globalscope::GlobalScope;
use crate::dom::url::URL;
use dom_struct::dom_struct;
use url::form_urlencoded;

// https://url.spec.whatwg.org/#interface-urlsearchparams
#[dom_struct]
pub struct URLSearchParams {
    reflector_: Reflector,
    // https://url.spec.whatwg.org/#concept-urlsearchparams-list
    list: DomRefCell<Vec<(String, String)>>,
    // https://url.spec.whatwg.org/#concept-urlsearchparams-url-object
    url: MutableWeakRef<URL>,
}

impl URLSearchParams {
    fn new_inherited(url: Option<&URL>) -> URLSearchParams {
        URLSearchParams {
            reflector_: Reflector::new(),
            list: DomRefCell::new(url.map_or(Vec::new(), |url| url.query_pairs())),
            url: MutableWeakRef::new(url),
        }
    }

    pub fn new(global: &GlobalScope, url: Option<&URL>) -> DomRoot<URLSearchParams> {
        reflect_dom_object(Box::new(URLSearchParams::new_inherited(url)), global)
    }

    // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
    #[allow(non_snake_case)]
    pub fn Constructor(
        global: &GlobalScope,
        init: USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString,
    ) -> Fallible<DomRoot<URLSearchParams>> {
        // Step 1.
        let query = URLSearchParams::new(global, None);
        match init {
            USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVStringSequenceSequence(init) => {
                // Step 2.

                // Step 2-1.
                if init.iter().any(|pair| pair.len() != 2) {
                    return Err(Error::Type("Sequence initializer must only contain pair elements.".to_string()));
                }

                // Step 2-2.
                *query.list.borrow_mut() =
                    init.iter().map(|pair| (pair[0].to_string(), pair[1].to_string())).collect::<Vec<_>>();
            },
            USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVStringUSVStringRecord(init) => {
                // Step 3.
                *query.list.borrow_mut() =
                    (*init).iter().map(|(name, value)| (name.to_string(), value.to_string())).collect::<Vec<_>>();
            },
            USVStringSequenceSequenceOrUSVStringUSVStringRecordOrUSVString::USVString(init) => {
                // Step 4.
                let init_bytes = match init.0.chars().next() {
                    Some(first_char) if first_char == '?' => {
                        let (_, other_bytes) = init.0.as_bytes().split_at(1);

                        other_bytes
                    },
                    _ => init.0.as_bytes(),
                };

                *query.list.borrow_mut() =
                    form_urlencoded::parse(init_bytes).into_owned().collect();
            }
        }

        // Step 5.
        Ok(query)
    }

    pub fn set_list(&self, list: Vec<(String, String)>) {
        *self.list.borrow_mut() = list;
    }
}

impl URLSearchParamsMethods for URLSearchParams {
    // https://url.spec.whatwg.org/#dom-urlsearchparams-append
    fn Append(&self, name: USVString, value: USVString) {
        // Step 1.
        self.list.borrow_mut().push((name.0, value.0));
        // Step 2.
        self.update_steps();
    }

    // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
    fn Delete(&self, name: USVString) {
        // Step 1.
        self.list.borrow_mut().retain(|&(ref k, _)| k != &name.0);
        // Step 2.
        self.update_steps();
    }

    // https://url.spec.whatwg.org/#dom-urlsearchparams-get
    fn Get(&self, name: USVString) -> Option<USVString> {
        let list = self.list.borrow();
        list.iter()
            .find(|&kv| kv.0 == name.0)
            .map(|ref kv| USVString(kv.1.clone()))
    }

    // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
    fn GetAll(&self, name: USVString) -> Vec<USVString> {
        let list = self.list.borrow();
        list.iter()
            .filter_map(|&(ref k, ref v)| {
                if k == &name.0 {
                    Some(USVString(v.clone()))
                } else {
                    None
                }
            })
            .collect()
    }

    // https://url.spec.whatwg.org/#dom-urlsearchparams-has
    fn Has(&self, name: USVString) -> bool {
        let list = self.list.borrow();
        list.iter().any(|&(ref k, _)| k == &name.0)
    }

    // https://url.spec.whatwg.org/#dom-urlsearchparams-set
    fn Set(&self, name: USVString, value: USVString) {
        {
            // Step 1.
            let mut list = self.list.borrow_mut();
            let mut index = None;
            let mut i = 0;
            list.retain(|&(ref k, _)| {
                if index.is_none() {
                    if k == &name.0 {
                        index = Some(i);
                    } else {
                        i += 1;
                    }
                    true
                } else {
                    k != &name.0
                }
            });
            match index {
                Some(index) => list[index].1 = value.0,
                None => list.push((name.0, value.0)), // Step 2.
            };
        } // Un-borrow self.list
          // Step 3.
        self.update_steps();
    }

    // https://url.spec.whatwg.org/#dom-urlsearchparams-sort
    fn Sort(&self) {
        // Step 1.
        self.list
            .borrow_mut()
            .sort_by(|(a, _), (b, _)| a.encode_utf16().cmp(b.encode_utf16()));

        // Step 2.
        self.update_steps();
    }

    // https://url.spec.whatwg.org/#stringification-behavior
    fn Stringifier(&self) -> DOMString {
        DOMString::from(self.serialize_utf8())
    }
}

impl URLSearchParams {
    // https://url.spec.whatwg.org/#concept-urlencoded-serializer
    pub fn serialize_utf8(&self) -> String {
        let list = self.list.borrow();
        form_urlencoded::Serializer::new(String::new())
            .extend_pairs(&*list)
            .finish()
    }

    // https://url.spec.whatwg.org/#concept-urlsearchparams-update
    fn update_steps(&self) {
        if let Some(url) = self.url.root() {
            url.set_query_pairs(&self.list.borrow())
        }
    }
}

impl Iterable for URLSearchParams {
    type Key = USVString;
    type Value = USVString;

    fn get_iterable_length(&self) -> u32 {
        self.list.borrow().len() as u32
    }

    fn get_value_at_index(&self, n: u32) -> USVString {
        let value = self.list.borrow()[n as usize].1.clone();
        USVString(value)
    }

    fn get_key_at_index(&self, n: u32) -> USVString {
        let key = self.list.borrow()[n as usize].0.clone();
        USVString(key)
    }
}