lib.rs 45 KB

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