lib.rs 22 KB

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