lib.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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.non_relative());
  54. ```
  55. Some URLs are said to be "non-relative":
  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.non_relative());
  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. extern crate rustc_serialize;
  88. #[macro_use] extern crate matches;
  89. #[cfg(feature="serde_serialization")] extern crate serde;
  90. #[cfg(feature="heap_size")] #[macro_use] extern crate heapsize;
  91. extern crate idna;
  92. use host::HostInternal;
  93. use percent_encoding::{PATH_SEGMENT_ENCODE_SET, percent_encode_to};
  94. use std::cmp;
  95. use std::fmt;
  96. use std::hash;
  97. use std::ops::{Range, RangeFrom, RangeTo};
  98. use std::path::{Path, PathBuf};
  99. use std::str;
  100. pub use encoding::EncodingOverride;
  101. pub use origin::Origin;
  102. pub use host::Host;
  103. pub use parser::ParseError;
  104. pub use slicing::Position;
  105. mod encoding;
  106. mod host;
  107. mod idna_mapping;
  108. mod origin;
  109. mod parser;
  110. mod slicing;
  111. pub mod percent_encoding;
  112. pub mod form_urlencoded;
  113. /// A parsed URL record.
  114. #[derive(Clone)]
  115. #[cfg_attr(feature="heap_size", derive(HeapSizeOf))]
  116. pub struct Url {
  117. serialization: String,
  118. non_relative: bool,
  119. // Components
  120. scheme_end: u32, // Before ':'
  121. username_end: u32, // Before ':' (if a password is given) or '@' (if not)
  122. host_start: u32,
  123. host_end: u32,
  124. host: HostInternal,
  125. port: Option<u16>,
  126. path_start: u32, // Before initial '/' if !non_relative
  127. query_start: Option<u32>, // Before '?', unlike Position::QueryStart
  128. fragment_start: Option<u32>, // Before '#', unlike Position::FragmentStart
  129. }
  130. impl Url {
  131. /// Parse an absolute URL from a string.
  132. #[inline]
  133. pub fn parse(input: &str) -> Result<Url, ::ParseError> {
  134. Url::parse_with(input, None, EncodingOverride::utf8(), None)
  135. }
  136. /// Parse a string as an URL, with this URL as the base URL.
  137. #[inline]
  138. pub fn join(&self, input: &str) -> Result<Url, ::ParseError> {
  139. Url::parse_with(input, Some(self), EncodingOverride::utf8(), None)
  140. }
  141. /// The URL parser with all of its parameters.
  142. ///
  143. /// `encoding_override` is a legacy concept only relevant for HTML.
  144. /// When it’s not needed,
  145. /// `s.parse::<Url>()`, `Url::from_str(s)` and `url.join(s)` can be used instead.
  146. pub fn parse_with(input: &str,
  147. base_url: Option<&Url>,
  148. encoding_override: EncodingOverride,
  149. log_syntax_violation: Option<&Fn(&'static str)>)
  150. -> Result<Url, ::ParseError> {
  151. parser::Parser {
  152. serialization: String::with_capacity(input.len()),
  153. base_url: base_url,
  154. query_encoding_override: encoding_override,
  155. log_syntax_violation: log_syntax_violation,
  156. }.parse_url(input)
  157. }
  158. #[inline]
  159. pub fn as_str(&self) -> &str {
  160. &self.serialization
  161. }
  162. /// Return the scheme of this URL, as an ASCII string without the ':' delimiter.
  163. #[inline]
  164. pub fn scheme(&self) -> &str {
  165. self.slice(..self.scheme_end)
  166. }
  167. /// Return whether this URL is non-relative (typical of e.g. `data:` and `mailto:` URLs.)
  168. #[inline]
  169. pub fn non_relative(&self) -> bool {
  170. self.non_relative
  171. }
  172. /// Return the username for this URL (typically the empty string)
  173. /// as a percent-encoded ASCII string.
  174. pub fn username(&self) -> &str {
  175. if self.slice(self.scheme_end..).starts_with("://") {
  176. self.slice(self.scheme_end + 3..self.username_end)
  177. } else {
  178. ""
  179. }
  180. }
  181. /// Return the password for this URL, if any, as a percent-encoded ASCII string.
  182. pub fn password(&self) -> Option<&str> {
  183. if self.byte_at(self.username_end) == b':' {
  184. debug_assert!(self.has_host());
  185. debug_assert!(self.byte_at(self.host_start - 1) == b'@');
  186. Some(self.slice(self.username_end + 1..self.host_start - 1))
  187. } else {
  188. None
  189. }
  190. }
  191. /// Return whether this URL has a host.
  192. ///
  193. /// Non-relative URLs (typical of `data:` and `mailto:`) and some `file:` URLs don’
  194. #[inline]
  195. pub fn has_host(&self) -> bool {
  196. !matches!(self.host, HostInternal::None)
  197. }
  198. /// Return the string representation of the host (domain or IP address) for this URL, if any.
  199. /// Non-ASCII domains are punycode-encoded per IDNA.
  200. ///
  201. /// Non-relative URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  202. /// don’t have a host.
  203. ///
  204. /// See also the `host` method.
  205. pub fn host_str(&self) -> Option<&str> {
  206. if self.has_host() {
  207. Some(self.slice(self.host_start..self.host_end))
  208. } else {
  209. None
  210. }
  211. }
  212. /// Return the parsed representation of the host for this URL.
  213. /// Non-ASCII domain labels are punycode-encoded per IDNA.
  214. ///
  215. /// Non-relative URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  216. /// don’t have a host.
  217. ///
  218. /// See also the `host_str` method.
  219. pub fn host(&self) -> Option<Host<&str>> {
  220. match self.host {
  221. HostInternal::None => None,
  222. HostInternal::Domain => Some(Host::Domain(self.slice(self.host_start..self.host_end))),
  223. HostInternal::Ipv4(address) => Some(Host::Ipv4(address)),
  224. HostInternal::Ipv6(address) => Some(Host::Ipv6(address)),
  225. }
  226. }
  227. /// Return the port number for this URL, if any.
  228. #[inline]
  229. pub fn port(&self) -> Option<u16> {
  230. self.port
  231. }
  232. /// Return the port number for this URL, or the default port number if it is known.
  233. ///
  234. /// This method only knows the default port number
  235. /// of the `http`, `https`, `ws`, `wss`, `ftp`, and `gopher` schemes.
  236. ///
  237. /// For URLs in these schemes, this method always returns `Some(_)`.
  238. /// For other schemes, it is the same as `Url::port()`.
  239. #[inline]
  240. pub fn port_or_default(&self) -> Option<u16> {
  241. self.port.or_else(|| parser::default_port(self.scheme()))
  242. }
  243. /// Return the path for this URL, as a percent-encoded ASCII string.
  244. /// For relative URLs, this starts with a '/' slash
  245. /// and continues with slash-separated path segments.
  246. /// For non-relative URLs, this is an arbitrary string that doesn’t start with '/'.
  247. pub fn path(&self) -> &str {
  248. match (self.query_start, self.fragment_start) {
  249. (None, None) => self.slice(self.path_start..),
  250. (Some(next_component_start), _) |
  251. (None, Some(next_component_start)) => {
  252. self.slice(self.path_start..next_component_start)
  253. }
  254. }
  255. }
  256. /// If this URL is relative, return an iterator of '/' slash-separated path segments,
  257. /// each as a percent-encoded ASCII string.
  258. ///
  259. /// Return `None` for non-relative URLs, or an iterator of at least one string.
  260. pub fn path_segments(&self) -> Option<str::Split<char>> {
  261. if self.non_relative {
  262. None
  263. } else {
  264. let path = self.path();
  265. debug_assert!(path.starts_with("/"));
  266. Some(path[1..].split('/'))
  267. }
  268. }
  269. /// Return this URL’s query string, if any, as a percent-encoded ASCII string.
  270. pub fn query(&self) -> Option<&str> {
  271. match (self.query_start, self.fragment_start) {
  272. (None, _) => None,
  273. (Some(query_start), None) => {
  274. debug_assert!(self.byte_at(query_start) == b'?');
  275. Some(self.slice(query_start + 1..))
  276. }
  277. (Some(query_start), Some(fragment_start)) => {
  278. debug_assert!(self.byte_at(query_start) == b'?');
  279. Some(self.slice(query_start + 1..fragment_start))
  280. }
  281. }
  282. }
  283. /// Return this URL’s fragment identifier, if any, as a percent-encoded ASCII string.
  284. pub fn fragment(&self) -> Option<&str> {
  285. self.fragment_start.map(|start| {
  286. debug_assert!(self.byte_at(start) == b'#');
  287. self.slice(start + 1..)
  288. })
  289. }
  290. /// Convert a file name as `std::path::Path` into an URL in the `file` scheme.
  291. ///
  292. /// This returns `Err` if the given path is not absolute or,
  293. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`).
  294. pub fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  295. let mut serialization = "file://".to_owned();
  296. let path_start = serialization.len() as u32;
  297. try!(path_to_file_url_segments(path.as_ref(), &mut serialization));
  298. Ok(Url {
  299. serialization: serialization,
  300. non_relative: false,
  301. scheme_end: "file".len() as u32,
  302. username_end: path_start,
  303. host_start: path_start,
  304. host_end: path_start,
  305. host: HostInternal::None,
  306. port: None,
  307. path_start: path_start,
  308. query_start: None,
  309. fragment_start: None,
  310. })
  311. }
  312. /// Convert a directory name as `std::path::Path` into an URL in the `file` scheme.
  313. ///
  314. /// This returns `Err` if the given path is not absolute or,
  315. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`).
  316. ///
  317. /// Compared to `from_file_path`, this ensure that URL’s the path has a trailing slash
  318. /// so that the entire path is considered when using this URL as a base URL.
  319. ///
  320. /// For example:
  321. ///
  322. /// * `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
  323. /// as the base URL is `file:///var/www/index.html`
  324. /// * `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www"))`
  325. /// as the base URL is `file:///var/index.html`, which might not be what was intended.
  326. ///
  327. /// Note that `std::path` does not consider trailing slashes significant
  328. /// and usually does not include them (e.g. in `Path::parent()`).
  329. pub fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  330. let mut url = try!(Url::from_file_path(path));
  331. if !url.serialization.ends_with('/') {
  332. url.serialization.push('/')
  333. }
  334. Ok(url)
  335. }
  336. /// Assuming the URL is in the `file` scheme or similar,
  337. /// convert its path to an absolute `std::path::Path`.
  338. ///
  339. /// **Note:** This does not actually check the URL’s `scheme`,
  340. /// and may give nonsensical results for other schemes.
  341. /// It is the user’s responsibility to check the URL’s scheme before calling this.
  342. ///
  343. /// ```
  344. /// # use url::Url;
  345. /// # let url = Url::parse("file:///etc/passwd").unwrap();
  346. /// let path = url.to_file_path();
  347. /// ```
  348. ///
  349. /// Returns `Err` if the host is neither empty nor `"localhost"`,
  350. /// or if `Path::new_opt()` returns `None`.
  351. /// (That is, if the percent-decoded path contains a NUL byte or,
  352. /// for a Windows path, is not UTF-8.)
  353. #[inline]
  354. pub fn to_file_path(&self) -> Result<PathBuf, ()> {
  355. // FIXME: Figure out what to do w.r.t host.
  356. if matches!(self.host(), None | Some(Host::Domain("localhost"))) {
  357. if let Some(segments) = self.path_segments() {
  358. return file_url_segments_to_pathbuf(segments)
  359. }
  360. }
  361. Err(())
  362. }
  363. /// Parse the URL’s query string, if any, as `application/x-www-form-urlencoded`
  364. /// and return a vector of (key, value) pairs.
  365. #[inline]
  366. pub fn query_pairs(&self) -> Option<Vec<(String, String)>> {
  367. self.query().map(|query| form_urlencoded::parse(query.as_bytes()))
  368. }
  369. // Private helper methods:
  370. #[inline]
  371. fn slice<R>(&self, range: R) -> &str where R: RangeArg {
  372. range.slice_of(&self.serialization)
  373. }
  374. #[inline]
  375. fn byte_at(&self, i: u32) -> u8 {
  376. self.serialization.as_bytes()[i as usize]
  377. }
  378. }
  379. /// Parse a string as an URL, without a base URL or encoding override.
  380. impl str::FromStr for Url {
  381. type Err = ParseError;
  382. #[inline]
  383. fn from_str(input: &str) -> Result<Url, ::ParseError> {
  384. Url::parse(input)
  385. }
  386. }
  387. /// Display the serialization of this URL.
  388. impl fmt::Display for Url {
  389. #[inline]
  390. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  391. fmt::Display::fmt(&self.serialization, formatter)
  392. }
  393. }
  394. /// Debug the serialization of this URL.
  395. impl fmt::Debug for Url {
  396. #[inline]
  397. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  398. fmt::Debug::fmt(&self.serialization, formatter)
  399. }
  400. }
  401. /// URLs compare like their serialization.
  402. impl Eq for Url {}
  403. /// URLs compare like their serialization.
  404. impl PartialEq for Url {
  405. #[inline]
  406. fn eq(&self, other: &Self) -> bool {
  407. self.serialization == other.serialization
  408. }
  409. }
  410. /// URLs compare like their serialization.
  411. impl Ord for Url {
  412. #[inline]
  413. fn cmp(&self, other: &Self) -> cmp::Ordering {
  414. self.serialization.cmp(&other.serialization)
  415. }
  416. }
  417. /// URLs compare like their serialization.
  418. impl PartialOrd for Url {
  419. #[inline]
  420. fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
  421. self.serialization.partial_cmp(&other.serialization)
  422. }
  423. }
  424. /// URLs hash like their serialization.
  425. impl hash::Hash for Url {
  426. #[inline]
  427. fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
  428. hash::Hash::hash(&self.serialization, state)
  429. }
  430. }
  431. /// Return the serialization of this URL.
  432. impl AsRef<str> for Url {
  433. #[inline]
  434. fn as_ref(&self) -> &str {
  435. &self.serialization
  436. }
  437. }
  438. trait RangeArg {
  439. fn slice_of<'a>(&self, s: &'a str) -> &'a str;
  440. }
  441. impl RangeArg for Range<u32> {
  442. #[inline]
  443. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  444. &s[self.start as usize .. self.end as usize]
  445. }
  446. }
  447. impl RangeArg for RangeFrom<u32> {
  448. #[inline]
  449. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  450. &s[self.start as usize ..]
  451. }
  452. }
  453. impl RangeArg for RangeTo<u32> {
  454. #[inline]
  455. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  456. &s[.. self.end as usize]
  457. }
  458. }
  459. impl rustc_serialize::Encodable for Url {
  460. fn encode<S: rustc_serialize::Encoder>(&self, encoder: &mut S) -> Result<(), S::Error> {
  461. encoder.emit_str(self.as_str())
  462. }
  463. }
  464. impl rustc_serialize::Decodable for Url {
  465. fn decode<D: rustc_serialize::Decoder>(decoder: &mut D) -> Result<Url, D::Error> {
  466. Url::parse(&*try!(decoder.read_str())).map_err(|error| {
  467. decoder.error(&format!("URL parsing error: {}", error))
  468. })
  469. }
  470. }
  471. /// Serializes this URL into a `serde` stream.
  472. ///
  473. /// This implementation is only available if the `serde_serialization` Cargo feature is enabled.
  474. #[cfg(feature="serde_serialization")]
  475. impl serde::Serialize for Url {
  476. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
  477. format!("{}", self).serialize(serializer)
  478. }
  479. }
  480. /// Deserializes this URL from a `serde` stream.
  481. ///
  482. /// This implementation is only available if the `serde_serialization` Cargo feature is enabled.
  483. #[cfg(feature="serde_serialization")]
  484. impl serde::Deserialize for Url {
  485. fn deserialize<D>(deserializer: &mut D) -> Result<Url, D::Error> where D: serde::Deserializer {
  486. let string_representation: String = try!(serde::Deserialize::deserialize(deserializer));
  487. Ok(Url::parse(&string_representation).unwrap())
  488. }
  489. }
  490. #[cfg(unix)]
  491. fn path_to_file_url_segments(path: &Path, serialization: &mut String) -> Result<(), ()> {
  492. use std::os::unix::prelude::OsStrExt;
  493. if !path.is_absolute() {
  494. return Err(())
  495. }
  496. // skip the root component
  497. for component in path.components().skip(1) {
  498. serialization.push('/');
  499. percent_encode_to(component.as_os_str().as_bytes(), PATH_SEGMENT_ENCODE_SET, serialization)
  500. }
  501. Ok(())
  502. }
  503. #[cfg(windows)]
  504. fn path_to_file_url_segments(path: &Path, serialization: &mut String) -> Result<(), ()> {
  505. path_to_file_url_segments_windows(path, serialization)
  506. }
  507. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  508. #[cfg_attr(not(windows), allow(dead_code))]
  509. fn path_to_file_url_segments_windows(path: &Path, serialization: &mut String) -> Result<(), ()> {
  510. use std::path::{Prefix, Component};
  511. if !path.is_absolute() {
  512. return Err(())
  513. }
  514. let mut components = path.components();
  515. let disk = match components.next() {
  516. Some(Component::Prefix(ref p)) => match p.kind() {
  517. Prefix::Disk(byte) => byte,
  518. Prefix::VerbatimDisk(byte) => byte,
  519. _ => return Err(()),
  520. },
  521. // FIXME: do something with UNC and other prefixes?
  522. _ => return Err(())
  523. };
  524. // Start with the prefix, e.g. "C:"
  525. serialization.push('/');
  526. serialization.push(disk as char);
  527. serialization.push(':');
  528. for component in components {
  529. if component == Component::RootDir { continue }
  530. // FIXME: somehow work with non-unicode?
  531. let component = try!(component.as_os_str().to_str().ok_or(()));
  532. serialization.push('/');
  533. percent_encode_to(component.as_bytes(), PATH_SEGMENT_ENCODE_SET, serialization);
  534. }
  535. Ok(())
  536. }
  537. #[cfg(unix)]
  538. fn file_url_segments_to_pathbuf(segments: str::Split<char>) -> Result<PathBuf, ()> {
  539. use std::ffi::OsStr;
  540. use std::os::unix::prelude::OsStrExt;
  541. use std::path::PathBuf;
  542. use percent_encoding::percent_decode_to;
  543. let mut bytes = Vec::new();
  544. for segment in segments {
  545. bytes.push(b'/');
  546. percent_decode_to(segment.as_bytes(), &mut bytes);
  547. }
  548. let os_str = OsStr::from_bytes(&bytes);
  549. let path = PathBuf::from(os_str);
  550. debug_assert!(path.is_absolute(),
  551. "to_file_path() failed to produce an absolute Path");
  552. Ok(path)
  553. }
  554. #[cfg(windows)]
  555. fn file_url_segments_to_pathbuf(segments: str::Split<char>) -> Result<PathBuf, ()> {
  556. file_url_segments_to_pathbuf_windows(segments)
  557. }
  558. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  559. #[cfg_attr(not(windows), allow(dead_code))]
  560. fn file_url_segments_to_pathbuf_windows(mut segments: str::Split<char>) -> Result<PathBuf, ()> {
  561. use percent_encoding::percent_decode;
  562. let first = try!(segments.next().ok_or(()));
  563. if first.len() != 2 || !first.starts_with(parser::ascii_alpha)
  564. || first.as_bytes()[1] != b':' {
  565. return Err(())
  566. }
  567. let mut string = first.to_owned();
  568. for segment in segments {
  569. string.push('\\');
  570. // Currently non-unicode windows paths cannot be represented
  571. match String::from_utf8(percent_decode(segment.as_bytes())) {
  572. Ok(s) => string.push_str(&s),
  573. Err(..) => return Err(()),
  574. }
  575. }
  576. let path = PathBuf::from(string);
  577. debug_assert!(path.is_absolute(),
  578. "to_file_path() failed to produce an absolute Path");
  579. Ok(path)
  580. }