lib.rs 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. // Copyright 2013-2015 The rust-url developers.
  2. //
  3. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  4. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  5. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  6. // option. This file may not be copied, modified, or distributed
  7. // except according to those terms.
  8. /*!
  9. rust-url is an implementation of the [URL Standard](http://url.spec.whatwg.org/)
  10. for the [Rust](http://rust-lang.org/) programming language.
  11. It builds with [Cargo](http://crates.io/).
  12. To use it in your project, add this to your `Cargo.toml` file:
  13. ```Cargo
  14. [dependencies.url]
  15. git = "https://github.com/servo/rust-url"
  16. ```
  17. Supporting encodings other than UTF-8 in query strings is an optional feature
  18. that requires [rust-encoding](https://github.com/lifthrasiir/rust-encoding)
  19. and is off by default.
  20. You can enable it with
  21. [Cargo’s *features* mechanism](http://doc.crates.io/manifest.html#the-[features]-section):
  22. ```Cargo
  23. [dependencies.url]
  24. git = "https://github.com/servo/rust-url"
  25. features = ["query_encoding"]
  26. ```
  27. … or by passing `--cfg 'feature="query_encoding"'` to rustc.
  28. # URL parsing and data structures
  29. First, URL parsing may fail for various reasons and therefore returns a `Result`.
  30. ```
  31. use url::{Url, ParseError};
  32. assert!(Url::parse("http://[:::1]") == Err(ParseError::InvalidIpv6Address))
  33. ```
  34. Let’s parse a valid URL and look at its components.
  35. ```
  36. use url::{Url, Host};
  37. let issue_list_url = Url::parse(
  38. "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"
  39. ).unwrap();
  40. assert!(issue_list_url.scheme() == "https");
  41. assert!(issue_list_url.username() == "");
  42. assert!(issue_list_url.password() == None);
  43. assert!(issue_list_url.host_str() == Some("github.com"));
  44. assert!(issue_list_url.host() == Some(Host::Domain("github.com")));
  45. assert!(issue_list_url.port() == None);
  46. assert!(issue_list_url.path() == "/rust-lang/rust/issues");
  47. assert!(issue_list_url.path_segments().map(|c| c.collect::<Vec<_>>()) ==
  48. Some(vec!["rust-lang", "rust", "issues"]));
  49. assert!(issue_list_url.query() == Some("labels=E-easy&state=open"));
  50. assert!(issue_list_url.fragment() == None);
  51. assert!(!issue_list_url.cannot_be_a_base());
  52. ```
  53. Some URLs are said to be *cannot-be-a-base*:
  54. they don’t have a username, password, host, or port,
  55. and their "path" is an arbitrary string rather than slash-separated segments:
  56. ```
  57. use url::Url;
  58. let data_url = Url::parse("data:text/plain,Hello?World#").unwrap();
  59. assert!(data_url.cannot_be_a_base());
  60. assert!(data_url.scheme() == "data");
  61. assert!(data_url.path() == "text/plain,Hello");
  62. assert!(data_url.path_segments().is_none());
  63. assert!(data_url.query() == Some("World"));
  64. assert!(data_url.fragment() == Some(""));
  65. ```
  66. # Base URL
  67. Many contexts allow URL *references* that can be relative to a *base URL*:
  68. ```html
  69. <link rel="stylesheet" href="../main.css">
  70. ```
  71. Since parsed URL are absolute, giving a base is required for parsing relative URLs:
  72. ```
  73. use url::{Url, ParseError};
  74. assert!(Url::parse("../main.css") == Err(ParseError::RelativeUrlWithoutBase))
  75. ```
  76. Use the `join` method on an `Url` to use it as a base URL:
  77. ```
  78. use url::Url;
  79. let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html").unwrap();
  80. let css_url = this_document.join("../main.css").unwrap();
  81. assert_eq!(css_url.as_str(), "http://servo.github.io/rust-url/main.css")
  82. */
  83. #![cfg_attr(feature="heap_size", feature(plugin, custom_derive))]
  84. #![cfg_attr(feature="heap_size", plugin(heapsize_plugin))]
  85. #[cfg(feature="rustc-serialize")] extern crate rustc_serialize;
  86. #[macro_use] extern crate matches;
  87. #[cfg(feature="serde")] extern crate serde;
  88. #[cfg(feature="heap_size")] #[macro_use] extern crate heapsize;
  89. pub extern crate idna;
  90. use encoding::EncodingOverride;
  91. use host::HostInternal;
  92. use parser::{Parser, Context, SchemeType, to_u32};
  93. use percent_encoding::{PATH_SEGMENT_ENCODE_SET, USERINFO_ENCODE_SET,
  94. percent_encode, percent_decode, utf8_percent_encode};
  95. use std::cmp;
  96. use std::fmt::{self, Write};
  97. use std::hash;
  98. use std::io;
  99. use std::mem;
  100. use std::net::{ToSocketAddrs, IpAddr};
  101. use std::ops::{Range, RangeFrom, RangeTo};
  102. use std::path::{Path, PathBuf};
  103. use std::str;
  104. pub use origin::{Origin, OpaqueOrigin};
  105. pub use host::{Host, HostAndPort, SocketAddrs};
  106. pub use path_segments::PathSegmentsMut;
  107. pub use parser::ParseError;
  108. pub use slicing::Position;
  109. mod encoding;
  110. mod host;
  111. mod origin;
  112. mod path_segments;
  113. mod parser;
  114. mod slicing;
  115. pub mod form_urlencoded;
  116. pub mod percent_encoding;
  117. pub mod quirks;
  118. /// A parsed URL record.
  119. #[derive(Clone)]
  120. #[cfg_attr(feature="heap_size", derive(HeapSizeOf))]
  121. pub struct Url {
  122. /// Syntax in pseudo-BNF:
  123. ///
  124. /// url = scheme ":" [ hierarchical | non-hierarchical ] [ "?" query ]? [ "#" fragment ]?
  125. /// non-hierarchical = non-hierarchical-path
  126. /// non-hierarchical-path = /* Does not start with "/" */
  127. /// hierarchical = authority? hierarchical-path
  128. /// authority = "//" userinfo? host [ ":" port ]?
  129. /// userinfo = username [ ":" password ]? "@"
  130. /// hierarchical-path = [ "/" path-segment ]+
  131. serialization: String,
  132. // Components
  133. scheme_end: u32, // Before ':'
  134. username_end: u32, // Before ':' (if a password is given) or '@' (if not)
  135. host_start: u32,
  136. host_end: u32,
  137. host: HostInternal,
  138. port: Option<u16>,
  139. path_start: u32, // Before initial '/', if any
  140. query_start: Option<u32>, // Before '?', unlike Position::QueryStart
  141. fragment_start: Option<u32>, // Before '#', unlike Position::FragmentStart
  142. }
  143. /// Full configuration for the URL parser.
  144. #[derive(Copy, Clone)]
  145. pub struct ParseOptions<'a> {
  146. base_url: Option<&'a Url>,
  147. encoding_override: encoding::EncodingOverride,
  148. log_syntax_violation: Option<&'a Fn(&'static str)>,
  149. }
  150. impl<'a> ParseOptions<'a> {
  151. /// Change the base URL
  152. pub fn base_url(mut self, new: Option<&'a Url>) -> Self {
  153. self.base_url = new;
  154. self
  155. }
  156. /// Override the character encoding of query strings.
  157. /// This is a legacy concept only relevant for HTML.
  158. #[cfg(feature = "query_encoding")]
  159. pub fn encoding_override(mut self, new: Option<encoding::EncodingRef>) -> Self {
  160. self.encoding_override = EncodingOverride::from_opt_encoding(new).to_output_encoding();
  161. self
  162. }
  163. /// Call the provided function or closure on non-fatal parse errors.
  164. pub fn log_syntax_violation(mut self, new: Option<&'a Fn(&'static str)>) -> Self {
  165. self.log_syntax_violation = new;
  166. self
  167. }
  168. /// Parse an URL string with the configuration so far.
  169. pub fn parse(self, input: &str) -> Result<Url, ::ParseError> {
  170. Parser {
  171. serialization: String::with_capacity(input.len()),
  172. base_url: self.base_url,
  173. query_encoding_override: self.encoding_override,
  174. log_syntax_violation: self.log_syntax_violation,
  175. context: Context::UrlParser,
  176. }.parse_url(input)
  177. }
  178. }
  179. impl Url {
  180. /// Parse an absolute URL from a string.
  181. #[inline]
  182. pub fn parse(input: &str) -> Result<Url, ::ParseError> {
  183. Url::options().parse(input)
  184. }
  185. /// Parse a string as an URL, with this URL as the base URL.
  186. #[inline]
  187. pub fn join(&self, input: &str) -> Result<Url, ::ParseError> {
  188. Url::options().base_url(Some(self)).parse(input)
  189. }
  190. /// Return a default `ParseOptions` that can fully configure the URL parser.
  191. pub fn options<'a>() -> ParseOptions<'a> {
  192. ParseOptions {
  193. base_url: None,
  194. encoding_override: EncodingOverride::utf8(),
  195. log_syntax_violation: None,
  196. }
  197. }
  198. /// Return the serialization of this URL.
  199. ///
  200. /// This is fast since that serialization is already stored in the `Url` struct.
  201. #[inline]
  202. pub fn as_str(&self) -> &str {
  203. &self.serialization
  204. }
  205. /// Return the serialization of this URL.
  206. ///
  207. /// This consumes the `Url` and takes ownership of the `String` stored in it.
  208. #[inline]
  209. pub fn into_string(self) -> String {
  210. self.serialization
  211. }
  212. /// For internal testing, not part of the public API.
  213. ///
  214. /// Methods of the `Url` struct assume a number of invariants.
  215. /// This checks each of these invariants and panic if one is not met.
  216. /// This is for testing rust-url itself.
  217. #[doc(hidden)]
  218. pub fn assert_invariants(&self) {
  219. macro_rules! assert {
  220. ($x: expr) => {
  221. if !$x {
  222. panic!("!( {} ) for URL {:?}", stringify!($x), self.serialization)
  223. }
  224. }
  225. }
  226. macro_rules! assert_eq {
  227. ($a: expr, $b: expr) => {
  228. {
  229. let a = $a;
  230. let b = $b;
  231. if a != b {
  232. panic!("{:?} != {:?} ({} != {}) for URL {:?}",
  233. a, b, stringify!($a), stringify!($b), self.serialization)
  234. }
  235. }
  236. }
  237. }
  238. assert!(self.scheme_end >= 1);
  239. assert!(matches!(self.byte_at(0), b'a'...b'z' | b'A'...b'Z'));
  240. assert!(self.slice(1..self.scheme_end).chars()
  241. .all(|c| matches!(c, 'a'...'z' | 'A'...'Z' | '0'...'9' | '+' | '-' | '.')));
  242. assert_eq!(self.byte_at(self.scheme_end), b':');
  243. if self.slice(self.scheme_end + 1 ..).starts_with("//") {
  244. // URL with authority
  245. match self.byte_at(self.username_end) {
  246. b':' => {
  247. assert!(self.host_start >= self.username_end + 2);
  248. assert_eq!(self.byte_at(self.host_start - 1), b'@');
  249. }
  250. b'@' => assert!(self.host_start == self.username_end + 1),
  251. _ => assert_eq!(self.username_end, self.scheme_end + 3),
  252. }
  253. assert!(self.host_start >= self.username_end);
  254. assert!(self.host_end >= self.host_start);
  255. let host_str = self.slice(self.host_start..self.host_end);
  256. match self.host {
  257. HostInternal::None => assert_eq!(host_str, ""),
  258. HostInternal::Ipv4(address) => assert_eq!(host_str, address.to_string()),
  259. HostInternal::Ipv6(address) => assert_eq!(host_str, format!("[{}]", address)),
  260. HostInternal::Domain => {
  261. if SchemeType::from(self.scheme()).is_special() {
  262. assert!(!host_str.is_empty())
  263. }
  264. }
  265. }
  266. if self.path_start == self.host_end {
  267. assert_eq!(self.port, None);
  268. } else {
  269. assert_eq!(self.byte_at(self.host_end), b':');
  270. let port_str = self.slice(self.host_end + 1..self.path_start);
  271. assert_eq!(self.port, Some(port_str.parse::<u16>().unwrap()));
  272. }
  273. assert_eq!(self.byte_at(self.path_start), b'/');
  274. } else {
  275. // Anarchist URL (no authority)
  276. assert_eq!(self.username_end, self.scheme_end + 1);
  277. assert_eq!(self.host_start, self.scheme_end + 1);
  278. assert_eq!(self.host_end, self.scheme_end + 1);
  279. assert_eq!(self.host, HostInternal::None);
  280. assert_eq!(self.port, None);
  281. assert_eq!(self.path_start, self.scheme_end + 1);
  282. }
  283. if let Some(start) = self.query_start {
  284. assert!(start > self.path_start);
  285. assert_eq!(self.byte_at(start), b'?');
  286. }
  287. if let Some(start) = self.fragment_start {
  288. assert!(start > self.path_start);
  289. assert_eq!(self.byte_at(start), b'#');
  290. }
  291. if let (Some(query_start), Some(fragment_start)) = (self.query_start, self.fragment_start) {
  292. assert!(fragment_start > query_start);
  293. }
  294. let other = Url::parse(self.as_str()).unwrap();
  295. assert_eq!(&self.serialization, &other.serialization);
  296. assert_eq!(self.scheme_end, other.scheme_end);
  297. assert_eq!(self.username_end, other.username_end);
  298. assert_eq!(self.host_start, other.host_start);
  299. assert_eq!(self.host_end, other.host_end);
  300. assert!(self.host == other.host ||
  301. // XXX No host round-trips to empty host.
  302. // See https://github.com/whatwg/url/issues/79
  303. (self.host_str(), other.host_str()) == (None, Some("")));
  304. assert_eq!(self.port, other.port);
  305. assert_eq!(self.path_start, other.path_start);
  306. assert_eq!(self.query_start, other.query_start);
  307. assert_eq!(self.fragment_start, other.fragment_start);
  308. }
  309. /// Return the origin of this URL (https://url.spec.whatwg.org/#origin)
  310. ///
  311. /// Note: this return an opaque origin for `file:` URLs, which causes
  312. /// `url.origin() != url.origin()`.
  313. ///
  314. /// # Examples
  315. ///
  316. /// URL with `ftp` scheme:
  317. ///
  318. /// ```rust
  319. /// use url::{Host, Origin, Url};
  320. ///
  321. /// let url = Url::parse("ftp://example.com/foo").unwrap();
  322. /// assert_eq!(url.origin(),
  323. /// Origin::Tuple("ftp".into(),
  324. /// Host::Domain("example.com".into()),
  325. /// 21));
  326. /// ```
  327. ///
  328. /// URL with `blob` scheme:
  329. ///
  330. /// ```rust
  331. /// use url::{Host, Origin, Url};
  332. ///
  333. /// let url = Url::parse("blob:https://example.com/foo").unwrap();
  334. /// assert_eq!(url.origin(),
  335. /// Origin::Tuple("https".into(),
  336. /// Host::Domain("example.com".into()),
  337. /// 443));
  338. /// ```
  339. ///
  340. /// URL with `file` scheme:
  341. ///
  342. /// ```rust
  343. /// use url::{Host, Origin, Url};
  344. ///
  345. /// let url = Url::parse("file:///tmp/foo").unwrap();
  346. /// assert!(!url.origin().is_tuple());
  347. ///
  348. /// let other_url = Url::parse("file:///tmp/foo").unwrap();
  349. /// assert!(url.origin() != other_url.origin());
  350. /// ```
  351. ///
  352. /// URL with other scheme:
  353. ///
  354. /// ```rust
  355. /// use url::{Host, Origin, Url};
  356. ///
  357. /// let url = Url::parse("foo:bar").unwrap();
  358. /// assert!(!url.origin().is_tuple());
  359. /// ```
  360. #[inline]
  361. pub fn origin(&self) -> Origin {
  362. origin::url_origin(self)
  363. }
  364. /// Return the scheme of this URL, lower-cased, as an ASCII string without the ':' delimiter.
  365. #[inline]
  366. pub fn scheme(&self) -> &str {
  367. self.slice(..self.scheme_end)
  368. }
  369. /// Return whether the URL has an 'authority',
  370. /// which can contain a username, password, host, and port number.
  371. ///
  372. /// URLs that do *not* are either path-only like `unix:/run/foo.socket`
  373. /// or cannot-be-a-base like `data:text/plain,Stuff`.
  374. #[inline]
  375. pub fn has_authority(&self) -> bool {
  376. debug_assert!(self.byte_at(self.scheme_end) == b':');
  377. self.slice(self.scheme_end..).starts_with("://")
  378. }
  379. /// Return whether this URL is a cannot-be-a-base URL,
  380. /// meaning that parsing a relative URL string with this URL as the base will return an error.
  381. ///
  382. /// This is the case if the scheme and `:` delimiter are not followed by a `/` slash,
  383. /// as is typically the case of `data:` and `mailto:` URLs.
  384. #[inline]
  385. pub fn cannot_be_a_base(&self) -> bool {
  386. self.byte_at(self.path_start) != b'/'
  387. }
  388. /// Return the username for this URL (typically the empty string)
  389. /// as a percent-encoded ASCII string.
  390. ///
  391. /// # Examples
  392. ///
  393. /// ```
  394. /// use url::Url;
  395. ///
  396. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  397. /// assert_eq!(url.username(), "rms");
  398. ///
  399. /// let url = Url::parse("https://example.com").unwrap();
  400. /// assert_eq!(url.username(), "");
  401. /// ```
  402. pub fn username(&self) -> &str {
  403. if self.has_authority() {
  404. self.slice(self.scheme_end + ("://".len() as u32)..self.username_end)
  405. } else {
  406. ""
  407. }
  408. }
  409. /// Return the password for this URL, if any, as a percent-encoded ASCII string.
  410. pub fn password(&self) -> Option<&str> {
  411. // This ':' is not the one marking a port number since a host can not be empty.
  412. // (Except for file: URLs, which do not have port numbers.)
  413. if self.has_authority() && self.byte_at(self.username_end) == b':' {
  414. debug_assert!(self.byte_at(self.host_start - 1) == b'@');
  415. Some(self.slice(self.username_end + 1..self.host_start - 1))
  416. } else {
  417. None
  418. }
  419. }
  420. /// Equivalent to `url.host().is_some()`.
  421. pub fn has_host(&self) -> bool {
  422. !matches!(self.host, HostInternal::None)
  423. }
  424. /// Return the string representation of the host (domain or IP address) for this URL, if any.
  425. ///
  426. /// Non-ASCII domains are punycode-encoded per IDNA.
  427. /// IPv6 addresses are given between `[` and `]` brackets.
  428. ///
  429. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  430. /// don’t have a host.
  431. ///
  432. /// See also the `host` method.
  433. pub fn host_str(&self) -> Option<&str> {
  434. if self.has_host() {
  435. Some(self.slice(self.host_start..self.host_end))
  436. } else {
  437. None
  438. }
  439. }
  440. /// Return the parsed representation of the host for this URL.
  441. /// Non-ASCII domain labels are punycode-encoded per IDNA.
  442. ///
  443. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  444. /// don’t have a host.
  445. ///
  446. /// See also the `host_str` method.
  447. pub fn host(&self) -> Option<Host<&str>> {
  448. match self.host {
  449. HostInternal::None => None,
  450. HostInternal::Domain => Some(Host::Domain(self.slice(self.host_start..self.host_end))),
  451. HostInternal::Ipv4(address) => Some(Host::Ipv4(address)),
  452. HostInternal::Ipv6(address) => Some(Host::Ipv6(address)),
  453. }
  454. }
  455. /// If this URL has a host and it is a domain name (not an IP address), return it.
  456. pub fn domain(&self) -> Option<&str> {
  457. match self.host {
  458. HostInternal::Domain => Some(self.slice(self.host_start..self.host_end)),
  459. _ => None,
  460. }
  461. }
  462. /// Return the port number for this URL, if any.
  463. #[inline]
  464. pub fn port(&self) -> Option<u16> {
  465. self.port
  466. }
  467. /// Return the port number for this URL, or the default port number if it is known.
  468. ///
  469. /// This method only knows the default port number
  470. /// of the `http`, `https`, `ws`, `wss`, `ftp`, and `gopher` schemes.
  471. ///
  472. /// For URLs in these schemes, this method always returns `Some(_)`.
  473. /// For other schemes, it is the same as `Url::port()`.
  474. #[inline]
  475. pub fn port_or_known_default(&self) -> Option<u16> {
  476. self.port.or_else(|| parser::default_port(self.scheme()))
  477. }
  478. /// If the URL has a host, return something that implements `ToSocketAddrs`.
  479. ///
  480. /// If the URL has no port number and the scheme’s default port number is not known
  481. /// (see `Url::port_or_known_default`),
  482. /// the closure is called to obtain a port number.
  483. /// Typically, this closure can match on the result `Url::scheme`
  484. /// to have per-scheme default port numbers,
  485. /// and panic for schemes it’s not prepared to handle.
  486. /// For example:
  487. ///
  488. /// ```rust
  489. /// # use url::Url;
  490. /// # use std::net::TcpStream;
  491. /// # use std::io;
  492. ///
  493. /// fn connect(url: &Url) -> io::Result<TcpStream> {
  494. /// TcpStream::connect(try!(url.with_default_port(default_port)))
  495. /// }
  496. ///
  497. /// fn default_port(url: &Url) -> Result<u16, ()> {
  498. /// match url.scheme() {
  499. /// "git" => Ok(9418),
  500. /// "git+ssh" => Ok(22),
  501. /// "git+https" => Ok(443),
  502. /// "git+http" => Ok(80),
  503. /// _ => Err(()),
  504. /// }
  505. /// }
  506. /// ```
  507. pub fn with_default_port<F>(&self, f: F) -> io::Result<HostAndPort<&str>>
  508. where F: FnOnce(&Url) -> Result<u16, ()> {
  509. Ok(HostAndPort {
  510. host: try!(self.host()
  511. .ok_or(())
  512. .or_else(|()| io_error("URL has no host"))),
  513. port: try!(self.port_or_known_default()
  514. .ok_or(())
  515. .or_else(|()| f(self))
  516. .or_else(|()| io_error("URL has no port number")))
  517. })
  518. }
  519. /// Return the path for this URL, as a percent-encoded ASCII string.
  520. /// For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with '/'.
  521. /// For other URLs, this starts with a '/' slash
  522. /// and continues with slash-separated path segments.
  523. pub fn path(&self) -> &str {
  524. match (self.query_start, self.fragment_start) {
  525. (None, None) => self.slice(self.path_start..),
  526. (Some(next_component_start), _) |
  527. (None, Some(next_component_start)) => {
  528. self.slice(self.path_start..next_component_start)
  529. }
  530. }
  531. }
  532. /// Unless this URL is cannot-be-a-base,
  533. /// return an iterator of '/' slash-separated path segments,
  534. /// each as a percent-encoded ASCII string.
  535. ///
  536. /// Return `None` for cannot-be-a-base URLs.
  537. ///
  538. /// When `Some` is returned, the iterator always contains at least one string
  539. /// (which may be empty).
  540. pub fn path_segments(&self) -> Option<str::Split<char>> {
  541. let path = self.path();
  542. if path.starts_with('/') {
  543. Some(path[1..].split('/'))
  544. } else {
  545. None
  546. }
  547. }
  548. /// Return this URL’s query string, if any, as a percent-encoded ASCII string.
  549. pub fn query(&self) -> Option<&str> {
  550. match (self.query_start, self.fragment_start) {
  551. (None, _) => None,
  552. (Some(query_start), None) => {
  553. debug_assert!(self.byte_at(query_start) == b'?');
  554. Some(self.slice(query_start + 1..))
  555. }
  556. (Some(query_start), Some(fragment_start)) => {
  557. debug_assert!(self.byte_at(query_start) == b'?');
  558. Some(self.slice(query_start + 1..fragment_start))
  559. }
  560. }
  561. }
  562. /// Parse the URL’s query string, if any, as `application/x-www-form-urlencoded`
  563. /// and return an iterator of (key, value) pairs.
  564. #[inline]
  565. pub fn query_pairs(&self) -> form_urlencoded::Parse {
  566. form_urlencoded::parse(self.query().unwrap_or("").as_bytes())
  567. }
  568. /// Return this URL’s fragment identifier, if any.
  569. ///
  570. /// **Note:** the parser did *not* percent-encode this component,
  571. /// but the input may have been percent-encoded already.
  572. pub fn fragment(&self) -> Option<&str> {
  573. self.fragment_start.map(|start| {
  574. debug_assert!(self.byte_at(start) == b'#');
  575. self.slice(start + 1..)
  576. })
  577. }
  578. fn mutate<F: FnOnce(&mut Parser) -> R, R>(&mut self, f: F) -> R {
  579. let mut parser = Parser::for_setter(mem::replace(&mut self.serialization, String::new()));
  580. let result = f(&mut parser);
  581. self.serialization = parser.serialization;
  582. result
  583. }
  584. /// Change this URL’s fragment identifier.
  585. pub fn set_fragment(&mut self, fragment: Option<&str>) {
  586. // Remove any previous fragment
  587. if let Some(start) = self.fragment_start {
  588. debug_assert!(self.byte_at(start) == b'#');
  589. self.serialization.truncate(start as usize);
  590. }
  591. // Write the new one
  592. if let Some(input) = fragment {
  593. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  594. self.serialization.push('#');
  595. self.mutate(|parser| parser.parse_fragment(parser::Input::new(input)))
  596. } else {
  597. self.fragment_start = None
  598. }
  599. }
  600. fn take_fragment(&mut self) -> Option<String> {
  601. self.fragment_start.take().map(|start| {
  602. debug_assert!(self.byte_at(start) == b'#');
  603. let fragment = self.slice(start + 1..).to_owned();
  604. self.serialization.truncate(start as usize);
  605. fragment
  606. })
  607. }
  608. fn restore_already_parsed_fragment(&mut self, fragment: Option<String>) {
  609. if let Some(ref fragment) = fragment {
  610. assert!(self.fragment_start.is_none());
  611. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  612. self.serialization.push('#');
  613. self.serialization.push_str(fragment);
  614. }
  615. }
  616. /// Change this URL’s query string.
  617. pub fn set_query(&mut self, query: Option<&str>) {
  618. let fragment = self.take_fragment();
  619. // Remove any previous query
  620. if let Some(start) = self.query_start.take() {
  621. debug_assert!(self.byte_at(start) == b'?');
  622. self.serialization.truncate(start as usize);
  623. }
  624. // Write the new query, if any
  625. if let Some(input) = query {
  626. self.query_start = Some(to_u32(self.serialization.len()).unwrap());
  627. self.serialization.push('?');
  628. let scheme_end = self.scheme_end;
  629. self.mutate(|parser| parser.parse_query(scheme_end, parser::Input::new(input)));
  630. }
  631. self.restore_already_parsed_fragment(fragment);
  632. }
  633. /// Manipulate this URL’s query string, viewed as a sequence of name/value pairs
  634. /// in `application/x-www-form-urlencoded` syntax.
  635. ///
  636. /// The return value has a method-chaining API:
  637. ///
  638. /// ```rust
  639. /// # use url::Url;
  640. /// let mut url = Url::parse("https://example.net?lang=fr#nav").unwrap();
  641. /// assert_eq!(url.query(), Some("lang=fr"));
  642. ///
  643. /// url.query_pairs_mut().append_pair("foo", "bar");
  644. /// assert_eq!(url.query(), Some("lang=fr&foo=bar"));
  645. /// assert_eq!(url.as_str(), "https://example.net/?lang=fr&foo=bar#nav");
  646. ///
  647. /// url.query_pairs_mut()
  648. /// .clear()
  649. /// .append_pair("foo", "bar & baz")
  650. /// .append_pair("saisons", "Été+hiver");
  651. /// assert_eq!(url.query(), Some("foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver"));
  652. /// assert_eq!(url.as_str(),
  653. /// "https://example.net/?foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver#nav");
  654. /// ```
  655. ///
  656. /// Note: `url.query_pairs_mut().clear();` is equivalent to `url.set_query(Some(""))`,
  657. /// not `url.set_query(None)`.
  658. ///
  659. /// The state of `Url` is unspecified if this return value is leaked without being dropped.
  660. pub fn query_pairs_mut(&mut self) -> form_urlencoded::Serializer<UrlQuery> {
  661. let fragment = self.take_fragment();
  662. let query_start;
  663. if let Some(start) = self.query_start {
  664. debug_assert!(self.byte_at(start) == b'?');
  665. query_start = start as usize;
  666. } else {
  667. query_start = self.serialization.len();
  668. self.query_start = Some(to_u32(query_start).unwrap());
  669. self.serialization.push('?');
  670. }
  671. let query = UrlQuery { url: self, fragment: fragment };
  672. form_urlencoded::Serializer::for_suffix(query, query_start + "?".len())
  673. }
  674. fn take_after_path(&mut self) -> (u32, String) {
  675. match (self.query_start, self.fragment_start) {
  676. (Some(i), _) | (None, Some(i)) => (i, self.slice(i..).to_owned()),
  677. (None, None) => (to_u32(self.serialization.len()).unwrap(), String::new())
  678. }
  679. }
  680. /// Change this URL’s path.
  681. pub fn set_path(&mut self, mut path: &str) {
  682. let (old_after_path_pos, after_path) = self.take_after_path();
  683. let cannot_be_a_base = self.cannot_be_a_base();
  684. let scheme_type = SchemeType::from(self.scheme());
  685. self.serialization.truncate(self.path_start as usize);
  686. self.mutate(|parser| {
  687. if cannot_be_a_base {
  688. if path.starts_with('/') {
  689. parser.serialization.push_str("%2F");
  690. path = &path[1..];
  691. }
  692. parser.parse_cannot_be_a_base_path(parser::Input::new(path));
  693. } else {
  694. let mut has_host = true; // FIXME
  695. parser.parse_path_start(scheme_type, &mut has_host, parser::Input::new(path));
  696. }
  697. });
  698. self.restore_after_path(old_after_path_pos, &after_path);
  699. }
  700. /// Return an object with methods to manipulate this URL’s path segments.
  701. ///
  702. /// Return `Err(())` if this URl is cannot-be-a-base.
  703. pub fn path_segments_mut(&mut self) -> Result<PathSegmentsMut, ()> {
  704. if self.cannot_be_a_base() {
  705. Err(())
  706. } else {
  707. Ok(path_segments::new(self))
  708. }
  709. }
  710. fn restore_after_path(&mut self, old_after_path_position: u32, after_path: &str) {
  711. let new_after_path_position = to_u32(self.serialization.len()).unwrap();
  712. let adjust = |index: &mut u32| {
  713. *index -= old_after_path_position;
  714. *index += new_after_path_position;
  715. };
  716. if let Some(ref mut index) = self.query_start { adjust(index) }
  717. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  718. self.serialization.push_str(after_path)
  719. }
  720. /// Change this URL’s port number.
  721. ///
  722. /// If this URL is cannot-be-a-base, does not have a host, or has the `file` scheme;
  723. /// do nothing and return `Err`.
  724. pub fn set_port(&mut self, mut port: Option<u16>) -> Result<(), ()> {
  725. if !self.has_host() || self.scheme() == "file" {
  726. return Err(())
  727. }
  728. if port.is_some() && port == parser::default_port(self.scheme()) {
  729. port = None
  730. }
  731. self.set_port_internal(port);
  732. Ok(())
  733. }
  734. fn set_port_internal(&mut self, port: Option<u16>) {
  735. match (self.port, port) {
  736. (None, None) => {}
  737. (Some(_), None) => {
  738. self.serialization.drain(self.host_end as usize .. self.path_start as usize);
  739. let offset = self.path_start - self.host_end;
  740. self.path_start = self.host_end;
  741. if let Some(ref mut index) = self.query_start { *index -= offset }
  742. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  743. }
  744. (Some(old), Some(new)) if old == new => {}
  745. (_, Some(new)) => {
  746. let path_and_after = self.slice(self.path_start..).to_owned();
  747. self.serialization.truncate(self.host_end as usize);
  748. write!(&mut self.serialization, ":{}", new).unwrap();
  749. let old_path_start = self.path_start;
  750. let new_path_start = to_u32(self.serialization.len()).unwrap();
  751. self.path_start = new_path_start;
  752. let adjust = |index: &mut u32| {
  753. *index -= old_path_start;
  754. *index += new_path_start;
  755. };
  756. if let Some(ref mut index) = self.query_start { adjust(index) }
  757. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  758. self.serialization.push_str(&path_and_after);
  759. }
  760. }
  761. self.port = port;
  762. }
  763. /// Change this URL’s host.
  764. ///
  765. /// If this URL is cannot-be-a-base or there is an error parsing the given `host`,
  766. /// do nothing and return `Err`.
  767. ///
  768. /// Removing the host (calling this with `None`)
  769. /// will also remove any username, password, and port number.
  770. pub fn set_host(&mut self, host: Option<&str>) -> Result<(), ParseError> {
  771. if self.cannot_be_a_base() {
  772. return Err(ParseError::SetHostOnCannotBeABaseUrl)
  773. }
  774. if let Some(host) = host {
  775. self.set_host_internal(try!(Host::parse(host)), None)
  776. } else if self.has_host() {
  777. debug_assert!(self.byte_at(self.scheme_end) == b':');
  778. debug_assert!(self.byte_at(self.path_start) == b'/');
  779. let new_path_start = self.scheme_end + 1;
  780. self.serialization.drain(self.path_start as usize..new_path_start as usize);
  781. let offset = self.path_start - new_path_start;
  782. self.path_start = new_path_start;
  783. self.username_end = new_path_start;
  784. self.host_start = new_path_start;
  785. self.host_end = new_path_start;
  786. self.port = None;
  787. if let Some(ref mut index) = self.query_start { *index -= offset }
  788. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  789. }
  790. Ok(())
  791. }
  792. /// opt_new_port: None means leave unchanged, Some(None) means remove any port number.
  793. fn set_host_internal(&mut self, host: Host<String>, opt_new_port: Option<Option<u16>>) {
  794. let old_suffix_pos = if opt_new_port.is_some() { self.path_start } else { self.host_end };
  795. let suffix = self.slice(old_suffix_pos..).to_owned();
  796. self.serialization.truncate(self.host_start as usize);
  797. if !self.has_authority() {
  798. debug_assert!(self.slice(self.scheme_end..self.host_start) == ":");
  799. debug_assert!(self.username_end == self.host_start);
  800. self.serialization.push('/');
  801. self.serialization.push('/');
  802. self.username_end += 2;
  803. self.host_start += 2;
  804. }
  805. write!(&mut self.serialization, "{}", host).unwrap();
  806. self.host_end = to_u32(self.serialization.len()).unwrap();
  807. self.host = host.into();
  808. if let Some(new_port) = opt_new_port {
  809. self.port = new_port;
  810. if let Some(port) = new_port {
  811. write!(&mut self.serialization, ":{}", port).unwrap();
  812. }
  813. }
  814. let new_suffix_pos = to_u32(self.serialization.len()).unwrap();
  815. self.serialization.push_str(&suffix);
  816. let adjust = |index: &mut u32| {
  817. *index -= old_suffix_pos;
  818. *index += new_suffix_pos;
  819. };
  820. adjust(&mut self.path_start);
  821. if let Some(ref mut index) = self.query_start { adjust(index) }
  822. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  823. }
  824. /// Change this URL’s host to the given IP address.
  825. ///
  826. /// If this URL is cannot-be-a-base, do nothing and return `Err`.
  827. ///
  828. /// Compared to `Url::set_host`, this skips the host parser.
  829. pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ()> {
  830. if self.cannot_be_a_base() {
  831. return Err(())
  832. }
  833. let address = match address {
  834. IpAddr::V4(address) => Host::Ipv4(address),
  835. IpAddr::V6(address) => Host::Ipv6(address),
  836. };
  837. self.set_host_internal(address, None);
  838. Ok(())
  839. }
  840. /// Change this URL’s password.
  841. ///
  842. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  843. pub fn set_password(&mut self, password: Option<&str>) -> Result<(), ()> {
  844. if !self.has_host() {
  845. return Err(())
  846. }
  847. if let Some(password) = password {
  848. let host_and_after = self.slice(self.host_start..).to_owned();
  849. self.serialization.truncate(self.username_end as usize);
  850. self.serialization.push(':');
  851. self.serialization.extend(utf8_percent_encode(password, USERINFO_ENCODE_SET));
  852. self.serialization.push('@');
  853. let old_host_start = self.host_start;
  854. let new_host_start = to_u32(self.serialization.len()).unwrap();
  855. let adjust = |index: &mut u32| {
  856. *index -= old_host_start;
  857. *index += new_host_start;
  858. };
  859. self.host_start = new_host_start;
  860. adjust(&mut self.host_end);
  861. adjust(&mut self.path_start);
  862. if let Some(ref mut index) = self.query_start { adjust(index) }
  863. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  864. self.serialization.push_str(&host_and_after);
  865. } else if self.byte_at(self.username_end) == b':' { // If there is a password to remove
  866. let has_username_or_password = self.byte_at(self.host_start - 1) == b'@';
  867. debug_assert!(has_username_or_password);
  868. let username_start = self.scheme_end + 3;
  869. let empty_username = username_start == self.username_end;
  870. let start = self.username_end; // Remove the ':'
  871. let end = if empty_username {
  872. self.host_start // Remove the '@' as well
  873. } else {
  874. self.host_start - 1 // Keep the '@' to separate the username from the host
  875. };
  876. self.serialization.drain(start as usize .. end as usize);
  877. let offset = end - start;
  878. self.host_start -= offset;
  879. self.host_end -= offset;
  880. self.path_start -= offset;
  881. if let Some(ref mut index) = self.query_start { *index -= offset }
  882. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  883. }
  884. Ok(())
  885. }
  886. /// Change this URL’s username.
  887. ///
  888. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  889. pub fn set_username(&mut self, username: &str) -> Result<(), ()> {
  890. if !self.has_host() {
  891. return Err(())
  892. }
  893. let username_start = self.scheme_end + 3;
  894. debug_assert!(self.slice(self.scheme_end..username_start) == "://");
  895. if self.slice(username_start..self.username_end) == username {
  896. return Ok(())
  897. }
  898. let after_username = self.slice(self.username_end..).to_owned();
  899. self.serialization.truncate(username_start as usize);
  900. self.serialization.extend(utf8_percent_encode(username, USERINFO_ENCODE_SET));
  901. let mut removed_bytes = self.username_end;
  902. self.username_end = to_u32(self.serialization.len()).unwrap();
  903. let mut added_bytes = self.username_end;
  904. let new_username_is_empty = self.username_end == username_start;
  905. match (new_username_is_empty, after_username.chars().next()) {
  906. (true, Some('@')) => {
  907. removed_bytes += 1;
  908. self.serialization.push_str(&after_username[1..]);
  909. }
  910. (false, Some('@')) | (_, Some(':')) | (true, _) => {
  911. self.serialization.push_str(&after_username);
  912. }
  913. (false, _) => {
  914. added_bytes += 1;
  915. self.serialization.push('@');
  916. self.serialization.push_str(&after_username);
  917. }
  918. }
  919. let adjust = |index: &mut u32| {
  920. *index -= removed_bytes;
  921. *index += added_bytes;
  922. };
  923. adjust(&mut self.host_start);
  924. adjust(&mut self.host_end);
  925. adjust(&mut self.path_start);
  926. if let Some(ref mut index) = self.query_start { adjust(index) }
  927. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  928. Ok(())
  929. }
  930. /// Change this URL’s scheme.
  931. ///
  932. /// Do nothing and return `Err` if:
  933. /// * The new scheme is not in `[a-zA-Z][a-zA-Z0-9+.-]+`
  934. /// * This URL is cannot-be-a-base and the new scheme is one of
  935. /// `http`, `https`, `ws`, `wss`, `ftp`, or `gopher`
  936. pub fn set_scheme(&mut self, scheme: &str) -> Result<(), ()> {
  937. let mut parser = Parser::for_setter(String::new());
  938. let remaining = try!(parser.parse_scheme(parser::Input::new(scheme)));
  939. if !remaining.is_empty() ||
  940. (!self.has_host() && SchemeType::from(&parser.serialization).is_special()) {
  941. return Err(())
  942. }
  943. let old_scheme_end = self.scheme_end;
  944. let new_scheme_end = to_u32(parser.serialization.len()).unwrap();
  945. let adjust = |index: &mut u32| {
  946. *index -= old_scheme_end;
  947. *index += new_scheme_end;
  948. };
  949. self.scheme_end = new_scheme_end;
  950. adjust(&mut self.username_end);
  951. adjust(&mut self.host_start);
  952. adjust(&mut self.host_end);
  953. adjust(&mut self.path_start);
  954. if let Some(ref mut index) = self.query_start { adjust(index) }
  955. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  956. parser.serialization.push_str(self.slice(old_scheme_end..));
  957. self.serialization = parser.serialization;
  958. Ok(())
  959. }
  960. /// Convert a file name as `std::path::Path` into an URL in the `file` scheme.
  961. ///
  962. /// This returns `Err` if the given path is not absolute or,
  963. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`).
  964. pub fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  965. let mut serialization = "file://".to_owned();
  966. let path_start = serialization.len() as u32;
  967. try!(path_to_file_url_segments(path.as_ref(), &mut serialization));
  968. Ok(Url {
  969. serialization: serialization,
  970. scheme_end: "file".len() as u32,
  971. username_end: path_start,
  972. host_start: path_start,
  973. host_end: path_start,
  974. host: HostInternal::None,
  975. port: None,
  976. path_start: path_start,
  977. query_start: None,
  978. fragment_start: None,
  979. })
  980. }
  981. /// Convert a directory name as `std::path::Path` into an URL in the `file` scheme.
  982. ///
  983. /// This returns `Err` if the given path is not absolute or,
  984. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`).
  985. ///
  986. /// Compared to `from_file_path`, this ensure that URL’s the path has a trailing slash
  987. /// so that the entire path is considered when using this URL as a base URL.
  988. ///
  989. /// For example:
  990. ///
  991. /// * `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
  992. /// as the base URL is `file:///var/www/index.html`
  993. /// * `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www"))`
  994. /// as the base URL is `file:///var/index.html`, which might not be what was intended.
  995. ///
  996. /// Note that `std::path` does not consider trailing slashes significant
  997. /// and usually does not include them (e.g. in `Path::parent()`).
  998. pub fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  999. let mut url = try!(Url::from_file_path(path));
  1000. if !url.serialization.ends_with('/') {
  1001. url.serialization.push('/')
  1002. }
  1003. Ok(url)
  1004. }
  1005. /// Assuming the URL is in the `file` scheme or similar,
  1006. /// convert its path to an absolute `std::path::Path`.
  1007. ///
  1008. /// **Note:** This does not actually check the URL’s `scheme`,
  1009. /// and may give nonsensical results for other schemes.
  1010. /// It is the user’s responsibility to check the URL’s scheme before calling this.
  1011. ///
  1012. /// ```
  1013. /// # use url::Url;
  1014. /// # let url = Url::parse("file:///etc/passwd").unwrap();
  1015. /// let path = url.to_file_path();
  1016. /// ```
  1017. ///
  1018. /// Returns `Err` if the host is neither empty nor `"localhost"`,
  1019. /// or if `Path::new_opt()` returns `None`.
  1020. /// (That is, if the percent-decoded path contains a NUL byte or,
  1021. /// for a Windows path, is not UTF-8.)
  1022. #[inline]
  1023. pub fn to_file_path(&self) -> Result<PathBuf, ()> {
  1024. // FIXME: Figure out what to do w.r.t host.
  1025. if matches!(self.host(), None | Some(Host::Domain("localhost"))) {
  1026. if let Some(segments) = self.path_segments() {
  1027. return file_url_segments_to_pathbuf(segments)
  1028. }
  1029. }
  1030. Err(())
  1031. }
  1032. // Private helper methods:
  1033. #[inline]
  1034. fn slice<R>(&self, range: R) -> &str where R: RangeArg {
  1035. range.slice_of(&self.serialization)
  1036. }
  1037. #[inline]
  1038. fn byte_at(&self, i: u32) -> u8 {
  1039. self.serialization.as_bytes()[i as usize]
  1040. }
  1041. }
  1042. /// Return an error if `Url::host` or `Url::port_or_known_default` return `None`.
  1043. impl ToSocketAddrs for Url {
  1044. type Iter = SocketAddrs;
  1045. fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
  1046. try!(self.with_default_port(|_| Err(()))).to_socket_addrs()
  1047. }
  1048. }
  1049. /// Parse a string as an URL, without a base URL or encoding override.
  1050. impl str::FromStr for Url {
  1051. type Err = ParseError;
  1052. #[inline]
  1053. fn from_str(input: &str) -> Result<Url, ::ParseError> {
  1054. Url::parse(input)
  1055. }
  1056. }
  1057. /// Display the serialization of this URL.
  1058. impl fmt::Display for Url {
  1059. #[inline]
  1060. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  1061. fmt::Display::fmt(&self.serialization, formatter)
  1062. }
  1063. }
  1064. /// Debug the serialization of this URL.
  1065. impl fmt::Debug for Url {
  1066. #[inline]
  1067. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  1068. fmt::Debug::fmt(&self.serialization, formatter)
  1069. }
  1070. }
  1071. /// URLs compare like their serialization.
  1072. impl Eq for Url {}
  1073. /// URLs compare like their serialization.
  1074. impl PartialEq for Url {
  1075. #[inline]
  1076. fn eq(&self, other: &Self) -> bool {
  1077. self.serialization == other.serialization
  1078. }
  1079. }
  1080. /// URLs compare like their serialization.
  1081. impl Ord for Url {
  1082. #[inline]
  1083. fn cmp(&self, other: &Self) -> cmp::Ordering {
  1084. self.serialization.cmp(&other.serialization)
  1085. }
  1086. }
  1087. /// URLs compare like their serialization.
  1088. impl PartialOrd for Url {
  1089. #[inline]
  1090. fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
  1091. self.serialization.partial_cmp(&other.serialization)
  1092. }
  1093. }
  1094. /// URLs hash like their serialization.
  1095. impl hash::Hash for Url {
  1096. #[inline]
  1097. fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
  1098. hash::Hash::hash(&self.serialization, state)
  1099. }
  1100. }
  1101. /// Return the serialization of this URL.
  1102. impl AsRef<str> for Url {
  1103. #[inline]
  1104. fn as_ref(&self) -> &str {
  1105. &self.serialization
  1106. }
  1107. }
  1108. trait RangeArg {
  1109. fn slice_of<'a>(&self, s: &'a str) -> &'a str;
  1110. }
  1111. impl RangeArg for Range<u32> {
  1112. #[inline]
  1113. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  1114. &s[self.start as usize .. self.end as usize]
  1115. }
  1116. }
  1117. impl RangeArg for RangeFrom<u32> {
  1118. #[inline]
  1119. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  1120. &s[self.start as usize ..]
  1121. }
  1122. }
  1123. impl RangeArg for RangeTo<u32> {
  1124. #[inline]
  1125. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  1126. &s[.. self.end as usize]
  1127. }
  1128. }
  1129. #[cfg(feature="rustc-serialize")]
  1130. impl rustc_serialize::Encodable for Url {
  1131. fn encode<S: rustc_serialize::Encoder>(&self, encoder: &mut S) -> Result<(), S::Error> {
  1132. encoder.emit_str(self.as_str())
  1133. }
  1134. }
  1135. #[cfg(feature="rustc-serialize")]
  1136. impl rustc_serialize::Decodable for Url {
  1137. fn decode<D: rustc_serialize::Decoder>(decoder: &mut D) -> Result<Url, D::Error> {
  1138. Url::parse(&*try!(decoder.read_str())).map_err(|error| {
  1139. decoder.error(&format!("URL parsing error: {}", error))
  1140. })
  1141. }
  1142. }
  1143. /// Serializes this URL into a `serde` stream.
  1144. ///
  1145. /// This implementation is only available if the `serde` Cargo feature is enabled.
  1146. #[cfg(feature="serde")]
  1147. impl serde::Serialize for Url {
  1148. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
  1149. format!("{}", self).serialize(serializer)
  1150. }
  1151. }
  1152. /// Deserializes this URL from a `serde` stream.
  1153. ///
  1154. /// This implementation is only available if the `serde` Cargo feature is enabled.
  1155. #[cfg(feature="serde")]
  1156. impl serde::Deserialize for Url {
  1157. fn deserialize<D>(deserializer: &mut D) -> Result<Url, D::Error> where D: serde::Deserializer {
  1158. let string_representation: String = try!(serde::Deserialize::deserialize(deserializer));
  1159. Ok(Url::parse(&string_representation).unwrap())
  1160. }
  1161. }
  1162. #[cfg(unix)]
  1163. fn path_to_file_url_segments(path: &Path, serialization: &mut String) -> Result<(), ()> {
  1164. use std::os::unix::prelude::OsStrExt;
  1165. if !path.is_absolute() {
  1166. return Err(())
  1167. }
  1168. let mut empty = true;
  1169. // skip the root component
  1170. for component in path.components().skip(1) {
  1171. empty = false;
  1172. serialization.push('/');
  1173. serialization.extend(percent_encode(
  1174. component.as_os_str().as_bytes(), PATH_SEGMENT_ENCODE_SET));
  1175. }
  1176. if empty {
  1177. // An URL’s path must not be empty.
  1178. serialization.push('/');
  1179. }
  1180. Ok(())
  1181. }
  1182. #[cfg(windows)]
  1183. fn path_to_file_url_segments(path: &Path, serialization: &mut String) -> Result<(), ()> {
  1184. path_to_file_url_segments_windows(path, serialization)
  1185. }
  1186. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  1187. #[cfg_attr(not(windows), allow(dead_code))]
  1188. fn path_to_file_url_segments_windows(path: &Path, serialization: &mut String) -> Result<(), ()> {
  1189. use std::path::{Prefix, Component};
  1190. if !path.is_absolute() {
  1191. return Err(())
  1192. }
  1193. let mut components = path.components();
  1194. let disk = match components.next() {
  1195. Some(Component::Prefix(ref p)) => match p.kind() {
  1196. Prefix::Disk(byte) => byte,
  1197. Prefix::VerbatimDisk(byte) => byte,
  1198. _ => return Err(()),
  1199. },
  1200. // FIXME: do something with UNC and other prefixes?
  1201. _ => return Err(())
  1202. };
  1203. // Start with the prefix, e.g. "C:"
  1204. serialization.push('/');
  1205. serialization.push(disk as char);
  1206. serialization.push(':');
  1207. for component in components {
  1208. if component == Component::RootDir { continue }
  1209. // FIXME: somehow work with non-unicode?
  1210. let component = try!(component.as_os_str().to_str().ok_or(()));
  1211. serialization.push('/');
  1212. serialization.extend(percent_encode(component.as_bytes(), PATH_SEGMENT_ENCODE_SET));
  1213. }
  1214. Ok(())
  1215. }
  1216. #[cfg(unix)]
  1217. fn file_url_segments_to_pathbuf(segments: str::Split<char>) -> Result<PathBuf, ()> {
  1218. use std::ffi::OsStr;
  1219. use std::os::unix::prelude::OsStrExt;
  1220. use std::path::PathBuf;
  1221. let mut bytes = Vec::new();
  1222. for segment in segments {
  1223. bytes.push(b'/');
  1224. bytes.extend(percent_decode(segment.as_bytes()));
  1225. }
  1226. let os_str = OsStr::from_bytes(&bytes);
  1227. let path = PathBuf::from(os_str);
  1228. debug_assert!(path.is_absolute(),
  1229. "to_file_path() failed to produce an absolute Path");
  1230. Ok(path)
  1231. }
  1232. #[cfg(windows)]
  1233. fn file_url_segments_to_pathbuf(segments: str::Split<char>) -> Result<PathBuf, ()> {
  1234. file_url_segments_to_pathbuf_windows(segments)
  1235. }
  1236. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  1237. #[cfg_attr(not(windows), allow(dead_code))]
  1238. fn file_url_segments_to_pathbuf_windows(mut segments: str::Split<char>) -> Result<PathBuf, ()> {
  1239. let first = try!(segments.next().ok_or(()));
  1240. if first.len() != 2 || !first.starts_with(parser::ascii_alpha)
  1241. || first.as_bytes()[1] != b':' {
  1242. return Err(())
  1243. }
  1244. let mut string = first.to_owned();
  1245. for segment in segments {
  1246. string.push('\\');
  1247. // Currently non-unicode windows paths cannot be represented
  1248. match String::from_utf8(percent_decode(segment.as_bytes()).collect()) {
  1249. Ok(s) => string.push_str(&s),
  1250. Err(..) => return Err(()),
  1251. }
  1252. }
  1253. let path = PathBuf::from(string);
  1254. debug_assert!(path.is_absolute(),
  1255. "to_file_path() failed to produce an absolute Path");
  1256. Ok(path)
  1257. }
  1258. fn io_error<T>(reason: &str) -> io::Result<T> {
  1259. Err(io::Error::new(io::ErrorKind::InvalidData, reason))
  1260. }
  1261. /// Implementation detail of `Url::query_pairs_mut`. Typically not used directly.
  1262. pub struct UrlQuery<'a> {
  1263. url: &'a mut Url,
  1264. fragment: Option<String>,
  1265. }
  1266. impl<'a> Drop for UrlQuery<'a> {
  1267. fn drop(&mut self) {
  1268. self.url.restore_already_parsed_fragment(self.fragment.take())
  1269. }
  1270. }