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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
use crate::{Param, WebUrl};
impl WebUrl {
//! Query Parameter Mutations
/// Adds the query `param`.
///
/// This always appends exactly one parameter & never changes the parameters that are already present. The '?'
/// separator is used when the URL has no query yet, otherwise the '&' separator is used. Since an empty region
/// between separators is an empty parameter, a query that is just a '?' already has one parameter & therefore still
/// needs the '&' separator.
///
/// # Example
/// Adding the param `p=1`:
/// - `"/"` -> `"/?p=1"`
/// - `"/?"` -> `"/?&p=1"`
/// - `"/?a=2"` -> `"/?a=2&p=1"`
/// - `"/?&"` -> `"/?&&p=1"`
///
/// # Panics
/// Panics if the resulting URL would exceed `WebUrl::MAX_LEN`. The URL is left unmodified.
pub fn add_param(&mut self, param: Param) {
// A URL with no query has no '?' either, so the query starts with one here. Every other case appends to a
// query that already has at least one param.
let separator: char = if self.path_end == self.query_end { '?' } else { '&' };
let added: usize = Self::push_param_len(param);
// The length is checked before anything is modified so an over-long URL panics with the URL intact rather than
// leaving the string inconsistent with the component offsets.
Self::check_len(self.url.len() + added);
// The param is assembled first so it can be spliced in with a single insertion. Inserting each piece directly
// would shift everything after the query once per piece.
let mut insert: String = String::with_capacity(added);
Self::push_param(&mut insert, separator, param);
// Only the fragment follows the query, so the insertion shifts the fragment alone.
let at: usize = self.query_end as usize;
self.url.insert_str(at, insert.as_str());
self.query_end = (at + insert.len()) as u32;
debug_assert!(self.is_consistent());
}
/// Adds the query `param`.
///
/// # Panics
/// Panics if the resulting URL would exceed `WebUrl::MAX_LEN`.
pub fn with_param(mut self, param: Param) -> Self {
self.add_param(param);
self
}
/// Removes every query param with the `name` & gets the number of removed params.
///
/// Removing every param removes the query along with its '?', since a query that is just a '?' is still one empty
/// param.
///
/// # Example
/// Removing the params named `a`:
/// - `"/?a=1"` -> `"/"`
/// - `"/?a=1&b=2"` -> `"/?b=2"`
/// - `"/?a=1&b=2&a=3"` -> `"/?b=2"`
pub fn remove_params(&mut self, name: &str) -> usize {
// The query is scanned before it is rebuilt so that a URL without a matching param is left untouched & never
// allocates.
if !self.query().into_iter().flatten().any(|p| p.name() == name) {
return 0;
}
let mut removed: usize = 0;
let mut query: String = String::with_capacity(self.query_len());
for param in self.query().into_iter().flatten() {
if param.name() == name {
removed += 1;
} else {
Self::push_query_param(&mut query, param);
}
}
self.set_query_str(query.as_str());
removed
}
/// Removes every query param with the `name`.
pub fn without_params(mut self, name: &str) -> Self {
self.remove_params(name);
self
}
/// Replaces every query param named like the `param` & gets the number of replaced params.
///
/// The first param with the name keeps its position & the rest are removed. When no param has the name the `param`
/// is appended as with `add_param`.
///
/// # Example
/// Replacing with the param `a=9`:
/// - `"/"` -> `"/?a=9"`
/// - `"/?a=1"` -> `"/?a=9"`
/// - `"/?b=2&a=1"` -> `"/?b=2&a=9"`
/// - `"/?a=1&b=2&a=3"` -> `"/?a=9&b=2"`
///
/// # Panics
/// Panics if the resulting URL would exceed `WebUrl::MAX_LEN`. The URL is left unmodified.
pub fn replace_params(&mut self, param: Param) -> usize {
let mut replaced: usize = 0;
let mut query: String = String::with_capacity(self.query_len());
for existing in self.query().into_iter().flatten() {
if existing.name() == param.name() {
replaced += 1;
if replaced == 1 {
Self::push_query_param(&mut query, param);
}
} else {
Self::push_query_param(&mut query, existing);
}
}
if replaced == 0 {
self.add_param(param);
} else {
self.set_query_str(query.as_str());
}
replaced
}
/// Replaces every query param named like the `param`.
///
/// # Panics
/// Panics if the resulting URL would exceed `WebUrl::MAX_LEN`.
pub fn with_replaced_params(mut self, param: Param) -> Self {
self.replace_params(param);
self
}
/// Appends the `separator` & the `param` to the `out` string.
///
/// This is the only place a param is spelled out, so `push_param_len` must match what it writes.
fn push_param(out: &mut String, separator: char, param: Param) {
out.push(separator);
out.push_str(param.name());
if let Some(value) = param.value() {
out.push('=');
out.push_str(value);
}
}
/// Gets the number of bytes `push_param` appends for the `param`. (including its separator)
fn push_param_len(param: Param) -> usize {
1 + param.name().len() + param.value().map(|v| 1 + v.len()).unwrap_or(0)
}
/// Appends the `param` to the `query` string being rebuilt, with its separator.
///
/// The '?' separator is used when the `query` is empty, otherwise the '&' separator is used.
fn push_query_param(query: &mut String, param: Param) {
Self::push_param(query, if query.is_empty() { '?' } else { '&' }, param);
}
}
#[cfg(test)]
mod tests {
use crate::{Fragment, Param, WebUrl};
use std::error::Error;
use std::str::FromStr;
/// Snapshots the query params as owned values.
///
/// The params borrow the URL, so they must be detached to be compared across a mutation.
fn params_of(url: &WebUrl) -> Vec<(String, Option<String>)> {
url.query()
.map(|q| {
q.iter_params()
.map(|p| (p.name().to_string(), p.value().map(str::to_string)))
.collect()
})
.unwrap_or_default()
}
#[test]
fn add_param() -> Result<(), Box<dyn Error>> {
let mut url: WebUrl = WebUrl::from_str("https://example.com")?;
url.set_fragment(Fragment::try_from("#fragment")?);
url.add_param(Param::try_from("one")?);
assert_eq!("https://example.com/?one#fragment", url.as_str());
url.add_param(Param::try_from("two=3")?);
assert_eq!("https://example.com/?one&two=3#fragment", url.as_str());
Ok(())
}
#[test]
fn add_param_appends_exactly_one_param() -> Result<(), Box<dyn Error>> {
// The '?' & '&' chars are separators, so an empty region between them is an empty parameter. Adding a parameter
// must append exactly one & leave the existing ones untouched.
let test_cases: &[(&str, &str, usize, usize)] = &[
("https://host/p", "https://host/p?p=1", 0, 1),
("https://host/p?", "https://host/p?&p=1", 1, 2),
("https://host/p?a=2", "https://host/p?a=2&p=1", 1, 2),
("https://host/p?&", "https://host/p?&&p=1", 2, 3),
("https://host/p?a=2&", "https://host/p?a=2&&p=1", 2, 3),
("https://host/p?a=2#f", "https://host/p?a=2&p=1#f", 1, 2),
("https://host/p?#f", "https://host/p?&p=1#f", 1, 2),
("https://host/p#f", "https://host/p?p=1#f", 0, 1),
];
for (input, expected, before_count, after_count) in test_cases {
let mut url: WebUrl = WebUrl::from_str(input)?;
let before: Vec<(String, Option<String>)> = params_of(&url);
assert_eq!(before.len(), *before_count, "input={input}");
url.add_param(Param::try_from("p=1")?);
assert_eq!(url.as_str(), *expected, "input={input}");
let after: Vec<(String, Option<String>)> = params_of(&url);
assert_eq!(after.len(), *after_count, "input={input}");
// The existing params are preserved in order & the new one is appended last.
assert_eq!(&after[..before.len()], &before[..], "input={input}");
assert_eq!(
after[after.len() - 1],
("p".to_string(), Some("1".to_string())),
"input={input}"
);
// The path & fragment are untouched & the URL still re-parses identically.
let reparsed: WebUrl = WebUrl::from_str(url.as_str())?;
assert_eq!(reparsed, url, "input={input}");
assert_eq!(reparsed.path().as_str(), "/p", "input={input}");
assert_eq!(
reparsed.fragment().map(|f| f.as_str()),
url.fragment().map(|f| f.as_str()),
"input={input}"
);
}
Ok(())
}
#[test]
fn add_param_repeated() -> Result<(), Box<dyn Error>> {
// Repeated additions must keep appending one at a time.
let mut url: WebUrl = WebUrl::from_str("https://host/p#f")?;
for (i, expected) in [
"https://host/p?a=0#f",
"https://host/p?a=0&a=1#f",
"https://host/p?a=0&a=1&a=2#f",
]
.iter()
.enumerate()
{
url.add_param(Param::try_from(format!("a={i}").as_str())?);
assert_eq!(url.as_str(), *expected);
assert_eq!(url.query().unwrap().iter_params().count(), i + 1);
}
Ok(())
}
#[test]
fn add_param_without_value() -> Result<(), Box<dyn Error>> {
// A param with no value has no '=' at all, which is distinct from an empty value.
let mut url: WebUrl = WebUrl::from_str("https://host/p")?;
url.add_param(Param::try_from("flag")?);
assert_eq!(url.as_str(), "https://host/p?flag");
url.add_param(Param::try_from("empty=")?);
assert_eq!(url.as_str(), "https://host/p?flag&empty=");
let params: Vec<Param> = url.query().unwrap().iter_params().collect();
assert_eq!(params[0].value(), None);
assert_eq!(params[1].value(), Some(""));
Ok(())
}
#[test]
fn with_param() -> Result<(), Box<dyn Error>> {
let url = WebUrl::from_str("https://example.com")?
.with_param(Param::try_from("a=1")?)
.with_param(Param::try_from("b=2")?);
assert_eq!(url.as_str(), "https://example.com/?a=1&b=2");
Ok(())
}
#[test]
fn remove_params() -> Result<(), Box<dyn Error>> {
// Removing every param removes the query along with its '?'.
let test_cases: &[(&str, &str, usize, &str)] = &[
("https://host/p?a=1", "a", 1, "https://host/p"),
("https://host/p?a=1&b=2", "a", 1, "https://host/p?b=2"),
("https://host/p?a=1&b=2&a=3", "a", 2, "https://host/p?b=2"),
("https://host/p?a&a=", "a", 2, "https://host/p"),
("https://host/p?a=1&b=2#f", "a", 1, "https://host/p?b=2#f"),
("https://host/p?a=1#f", "a", 1, "https://host/p#f"),
// A URL with no matching param is left untouched.
("https://host/p?a=1", "b", 0, "https://host/p?a=1"),
("https://host/p", "a", 0, "https://host/p"),
// A query that is just a '?' is still one empty param.
("https://host/p?", "", 1, "https://host/p"),
("https://host/p?&", "", 2, "https://host/p"),
("https://host/p?&a=1", "", 1, "https://host/p?a=1"),
];
for (input, name, removed, expected) in test_cases {
let mut url: WebUrl = WebUrl::from_str(input)?;
assert_eq!(url.remove_params(name), *removed, "input={input} name={name}");
assert_eq!(url.as_str(), *expected, "input={input} name={name}");
}
Ok(())
}
#[test]
fn without_params() -> Result<(), Box<dyn Error>> {
let url: WebUrl = WebUrl::from_str("https://host/p?a=1&b=2&a=3")?.without_params("a");
assert_eq!(url.as_str(), "https://host/p?b=2");
Ok(())
}
#[test]
fn replace_params() -> Result<(), Box<dyn Error>> {
// The first param with the name keeps its position & the rest are removed.
let test_cases: &[(&str, &str, usize, &str)] = &[
("https://host/p?a=1", "a=9", 1, "https://host/p?a=9"),
("https://host/p?b=2&a=1", "a=9", 1, "https://host/p?b=2&a=9"),
("https://host/p?a=1&b=2&a=3", "a=9", 2, "https://host/p?a=9&b=2"),
("https://host/p?a=1#f", "a=9", 1, "https://host/p?a=9#f"),
// The replacement drops the value when it has none.
("https://host/p?a=1", "a", 1, "https://host/p?a"),
// With no param of the name the replacement is appended, as with `add_param`.
("https://host/p", "a=9", 0, "https://host/p?a=9"),
("https://host/p?b=2", "a=9", 0, "https://host/p?b=2&a=9"),
("https://host/p#f", "a=9", 0, "https://host/p?a=9#f"),
// A query that is just a '?' is still one empty param.
("https://host/p?", "a=9", 0, "https://host/p?&a=9"),
("https://host/p?", "", 1, "https://host/p?"),
];
for (input, param, replaced, expected) in test_cases {
let mut url: WebUrl = WebUrl::from_str(input)?;
let param: Param = Param::try_from(*param)?;
assert_eq!(url.replace_params(param), *replaced, "input={input} param={param}");
assert_eq!(url.as_str(), *expected, "input={input} param={param}");
}
Ok(())
}
#[test]
fn with_replaced_params() -> Result<(), Box<dyn Error>> {
let url: WebUrl = WebUrl::from_str("https://host/p?a=1&b=2&a=3")?.with_replaced_params(Param::try_from("a=9")?);
assert_eq!(url.as_str(), "https://host/p?a=9&b=2");
Ok(())
}
}