lib.rs 50 KB

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