lib.rs 50 KB

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