-
Notifications
You must be signed in to change notification settings - Fork 331
/
lib.rs
2966 lines (2764 loc) · 97.1 KB
/
lib.rs
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013-2015 The rust-url developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
rust-url is an implementation of the [URL Standard](http://url.spec.whatwg.org/)
for the [Rust](http://rust-lang.org/) programming language.
# URL parsing and data structures
First, URL parsing may fail for various reasons and therefore returns a `Result`.
```
use url::{Url, ParseError};
assert!(Url::parse("http://[:::1]") == Err(ParseError::InvalidIpv6Address))
```
Let’s parse a valid URL and look at its components.
```
use url::{Url, Host, Position};
# use url::ParseError;
# fn run() -> Result<(), ParseError> {
let issue_list_url = Url::parse(
"https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"
)?;
assert!(issue_list_url.scheme() == "https");
assert!(issue_list_url.username() == "");
assert!(issue_list_url.password() == None);
assert!(issue_list_url.host_str() == Some("github.com"));
assert!(issue_list_url.host() == Some(Host::Domain("github.com")));
assert!(issue_list_url.port() == None);
assert!(issue_list_url.path() == "/rust-lang/rust/issues");
assert!(issue_list_url.path_segments().map(|c| c.collect::<Vec<_>>()) ==
Some(vec!["rust-lang", "rust", "issues"]));
assert!(issue_list_url.query() == Some("labels=E-easy&state=open"));
assert!(&issue_list_url[Position::BeforePath..] == "/rust-lang/rust/issues?labels=E-easy&state=open");
assert!(issue_list_url.fragment() == None);
assert!(!issue_list_url.cannot_be_a_base());
# Ok(())
# }
# run().unwrap();
```
Some URLs are said to be *cannot-be-a-base*:
they don’t have a username, password, host, or port,
and their "path" is an arbitrary string rather than slash-separated segments:
```
use url::Url;
# use url::ParseError;
# fn run() -> Result<(), ParseError> {
let data_url = Url::parse("data:text/plain,Hello?World#")?;
assert!(data_url.cannot_be_a_base());
assert!(data_url.scheme() == "data");
assert!(data_url.path() == "text/plain,Hello");
assert!(data_url.path_segments().is_none());
assert!(data_url.query() == Some("World"));
assert!(data_url.fragment() == Some(""));
# Ok(())
# }
# run().unwrap();
```
## Serde
Enable the `serde` feature to include `Deserialize` and `Serialize` implementations for `url::Url`.
# Base URL
Many contexts allow URL *references* that can be relative to a *base URL*:
```html
<link rel="stylesheet" href="../main.css">
```
Since parsed URLs are absolute, giving a base is required for parsing relative URLs:
```
use url::{Url, ParseError};
assert!(Url::parse("../main.css") == Err(ParseError::RelativeUrlWithoutBase))
```
Use the `join` method on an `Url` to use it as a base URL:
```
use url::Url;
# use url::ParseError;
# fn run() -> Result<(), ParseError> {
let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html")?;
let css_url = this_document.join("../main.css")?;
assert_eq!(css_url.as_str(), "http://servo.github.io/rust-url/main.css");
# Ok(())
# }
# run().unwrap();
```
# Feature: `serde`
If you enable the `serde` feature, [`Url`](struct.Url.html) will implement
[`serde::Serialize`](https://docs.rs/serde/1/serde/trait.Serialize.html) and
[`serde::Deserialize`](https://docs.rs/serde/1/serde/trait.Deserialize.html).
See [serde documentation](https://serde.rs) for more information.
```toml
url = { version = "2", features = ["serde"] }
```
*/
#![doc(html_root_url = "https://docs.rs/url/2.3.1")]
#![cfg_attr(
feature = "debugger_visualizer",
feature(debugger_visualizer),
debugger_visualizer(natvis_file = "../../debug_metadata/url.natvis")
)]
pub use form_urlencoded;
#[cfg(feature = "serde")]
extern crate serde;
use crate::host::HostInternal;
use crate::parser::{to_u32, Context, Parser, SchemeType, PATH_SEGMENT, USERINFO};
use percent_encoding::{percent_decode, percent_encode, utf8_percent_encode};
use std::borrow::Borrow;
use std::cmp;
use std::fmt::{self, Write};
use std::hash;
use std::io;
use std::mem;
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
use std::ops::{Range, RangeFrom, RangeTo};
use std::path::{Path, PathBuf};
use std::str;
use std::convert::TryFrom;
pub use crate::host::Host;
pub use crate::origin::{OpaqueOrigin, Origin};
pub use crate::parser::{ParseError, SyntaxViolation};
pub use crate::path_segments::PathSegmentsMut;
pub use crate::slicing::Position;
pub use form_urlencoded::EncodingOverride;
mod host;
mod origin;
mod parser;
mod path_segments;
mod slicing;
#[doc(hidden)]
pub mod quirks;
/// A parsed URL record.
#[derive(Clone)]
pub struct Url {
/// Syntax in pseudo-BNF:
///
/// url = scheme ":" [ hierarchical | non-hierarchical ] [ "?" query ]? [ "#" fragment ]?
/// non-hierarchical = non-hierarchical-path
/// non-hierarchical-path = /* Does not start with "/" */
/// hierarchical = authority? hierarchical-path
/// authority = "//" userinfo? host [ ":" port ]?
/// userinfo = username [ ":" password ]? "@"
/// hierarchical-path = [ "/" path-segment ]+
serialization: String,
// Components
scheme_end: u32, // Before ':'
username_end: u32, // Before ':' (if a password is given) or '@' (if not)
host_start: u32,
host_end: u32,
host: HostInternal,
port: Option<u16>,
path_start: u32, // Before initial '/', if any
query_start: Option<u32>, // Before '?', unlike Position::QueryStart
fragment_start: Option<u32>, // Before '#', unlike Position::FragmentStart
}
/// Full configuration for the URL parser.
#[derive(Copy, Clone)]
pub struct ParseOptions<'a> {
base_url: Option<&'a Url>,
encoding_override: EncodingOverride<'a>,
violation_fn: Option<&'a dyn Fn(SyntaxViolation)>,
}
impl<'a> ParseOptions<'a> {
/// Change the base URL
pub fn base_url(mut self, new: Option<&'a Url>) -> Self {
self.base_url = new;
self
}
/// Override the character encoding of query strings.
/// This is a legacy concept only relevant for HTML.
pub fn encoding_override(mut self, new: EncodingOverride<'a>) -> Self {
self.encoding_override = new;
self
}
/// Call the provided function or closure for a non-fatal `SyntaxViolation`
/// when it occurs during parsing. Note that since the provided function is
/// `Fn`, the caller might need to utilize _interior mutability_, such as with
/// a `RefCell`, to collect the violations.
///
/// ## Example
/// ```
/// use std::cell::RefCell;
/// use url::{Url, SyntaxViolation};
/// # use url::ParseError;
/// # fn run() -> Result<(), url::ParseError> {
/// let violations = RefCell::new(Vec::new());
/// let url = Url::options()
/// .syntax_violation_callback(Some(&|v| violations.borrow_mut().push(v)))
/// .parse("https:////example.com")?;
/// assert_eq!(url.as_str(), "https://example.com/");
/// assert_eq!(violations.into_inner(),
/// vec!(SyntaxViolation::ExpectedDoubleSlash));
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
pub fn syntax_violation_callback(mut self, new: Option<&'a dyn Fn(SyntaxViolation)>) -> Self {
self.violation_fn = new;
self
}
/// Parse an URL string with the configuration so far.
pub fn parse(self, input: &str) -> Result<Url, crate::ParseError> {
Parser {
serialization: String::with_capacity(input.len()),
base_url: self.base_url,
query_encoding_override: self.encoding_override,
violation_fn: self.violation_fn,
context: Context::UrlParser,
}
.parse_url(input)
}
}
impl Url {
/// Parse an absolute URL from a string.
///
/// # Examples
///
/// ```rust
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("https://example.net")?;
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
///
/// # Errors
///
/// If the function can not parse an absolute URL from the given string,
/// a [`ParseError`] variant will be returned.
///
/// [`ParseError`]: enum.ParseError.html
#[inline]
pub fn parse(input: &str) -> Result<Url, crate::ParseError> {
Url::options().parse(input)
}
/// Parse an absolute URL from a string and add params to its query string.
///
/// Existing params are not removed.
///
/// # Examples
///
/// ```rust
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse_with_params("https://example.net?dont=clobberme",
/// &[("lang", "rust"), ("browser", "servo")])?;
/// assert_eq!("https://example.net/?dont=clobberme&lang=rust&browser=servo", url.as_str());
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
///
/// # Errors
///
/// If the function can not parse an absolute URL from the given string,
/// a [`ParseError`] variant will be returned.
///
/// [`ParseError`]: enum.ParseError.html
#[inline]
pub fn parse_with_params<I, K, V>(input: &str, iter: I) -> Result<Url, crate::ParseError>
where
I: IntoIterator,
I::Item: Borrow<(K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
let mut url = Url::options().parse(input);
if let Ok(ref mut url) = url {
url.query_pairs_mut().extend_pairs(iter);
}
url
}
/// Parse a string as an URL, with this URL as the base URL.
///
/// The inverse of this is [`make_relative`].
///
/// Note: a trailing slash is significant.
/// Without it, the last path component is considered to be a “file” name
/// to be removed to get at the “directory” that is used as the base:
///
/// # Examples
///
/// ```rust
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let base = Url::parse("https://example.net/a/b.html")?;
/// let url = base.join("c.png")?;
/// assert_eq!(url.as_str(), "https://example.net/a/c.png"); // Not /a/b.html/c.png
///
/// let base = Url::parse("https://example.net/a/b/")?;
/// let url = base.join("c.png")?;
/// assert_eq!(url.as_str(), "https://example.net/a/b/c.png");
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
///
/// # Errors
///
/// If the function can not parse an URL from the given string
/// with this URL as the base URL, a [`ParseError`] variant will be returned.
///
/// [`ParseError`]: enum.ParseError.html
/// [`make_relative`]: #method.make_relative
#[inline]
pub fn join(&self, input: &str) -> Result<Url, crate::ParseError> {
Url::options().base_url(Some(self)).parse(input)
}
/// Creates a relative URL if possible, with this URL as the base URL.
///
/// This is the inverse of [`join`].
///
/// # Examples
///
/// ```rust
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let base = Url::parse("https://example.net/a/b.html")?;
/// let url = Url::parse("https://example.net/a/c.png")?;
/// let relative = base.make_relative(&url);
/// assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("c.png"));
///
/// let base = Url::parse("https://example.net/a/b/")?;
/// let url = Url::parse("https://example.net/a/b/c.png")?;
/// let relative = base.make_relative(&url);
/// assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("c.png"));
///
/// let base = Url::parse("https://example.net/a/b/")?;
/// let url = Url::parse("https://example.net/a/d/c.png")?;
/// let relative = base.make_relative(&url);
/// assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("../d/c.png"));
///
/// let base = Url::parse("https://example.net/a/b.html?c=d")?;
/// let url = Url::parse("https://example.net/a/b.html?e=f")?;
/// let relative = base.make_relative(&url);
/// assert_eq!(relative.as_ref().map(|s| s.as_str()), Some("?e=f"));
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
///
/// # Errors
///
/// If this URL can't be a base for the given URL, `None` is returned.
/// This is for example the case if the scheme, host or port are not the same.
///
/// [`join`]: #method.join
pub fn make_relative(&self, url: &Url) -> Option<String> {
if self.cannot_be_a_base() {
return None;
}
// Scheme, host and port need to be the same
if self.scheme() != url.scheme() || self.host() != url.host() || self.port() != url.port() {
return None;
}
// We ignore username/password at this point
// The path has to be transformed
let mut relative = String::new();
// Extract the filename of both URIs, these need to be handled separately
fn extract_path_filename(s: &str) -> (&str, &str) {
let last_slash_idx = s.rfind('/').unwrap_or(0);
let (path, filename) = s.split_at(last_slash_idx);
if filename.is_empty() {
(path, "")
} else {
(path, &filename[1..])
}
}
let (base_path, base_filename) = extract_path_filename(self.path());
let (url_path, url_filename) = extract_path_filename(url.path());
let mut base_path = base_path.split('/').peekable();
let mut url_path = url_path.split('/').peekable();
// Skip over the common prefix
while base_path.peek().is_some() && base_path.peek() == url_path.peek() {
base_path.next();
url_path.next();
}
// Add `..` segments for the remainder of the base path
for base_path_segment in base_path {
// Skip empty last segments
if base_path_segment.is_empty() {
break;
}
if !relative.is_empty() {
relative.push('/');
}
relative.push_str("..");
}
// Append the remainder of the other URI
for url_path_segment in url_path {
if !relative.is_empty() {
relative.push('/');
}
relative.push_str(url_path_segment);
}
// Add the filename if they are not the same
if !relative.is_empty() || base_filename != url_filename {
// If the URIs filename is empty this means that it was a directory
// so we'll have to append a '/'.
//
// Otherwise append it directly as the new filename.
if url_filename.is_empty() {
relative.push('/');
} else {
if !relative.is_empty() {
relative.push('/');
}
relative.push_str(url_filename);
}
}
// Query and fragment are only taken from the other URI
if let Some(query) = url.query() {
relative.push('?');
relative.push_str(query);
}
if let Some(fragment) = url.fragment() {
relative.push('#');
relative.push_str(fragment);
}
Some(relative)
}
/// Return a default `ParseOptions` that can fully configure the URL parser.
///
/// # Examples
///
/// Get default `ParseOptions`, then change base url
///
/// ```rust
/// use url::Url;
/// # use url::ParseError;
/// # fn run() -> Result<(), ParseError> {
/// let options = Url::options();
/// let api = Url::parse("https://api.example.com")?;
/// let base_url = options.base_url(Some(&api));
/// let version_url = base_url.parse("version.json")?;
/// assert_eq!(version_url.as_str(), "https://api.example.com/version.json");
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
pub fn options<'a>() -> ParseOptions<'a> {
ParseOptions {
base_url: None,
encoding_override: None,
violation_fn: None,
}
}
/// Return the serialization of this URL.
///
/// This is fast since that serialization is already stored in the `Url` struct.
///
/// # Examples
///
/// ```rust
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url_str = "https://example.net/";
/// let url = Url::parse(url_str)?;
/// assert_eq!(url.as_str(), url_str);
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
#[inline]
pub fn as_str(&self) -> &str {
&self.serialization
}
/// Return the serialization of this URL.
///
/// This consumes the `Url` and takes ownership of the `String` stored in it.
///
/// # Examples
///
/// ```rust
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url_str = "https://example.net/";
/// let url = Url::parse(url_str)?;
/// assert_eq!(String::from(url), url_str);
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
#[inline]
#[deprecated(since = "2.3.0", note = "use Into<String>")]
pub fn into_string(self) -> String {
self.into()
}
/// For internal testing, not part of the public API.
///
/// Methods of the `Url` struct assume a number of invariants.
/// This checks each of these invariants and panic if one is not met.
/// This is for testing rust-url itself.
#[doc(hidden)]
pub fn check_invariants(&self) -> Result<(), String> {
macro_rules! assert {
($x: expr) => {
if !$x {
return Err(format!(
"!( {} ) for URL {:?}",
stringify!($x),
self.serialization
));
}
};
}
macro_rules! assert_eq {
($a: expr, $b: expr) => {
{
let a = $a;
let b = $b;
if a != b {
return Err(format!("{:?} != {:?} ({} != {}) for URL {:?}",
a, b, stringify!($a), stringify!($b),
self.serialization))
}
}
}
}
assert!(self.scheme_end >= 1);
assert!(matches!(self.byte_at(0), b'a'..=b'z' | b'A'..=b'Z'));
assert!(self
.slice(1..self.scheme_end)
.chars()
.all(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '+' | '-' | '.')));
assert_eq!(self.byte_at(self.scheme_end), b':');
if self.slice(self.scheme_end + 1..).starts_with("//") {
// URL with authority
if self.username_end != self.serialization.len() as u32 {
match self.byte_at(self.username_end) {
b':' => {
assert!(self.host_start >= self.username_end + 2);
assert_eq!(self.byte_at(self.host_start - 1), b'@');
}
b'@' => assert!(self.host_start == self.username_end + 1),
_ => assert_eq!(self.username_end, self.scheme_end + 3),
}
}
assert!(self.host_start >= self.username_end);
assert!(self.host_end >= self.host_start);
let host_str = self.slice(self.host_start..self.host_end);
match self.host {
HostInternal::None => assert_eq!(host_str, ""),
HostInternal::Ipv4(address) => assert_eq!(host_str, address.to_string()),
HostInternal::Ipv6(address) => {
let h: Host<String> = Host::Ipv6(address);
assert_eq!(host_str, h.to_string())
}
HostInternal::Domain => {
if SchemeType::from(self.scheme()).is_special() {
assert!(!host_str.is_empty())
}
}
}
if self.path_start == self.host_end {
assert_eq!(self.port, None);
} else {
assert_eq!(self.byte_at(self.host_end), b':');
let port_str = self.slice(self.host_end + 1..self.path_start);
assert_eq!(
self.port,
Some(port_str.parse::<u16>().expect("Couldn't parse port?"))
);
}
assert!(
self.path_start as usize == self.serialization.len()
|| matches!(self.byte_at(self.path_start), b'/' | b'#' | b'?')
);
} else {
// Anarchist URL (no authority)
assert_eq!(self.username_end, self.scheme_end + 1);
assert_eq!(self.host_start, self.scheme_end + 1);
assert_eq!(self.host_end, self.scheme_end + 1);
assert_eq!(self.host, HostInternal::None);
assert_eq!(self.port, None);
assert_eq!(self.path_start, self.scheme_end + 1);
}
if let Some(start) = self.query_start {
assert!(start >= self.path_start);
assert_eq!(self.byte_at(start), b'?');
}
if let Some(start) = self.fragment_start {
assert!(start >= self.path_start);
assert_eq!(self.byte_at(start), b'#');
}
if let (Some(query_start), Some(fragment_start)) = (self.query_start, self.fragment_start) {
assert!(fragment_start > query_start);
}
let other = Url::parse(self.as_str()).expect("Failed to parse myself?");
assert_eq!(&self.serialization, &other.serialization);
assert_eq!(self.scheme_end, other.scheme_end);
assert_eq!(self.username_end, other.username_end);
assert_eq!(self.host_start, other.host_start);
assert_eq!(self.host_end, other.host_end);
assert!(
self.host == other.host ||
// XXX No host round-trips to empty host.
// See https://github.com/whatwg/url/issues/79
(self.host_str(), other.host_str()) == (None, Some(""))
);
assert_eq!(self.port, other.port);
assert_eq!(self.path_start, other.path_start);
assert_eq!(self.query_start, other.query_start);
assert_eq!(self.fragment_start, other.fragment_start);
Ok(())
}
/// Return the origin of this URL (<https://url.spec.whatwg.org/#origin>)
///
/// Note: this returns an opaque origin for `file:` URLs, which causes
/// `url.origin() != url.origin()`.
///
/// # Examples
///
/// URL with `ftp` scheme:
///
/// ```rust
/// use url::{Host, Origin, Url};
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("ftp://example.com/foo")?;
/// assert_eq!(url.origin(),
/// Origin::Tuple("ftp".into(),
/// Host::Domain("example.com".into()),
/// 21));
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
///
/// URL with `blob` scheme:
///
/// ```rust
/// use url::{Host, Origin, Url};
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("blob:https://example.com/foo")?;
/// assert_eq!(url.origin(),
/// Origin::Tuple("https".into(),
/// Host::Domain("example.com".into()),
/// 443));
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
///
/// URL with `file` scheme:
///
/// ```rust
/// use url::{Host, Origin, Url};
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("file:///tmp/foo")?;
/// assert!(!url.origin().is_tuple());
///
/// let other_url = Url::parse("file:///tmp/foo")?;
/// assert!(url.origin() != other_url.origin());
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
///
/// URL with other scheme:
///
/// ```rust
/// use url::{Host, Origin, Url};
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("foo:bar")?;
/// assert!(!url.origin().is_tuple());
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
#[inline]
pub fn origin(&self) -> Origin {
origin::url_origin(self)
}
/// Return the scheme of this URL, lower-cased, as an ASCII string without the ':' delimiter.
///
/// # Examples
///
/// ```
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("file:///tmp/foo")?;
/// assert_eq!(url.scheme(), "file");
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
#[inline]
pub fn scheme(&self) -> &str {
self.slice(..self.scheme_end)
}
/// Return whether the URL has an 'authority',
/// which can contain a username, password, host, and port number.
///
/// URLs that do *not* are either path-only like `unix:/run/foo.socket`
/// or cannot-be-a-base like `data:text/plain,Stuff`.
///
/// See also the `authority` method.
///
/// # Examples
///
/// ```
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("ftp://rms@example.com")?;
/// assert!(url.has_authority());
///
/// let url = Url::parse("unix:/run/foo.socket")?;
/// assert!(!url.has_authority());
///
/// let url = Url::parse("data:text/plain,Stuff")?;
/// assert!(!url.has_authority());
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
#[inline]
pub fn has_authority(&self) -> bool {
debug_assert!(self.byte_at(self.scheme_end) == b':');
self.slice(self.scheme_end..).starts_with("://")
}
/// Return the authority of this URL as an ASCII string.
///
/// Non-ASCII domains are punycode-encoded per IDNA if this is the host
/// of a special URL, or percent encoded for non-special URLs.
/// IPv6 addresses are given between `[` and `]` brackets.
/// Ports are omitted if they match the well known port of a special URL.
///
/// Username and password are percent-encoded.
///
/// See also the `has_authority` method.
///
/// # Examples
///
/// ```
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("unix:/run/foo.socket")?;
/// assert_eq!(url.authority(), "");
/// let url = Url::parse("file:///tmp/foo")?;
/// assert_eq!(url.authority(), "");
/// let url = Url::parse("https://user:password@example.com/tmp/foo")?;
/// assert_eq!(url.authority(), "user:password@example.com");
/// let url = Url::parse("irc://àlex.рф.example.com:6667/foo")?;
/// assert_eq!(url.authority(), "%C3%A0lex.%D1%80%D1%84.example.com:6667");
/// let url = Url::parse("http://àlex.рф.example.com:80/foo")?;
/// assert_eq!(url.authority(), "xn--lex-8ka.xn--p1ai.example.com");
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
pub fn authority(&self) -> &str {
let scheme_separator_len = "://".len() as u32;
if self.has_authority() && self.path_start > self.scheme_end + scheme_separator_len {
self.slice(self.scheme_end + scheme_separator_len..self.path_start)
} else {
""
}
}
/// Return whether this URL is a cannot-be-a-base URL,
/// meaning that parsing a relative URL string with this URL as the base will return an error.
///
/// This is the case if the scheme and `:` delimiter are not followed by a `/` slash,
/// as is typically the case of `data:` and `mailto:` URLs.
///
/// # Examples
///
/// ```
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("ftp://rms@example.com")?;
/// assert!(!url.cannot_be_a_base());
///
/// let url = Url::parse("unix:/run/foo.socket")?;
/// assert!(!url.cannot_be_a_base());
///
/// let url = Url::parse("data:text/plain,Stuff")?;
/// assert!(url.cannot_be_a_base());
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
#[inline]
pub fn cannot_be_a_base(&self) -> bool {
!self.slice(self.scheme_end + 1..).starts_with('/')
}
/// Return the username for this URL (typically the empty string)
/// as a percent-encoded ASCII string.
///
/// # Examples
///
/// ```
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("ftp://rms@example.com")?;
/// assert_eq!(url.username(), "rms");
///
/// let url = Url::parse("ftp://:secret123@example.com")?;
/// assert_eq!(url.username(), "");
///
/// let url = Url::parse("https://example.com")?;
/// assert_eq!(url.username(), "");
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
pub fn username(&self) -> &str {
let scheme_separator_len = "://".len() as u32;
if self.has_authority() && self.username_end > self.scheme_end + scheme_separator_len {
self.slice(self.scheme_end + scheme_separator_len..self.username_end)
} else {
""
}
}
/// Return the password for this URL, if any, as a percent-encoded ASCII string.
///
/// # Examples
///
/// ```
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("ftp://rms:secret123@example.com")?;
/// assert_eq!(url.password(), Some("secret123"));
///
/// let url = Url::parse("ftp://:secret123@example.com")?;
/// assert_eq!(url.password(), Some("secret123"));
///
/// let url = Url::parse("ftp://rms@example.com")?;
/// assert_eq!(url.password(), None);
///
/// let url = Url::parse("https://example.com")?;
/// assert_eq!(url.password(), None);
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
pub fn password(&self) -> Option<&str> {
// This ':' is not the one marking a port number since a host can not be empty.
// (Except for file: URLs, which do not have port numbers.)
if self.has_authority()
&& self.username_end != self.serialization.len() as u32
&& self.byte_at(self.username_end) == b':'
{
debug_assert!(self.byte_at(self.host_start - 1) == b'@');
Some(self.slice(self.username_end + 1..self.host_start - 1))
} else {
None
}
}
/// Equivalent to `url.host().is_some()`.
///
/// # Examples
///
/// ```
/// use url::Url;
/// # use url::ParseError;
///
/// # fn run() -> Result<(), ParseError> {
/// let url = Url::parse("ftp://rms@example.com")?;
/// assert!(url.has_host());
///
/// let url = Url::parse("unix:/run/foo.socket")?;
/// assert!(!url.has_host());
///
/// let url = Url::parse("data:text/plain,Stuff")?;
/// assert!(!url.has_host());
/// # Ok(())
/// # }
/// # run().unwrap();
/// ```
pub fn has_host(&self) -> bool {
!matches!(self.host, HostInternal::None)
}
/// Return the string representation of the host (domain or IP address) for this URL, if any.
///
/// Non-ASCII domains are punycode-encoded per IDNA if this is the host
/// of a special URL, or percent encoded for non-special URLs.
/// IPv6 addresses are given between `[` and `]` brackets.
///
/// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
/// don’t have a host.
///
/// See also the `host` method.
///
/// # Examples
///
/// ```