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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
use std::error::Error;
use std::fmt::{self, Formatter, Write};
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
use std::ops::{Range, RangeFrom, RangeTo};
const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
pub(crate) const USERINFO: &AsciiSet = &PATH
.add(b'/')
.add(b':')
.add(b';')
.add(b'=')
.add(b'@')
.add(b'[')
.add(b'\\')
.add(b']')
.add(b'^')
.add(b'|');
#[derive(Clone)]
pub struct Hostname {
serialization: String,
pub scheme_end: usize,
pub username_end: usize,
pub host_start: usize,
pub host_end: usize,
}
impl Hostname {
pub fn parse(input: &str) -> Result<Hostname, ParseError> {
Parser {
serialization: String::with_capacity(input.len()),
}.parse_url(input)
}
fn has_host(&self) -> bool {
self.host_end > self.host_start
}
pub fn host_str(&self) -> Option<&str> {
if self.has_host() {
Some(self.slice(self.host_start..self.host_end))
} else {
None
}
}
pub fn url_str(&self) -> &str {
&self.serialization
}
fn slice<R>(&self, range: R) -> &str where R: RangeArg {
range.slice_of(&self.serialization)
}
}
trait RangeArg {
fn slice_of<'a>(&self, s: &'a str) -> &'a str;
}
impl RangeArg for Range<usize> {
fn slice_of<'a>(&self, s: &'a str) -> &'a str {
&s[self.start .. self.end ]
}
}
impl RangeArg for RangeFrom<usize> {
fn slice_of<'a>(&self, s: &'a str) -> &'a str {
&s[self.start ..]
}
}
impl RangeArg for RangeTo<usize> {
fn slice_of<'a>(&self, s: &'a str) -> &'a str {
&s[.. self.end]
}
}
pub type ParseResult<T> = Result<T, ParseError>;
macro_rules! simple_enum_error {
($($name: ident => $description: expr,)+) => {
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum ParseError {
$(
$name,
)+
}
impl Error for ParseError {}
impl fmt::Display for ParseError {
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
match *self {
$(
ParseError::$name => $description,
)+
}.fmt(fmt)
}
}
}
}
simple_enum_error! {
IdnaError => "invalid international domain name",
RelativeUrlWithoutBase => "relative URL without a base",
FileUrlNotSupported => "file URLs are not supported",
ExpectedMoreChars => "Expected more characters",
}
#[cfg(feature = "heapsize")]
known_heap_size!(0, ParseError);
impl From<idna::Errors> for ParseError {
fn from(_: idna::Errors) -> ParseError { ParseError::IdnaError }
}
#[derive(Copy, Clone)]
pub enum SchemeType {
File,
SpecialNotFile,
NotSpecial,
}
impl SchemeType {
pub fn is_special(self) -> bool {
!matches!(self, SchemeType::NotSpecial)
}
pub fn from(s: &str) -> Self {
match s {
"http" | "https" | "ws" | "wss" | "ftp" | "gopher" => SchemeType::SpecialNotFile,
"file" => SchemeType::File,
_ => SchemeType::NotSpecial,
}
}
}
#[derive(Clone)]
pub struct Input<'i> {
chars: std::str::Chars<'i>,
}
impl<'i> Input<'i> {
pub fn new(input: &'i str) -> Self {
let input = input.trim_matches(c0_control_or_space);
Input { chars: input.chars() }
}
pub fn is_empty(&self) -> bool {
self.clone().next().is_none()
}
fn starts_with<P: Pattern>(&self, p: P) -> bool {
p.split_prefix(&mut self.clone())
}
pub fn split_prefix<P: Pattern>(&self, p: P) -> Option<Self> {
let mut remaining = self.clone();
if p.split_prefix(&mut remaining) {
Some(remaining)
} else {
None
}
}
fn count_matching<F: Fn(char) -> bool>(&self, f: F) -> (u32, Self) {
let mut count = 0;
let mut remaining = self.clone();
loop {
let mut input = remaining.clone();
if matches!(input.next(), Some(c) if f(c)) {
remaining = input;
count += 1;
} else {
return (count, remaining)
}
}
}
fn next_utf8(&mut self) -> Option<(char, &'i str)> {
loop {
let utf8 = self.chars.as_str();
match self.chars.next() {
Some(c) => {
if !matches!(c, '\t' | '\n' | '\r') {
return Some((c, &utf8[..c.len_utf8()]))
}
}
None => return None
}
}
}
}
pub trait Pattern {
fn split_prefix(self, input: &mut Input) -> bool;
}
impl Pattern for char {
fn split_prefix(self, input: &mut Input) -> bool { input.next() == Some(self) }
}
impl<'a> Pattern for &'a str {
fn split_prefix(self, input: &mut Input) -> bool {
for c in self.chars() {
if input.next() != Some(c) {
return false
}
}
true
}
}
impl<F: FnMut(char) -> bool> Pattern for F {
fn split_prefix(self, input: &mut Input) -> bool { input.next().map_or(false, self) }
}
impl<'i> Iterator for Input<'i> {
type Item = char;
fn next(&mut self) -> Option<char> {
self.chars.next()
}
}
pub struct Parser {
pub serialization: String,
}
impl Parser {
pub fn parse_url(mut self, input: &str) -> ParseResult<Hostname> {
let input = Input::new(input);
if let Ok(remaining) = self.parse_scheme(input.clone()) {
return self.parse_with_scheme(remaining)
}
Err(ParseError::RelativeUrlWithoutBase)
}
pub fn parse_scheme<'i>(&mut self, mut input: Input<'i>) -> Result<Input<'i>, ()> {
if input.is_empty() || !input.starts_with(ascii_alpha) {
return Err(())
}
debug_assert!(self.serialization.is_empty());
while let Some(c) = input.next() {
match c {
'a'..='z' => self.serialization.push(c),
'A'..='Z' => self.serialization.push(c.to_ascii_lowercase()),
'0'..='9' | '+' | '-' | '.' => self.serialization.push(c),
':' => return Ok(input),
_ => {
self.serialization.clear();
return Err(())
}
}
}
Err(())
}
fn parse_with_scheme(mut self, input: Input) -> ParseResult<Hostname> {
let scheme_end = self.serialization.len();
let scheme_type = SchemeType::from(&self.serialization);
self.serialization.push(':');
match scheme_type {
SchemeType::File => {
Err(ParseError::FileUrlNotSupported)
}
SchemeType::SpecialNotFile => {
let (_, remaining) = input.count_matching(|c| matches!(c, '/' | '\\'));
self.after_double_slash(remaining, scheme_type, scheme_end)
}
SchemeType::NotSpecial => {
self.parse_non_special(input, scheme_type, scheme_end)
}
}
}
fn parse_non_special(mut self, input: Input, scheme_type: SchemeType, scheme_end: usize)
-> ParseResult<Hostname> {
if let Some(input) = input.split_prefix("//") {
return self.after_double_slash(input, scheme_type, scheme_end)
}
let path_start = self.serialization.len();
let username_end = path_start;
let host_start = path_start;
let host_end = path_start;
self.serialization.push_str(&input.chars.as_str());
let ser_remaining = self.serialization.as_mut_str().get_mut(host_end..);
ser_remaining.map(|s| {
s.make_ascii_lowercase();
&*s
});
Ok(Hostname {
serialization: self.serialization,
scheme_end,
username_end,
host_start,
host_end,
})
}
fn after_double_slash(mut self, input: Input, scheme_type: SchemeType, scheme_end: usize)
-> ParseResult<Hostname> {
self.serialization.push_str("//");
let (username_end, remaining) = self.parse_userinfo(input, scheme_type)?;
let host_start = self.serialization.len();
let (host_end, remaining) = self.parse_host(remaining, scheme_type)?;
self.serialization.push_str(&remaining.chars.as_str());
let ser_remaining = self.serialization.as_mut_str().get_mut(host_end..);
ser_remaining.map(|s| {
s.make_ascii_lowercase();
&*s
});
Ok(Hostname {
serialization: self.serialization,
scheme_end,
username_end,
host_start,
host_end,
})
}
fn parse_userinfo<'i>(&mut self, mut input: Input<'i>, scheme_type: SchemeType)
-> ParseResult<(usize, Input<'i>)> {
let mut last_at = None;
let mut remaining = input.clone();
let mut char_count = 0;
while let Some(c) = remaining.next() {
match c {
'@' => {
last_at = Some((char_count, remaining.clone()))
},
'/' | '?' | '#' => break,
'\\' if scheme_type.is_special() => break,
_ => (),
}
char_count += 1;
}
let (mut userinfo_char_count, remaining) = match last_at {
None => return Ok((self.serialization.len(), input)),
Some((0, remaining)) => return Ok((self.serialization.len(), remaining)),
Some(x) => x
};
let mut username_end = None;
let mut has_password = false;
let mut has_username = false;
while userinfo_char_count > 0 {
let (c, utf8_c) = input.next_utf8().ok_or(ParseError::ExpectedMoreChars)?;
userinfo_char_count -= 1;
if c == ':' && username_end.is_none() {
username_end = Some(self.serialization.len());
if userinfo_char_count > 0 {
self.serialization.push(':');
has_password = true;
}
} else {
if !has_password {
has_username = true;
}
self.serialization
.extend(utf8_percent_encode(utf8_c, USERINFO));
}
}
let username_end = match username_end {
Some(i) => i,
None => self.serialization.len(),
};
if has_username || has_password {
self.serialization.push('@');
}
Ok((username_end, remaining))
}
pub fn parse_host<'i>(&mut self, mut input: Input<'i>, scheme_type: SchemeType)
-> ParseResult<(usize, Input<'i>)> {
let input_str = input.chars.as_str();
let mut remaining = input.clone();
let mut inside_square_brackets = false;
let mut has_ignored_chars = false;
let mut non_ignored_chars = 0;
let mut bytes = 0;
for c in input_str.chars() {
match c {
':' if !inside_square_brackets => break,
'\\' if scheme_type.is_special() => break,
'/' | '?' | '#' => break,
'\t' | '\n' | '\r' => {
has_ignored_chars = true;
}
'[' => {
inside_square_brackets = true;
non_ignored_chars += 1
}
']' => {
inside_square_brackets = false;
non_ignored_chars += 1
}
_ => non_ignored_chars += 1
}
remaining.next();
bytes += c.len_utf8();
}
let replaced: String;
let host_str;
{
let host_input = input.by_ref().take(non_ignored_chars);
if has_ignored_chars {
replaced = host_input.collect();
host_str = &*replaced
} else {
for _ in host_input {}
host_str = &input_str[..bytes]
}
}
if host_str.is_ascii() {
write!(&mut self.serialization, "{}", host_str).unwrap();
} else {
let encoded = idna::domain_to_ascii(&host_str)?;
write!(&mut self.serialization, "{}", encoded).unwrap();
}
let host_end = self.serialization.len();
Ok((host_end, remaining))
}
}
#[inline]
fn c0_control_or_space(ch: char) -> bool {
ch <= ' '
}
#[inline]
pub fn ascii_alpha(ch: char) -> bool {
matches!(ch, 'a'..='z' | 'A'..='Z')
}