lib.rs 48 KB

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