lib.rs 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  1. // Copyright 2013-2015 The rust-url developers.
  2. //
  3. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  4. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  5. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  6. // option. This file may not be copied, modified, or distributed
  7. // except according to those terms.
  8. /*!
  9. rust-url is an implementation of the [URL Standard](http://url.spec.whatwg.org/)
  10. for the [Rust](http://rust-lang.org/) programming language.
  11. It builds with [Cargo](http://crates.io/).
  12. To use it in your project, add this to your `Cargo.toml` file:
  13. ```Cargo
  14. [dependencies.url]
  15. git = "https://github.com/servo/rust-url"
  16. ```
  17. Supporting encodings other than UTF-8 in query strings is an optional feature
  18. that requires [rust-encoding](https://github.com/lifthrasiir/rust-encoding)
  19. and is off by default.
  20. You can enable it with
  21. [Cargo’s *features* mechanism](http://doc.crates.io/manifest.html#the-[features]-section):
  22. ```Cargo
  23. [dependencies.url]
  24. git = "https://github.com/servo/rust-url"
  25. features = ["query_encoding"]
  26. ```
  27. … or by passing `--cfg 'feature="query_encoding"'` to rustc.
  28. # URL parsing and data structures
  29. First, URL parsing may fail for various reasons and therefore returns a `Result`.
  30. ```
  31. use url::{Url, ParseError};
  32. assert!(Url::parse("http://[:::1]") == Err(ParseError::InvalidIpv6Address))
  33. ```
  34. Let’s parse a valid URL and look at its components.
  35. ```
  36. use url::{Url, Host};
  37. let issue_list_url = Url::parse(
  38. "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"
  39. ).unwrap();
  40. assert!(issue_list_url.scheme() == "https");
  41. assert!(issue_list_url.username() == "");
  42. assert!(issue_list_url.password() == None);
  43. assert!(issue_list_url.host_str() == Some("github.com"));
  44. assert!(issue_list_url.host() == Some(Host::Domain("github.com")));
  45. assert!(issue_list_url.port() == None);
  46. assert!(issue_list_url.path() == "/rust-lang/rust/issues");
  47. assert!(issue_list_url.path_segments().map(|c| c.collect::<Vec<_>>()) ==
  48. Some(vec!["rust-lang", "rust", "issues"]));
  49. assert!(issue_list_url.query() == Some("labels=E-easy&state=open"));
  50. assert!(issue_list_url.fragment() == None);
  51. assert!(!issue_list_url.cannot_be_a_base());
  52. ```
  53. Some URLs are said to be *cannot-be-a-base*:
  54. they don’t have a username, password, host, or port,
  55. and their "path" is an arbitrary string rather than slash-separated segments:
  56. ```
  57. use url::Url;
  58. let data_url = Url::parse("data:text/plain,Hello?World#").unwrap();
  59. assert!(data_url.cannot_be_a_base());
  60. assert!(data_url.scheme() == "data");
  61. assert!(data_url.path() == "text/plain,Hello");
  62. assert!(data_url.path_segments().is_none());
  63. assert!(data_url.query() == Some("World"));
  64. assert!(data_url.fragment() == Some(""));
  65. ```
  66. # Base URL
  67. Many contexts allow URL *references* that can be relative to a *base URL*:
  68. ```html
  69. <link rel="stylesheet" href="../main.css">
  70. ```
  71. Since parsed URL are absolute, giving a base is required for parsing relative URLs:
  72. ```
  73. use url::{Url, ParseError};
  74. assert!(Url::parse("../main.css") == Err(ParseError::RelativeUrlWithoutBase))
  75. ```
  76. Use the `join` method on an `Url` to use it as a base URL:
  77. ```
  78. use url::Url;
  79. let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html").unwrap();
  80. let css_url = this_document.join("../main.css").unwrap();
  81. assert_eq!(css_url.as_str(), "http://servo.github.io/rust-url/main.css")
  82. */
  83. #[cfg(feature="rustc-serialize")] extern crate rustc_serialize;
  84. #[macro_use] extern crate matches;
  85. #[cfg(feature="serde")] extern crate serde;
  86. #[cfg(feature="heapsize")] #[macro_use] extern crate heapsize;
  87. pub extern crate idna;
  88. use encoding::EncodingOverride;
  89. #[cfg(feature = "heapsize")] use heapsize::HeapSizeOf;
  90. use host::HostInternal;
  91. use parser::{Parser, Context, SchemeType, to_u32};
  92. use percent_encoding::{PATH_SEGMENT_ENCODE_SET, USERINFO_ENCODE_SET,
  93. percent_encode, percent_decode, utf8_percent_encode};
  94. use std::borrow::Borrow;
  95. use std::cmp;
  96. #[cfg(feature = "serde")] use std::error::Error;
  97. use std::fmt::{self, Write};
  98. use std::hash;
  99. use std::io;
  100. use std::mem;
  101. use std::net::{ToSocketAddrs, IpAddr};
  102. use std::ops::{Range, RangeFrom, RangeTo};
  103. use std::path::{Path, PathBuf};
  104. use std::str;
  105. pub use origin::{Origin, OpaqueOrigin};
  106. pub use host::{Host, HostAndPort, SocketAddrs};
  107. pub use path_segments::PathSegmentsMut;
  108. pub use parser::ParseError;
  109. pub use slicing::Position;
  110. mod encoding;
  111. mod host;
  112. mod origin;
  113. mod path_segments;
  114. mod parser;
  115. mod slicing;
  116. pub mod form_urlencoded;
  117. pub mod percent_encoding;
  118. pub mod quirks;
  119. /// A parsed URL record.
  120. #[derive(Clone)]
  121. pub struct Url {
  122. /// Syntax in pseudo-BNF:
  123. ///
  124. /// url = scheme ":" [ hierarchical | non-hierarchical ] [ "?" query ]? [ "#" fragment ]?
  125. /// non-hierarchical = non-hierarchical-path
  126. /// non-hierarchical-path = /* Does not start with "/" */
  127. /// hierarchical = authority? hierarchical-path
  128. /// authority = "//" userinfo? host [ ":" port ]?
  129. /// userinfo = username [ ":" password ]? "@"
  130. /// hierarchical-path = [ "/" path-segment ]+
  131. serialization: String,
  132. // Components
  133. scheme_end: u32, // Before ':'
  134. username_end: u32, // Before ':' (if a password is given) or '@' (if not)
  135. host_start: u32,
  136. host_end: u32,
  137. host: HostInternal,
  138. port: Option<u16>,
  139. path_start: u32, // Before initial '/', if any
  140. query_start: Option<u32>, // Before '?', unlike Position::QueryStart
  141. fragment_start: Option<u32>, // Before '#', unlike Position::FragmentStart
  142. }
  143. #[cfg(feature = "heapsize")]
  144. impl HeapSizeOf for Url {
  145. fn heap_size_of_children(&self) -> usize {
  146. self.serialization.heap_size_of_children()
  147. }
  148. }
  149. /// Full configuration for the URL parser.
  150. #[derive(Copy, Clone)]
  151. pub struct ParseOptions<'a> {
  152. base_url: Option<&'a Url>,
  153. encoding_override: encoding::EncodingOverride,
  154. log_syntax_violation: Option<&'a Fn(&'static str)>,
  155. }
  156. impl<'a> ParseOptions<'a> {
  157. /// Change the base URL
  158. pub fn base_url(mut self, new: Option<&'a Url>) -> Self {
  159. self.base_url = new;
  160. self
  161. }
  162. /// Override the character encoding of query strings.
  163. /// This is a legacy concept only relevant for HTML.
  164. #[cfg(feature = "query_encoding")]
  165. pub fn encoding_override(mut self, new: Option<encoding::EncodingRef>) -> Self {
  166. self.encoding_override = EncodingOverride::from_opt_encoding(new).to_output_encoding();
  167. self
  168. }
  169. /// Call the provided function or closure on non-fatal parse errors.
  170. pub fn log_syntax_violation(mut self, new: Option<&'a Fn(&'static str)>) -> Self {
  171. self.log_syntax_violation = new;
  172. self
  173. }
  174. /// Parse an URL string with the configuration so far.
  175. pub fn parse(self, input: &str) -> Result<Url, ::ParseError> {
  176. Parser {
  177. serialization: String::with_capacity(input.len()),
  178. base_url: self.base_url,
  179. query_encoding_override: self.encoding_override,
  180. log_syntax_violation: self.log_syntax_violation,
  181. context: Context::UrlParser,
  182. }.parse_url(input)
  183. }
  184. }
  185. impl Url {
  186. /// Parse an absolute URL from a string.
  187. ///
  188. /// # Examples
  189. ///
  190. /// ```rust
  191. /// use url::Url;
  192. ///
  193. /// let url = Url::parse("https://example.net").unwrap();
  194. /// ```
  195. #[inline]
  196. pub fn parse(input: &str) -> Result<Url, ::ParseError> {
  197. Url::options().parse(input)
  198. }
  199. /// Parse an absolute URL from a string and add params to its query string.
  200. ///
  201. /// Existing params are not removed.
  202. ///
  203. /// # Examples
  204. ///
  205. /// ```rust
  206. /// use url::Url;
  207. ///
  208. /// let url = Url::parse_with_params("https://example.net?dont=clobberme",
  209. /// &[("lang", "rust"), ("browser", "servo")]);
  210. /// ```
  211. #[inline]
  212. pub fn parse_with_params<I, K, V>(input: &str, iter: I) -> Result<Url, ::ParseError>
  213. where I: IntoIterator,
  214. I::Item: Borrow<(K, V)>,
  215. K: AsRef<str>,
  216. V: AsRef<str>
  217. {
  218. let mut url = Url::options().parse(input);
  219. if let Ok(ref mut url) = url {
  220. url.query_pairs_mut().extend_pairs(iter);
  221. }
  222. url
  223. }
  224. /// Parse a string as an URL, with this URL as the base URL.
  225. ///
  226. /// # Examples
  227. ///
  228. /// ```rust
  229. /// use url::Url;
  230. ///
  231. /// let url = Url::parse("https://example.net").unwrap();
  232. /// let url = url.join("foo").unwrap();
  233. /// assert_eq!(url.as_str(), "https://example.net/foo");
  234. /// ```
  235. ///
  236. /// Trailing slashes are not preserved:
  237. ///
  238. /// ```rust
  239. /// use url::Url;
  240. ///
  241. /// let url = Url::parse("https://example.net/foo/").unwrap();
  242. /// let url = url.join("bar").unwrap();
  243. /// assert_eq!(url.as_str(), "https://example.net/foo/bar");
  244. /// ```
  245. #[inline]
  246. pub fn join(&self, input: &str) -> Result<Url, ::ParseError> {
  247. Url::options().base_url(Some(self)).parse(input)
  248. }
  249. /// Return a default `ParseOptions` that can fully configure the URL parser.
  250. pub fn options<'a>() -> ParseOptions<'a> {
  251. ParseOptions {
  252. base_url: None,
  253. encoding_override: EncodingOverride::utf8(),
  254. log_syntax_violation: None,
  255. }
  256. }
  257. /// Return the serialization of this URL.
  258. ///
  259. /// This is fast since that serialization is already stored in the `Url` struct.
  260. ///
  261. /// # Examples
  262. ///
  263. /// ```rust
  264. /// use url::Url;
  265. ///
  266. /// let url_str = "https://example.net/";
  267. /// let url = Url::parse(url_str).unwrap();
  268. /// assert_eq!(url.as_str(), url_str);
  269. /// ```
  270. #[inline]
  271. pub fn as_str(&self) -> &str {
  272. &self.serialization
  273. }
  274. /// Return the serialization of this URL.
  275. ///
  276. /// This consumes the `Url` and takes ownership of the `String` stored in it.
  277. ///
  278. /// # Examples
  279. ///
  280. /// ```rust
  281. /// use url::Url;
  282. ///
  283. /// let url_str = "https://example.net/";
  284. /// let url = Url::parse(url_str).unwrap();
  285. /// assert_eq!(url.into_string(), url_str);
  286. /// ```
  287. #[inline]
  288. pub fn into_string(self) -> String {
  289. self.serialization
  290. }
  291. /// For internal testing, not part of the public API.
  292. ///
  293. /// Methods of the `Url` struct assume a number of invariants.
  294. /// This checks each of these invariants and panic if one is not met.
  295. /// This is for testing rust-url itself.
  296. #[doc(hidden)]
  297. pub fn assert_invariants(&self) {
  298. macro_rules! assert {
  299. ($x: expr) => {
  300. if !$x {
  301. panic!("!( {} ) for URL {:?}", stringify!($x), self.serialization)
  302. }
  303. }
  304. }
  305. macro_rules! assert_eq {
  306. ($a: expr, $b: expr) => {
  307. {
  308. let a = $a;
  309. let b = $b;
  310. if a != b {
  311. panic!("{:?} != {:?} ({} != {}) for URL {:?}",
  312. a, b, stringify!($a), stringify!($b), self.serialization)
  313. }
  314. }
  315. }
  316. }
  317. assert!(self.scheme_end >= 1);
  318. assert!(matches!(self.byte_at(0), b'a'...b'z' | b'A'...b'Z'));
  319. assert!(self.slice(1..self.scheme_end).chars()
  320. .all(|c| matches!(c, 'a'...'z' | 'A'...'Z' | '0'...'9' | '+' | '-' | '.')));
  321. assert_eq!(self.byte_at(self.scheme_end), b':');
  322. if self.slice(self.scheme_end + 1 ..).starts_with("//") {
  323. // URL with authority
  324. match self.byte_at(self.username_end) {
  325. b':' => {
  326. assert!(self.host_start >= self.username_end + 2);
  327. assert_eq!(self.byte_at(self.host_start - 1), b'@');
  328. }
  329. b'@' => assert!(self.host_start == self.username_end + 1),
  330. _ => assert_eq!(self.username_end, self.scheme_end + 3),
  331. }
  332. assert!(self.host_start >= self.username_end);
  333. assert!(self.host_end >= self.host_start);
  334. let host_str = self.slice(self.host_start..self.host_end);
  335. match self.host {
  336. HostInternal::None => assert_eq!(host_str, ""),
  337. HostInternal::Ipv4(address) => assert_eq!(host_str, address.to_string()),
  338. HostInternal::Ipv6(address) => {
  339. let h: Host<String> = Host::Ipv6(address);
  340. assert_eq!(host_str, h.to_string())
  341. }
  342. HostInternal::Domain => {
  343. if SchemeType::from(self.scheme()).is_special() {
  344. assert!(!host_str.is_empty())
  345. }
  346. }
  347. }
  348. if self.path_start == self.host_end {
  349. assert_eq!(self.port, None);
  350. } else {
  351. assert_eq!(self.byte_at(self.host_end), b':');
  352. let port_str = self.slice(self.host_end + 1..self.path_start);
  353. assert_eq!(self.port, Some(port_str.parse::<u16>().expect("Couldn't parse port?")));
  354. }
  355. assert_eq!(self.byte_at(self.path_start), b'/');
  356. } else {
  357. // Anarchist URL (no authority)
  358. assert_eq!(self.username_end, self.scheme_end + 1);
  359. assert_eq!(self.host_start, self.scheme_end + 1);
  360. assert_eq!(self.host_end, self.scheme_end + 1);
  361. assert_eq!(self.host, HostInternal::None);
  362. assert_eq!(self.port, None);
  363. assert_eq!(self.path_start, self.scheme_end + 1);
  364. }
  365. if let Some(start) = self.query_start {
  366. assert!(start > self.path_start);
  367. assert_eq!(self.byte_at(start), b'?');
  368. }
  369. if let Some(start) = self.fragment_start {
  370. assert!(start > self.path_start);
  371. assert_eq!(self.byte_at(start), b'#');
  372. }
  373. if let (Some(query_start), Some(fragment_start)) = (self.query_start, self.fragment_start) {
  374. assert!(fragment_start > query_start);
  375. }
  376. let other = Url::parse(self.as_str()).expect("Failed to parse myself?");
  377. assert_eq!(&self.serialization, &other.serialization);
  378. assert_eq!(self.scheme_end, other.scheme_end);
  379. assert_eq!(self.username_end, other.username_end);
  380. assert_eq!(self.host_start, other.host_start);
  381. assert_eq!(self.host_end, other.host_end);
  382. assert!(self.host == other.host ||
  383. // XXX No host round-trips to empty host.
  384. // See https://github.com/whatwg/url/issues/79
  385. (self.host_str(), other.host_str()) == (None, Some("")));
  386. assert_eq!(self.port, other.port);
  387. assert_eq!(self.path_start, other.path_start);
  388. assert_eq!(self.query_start, other.query_start);
  389. assert_eq!(self.fragment_start, other.fragment_start);
  390. }
  391. /// Return the origin of this URL (https://url.spec.whatwg.org/#origin)
  392. ///
  393. /// Note: this returns an opaque origin for `file:` URLs, which causes
  394. /// `url.origin() != url.origin()`.
  395. ///
  396. /// # Examples
  397. ///
  398. /// URL with `ftp` scheme:
  399. ///
  400. /// ```rust
  401. /// use url::{Host, Origin, Url};
  402. ///
  403. /// let url = Url::parse("ftp://example.com/foo").unwrap();
  404. /// assert_eq!(url.origin(),
  405. /// Origin::Tuple("ftp".into(),
  406. /// Host::Domain("example.com".into()),
  407. /// 21));
  408. /// ```
  409. ///
  410. /// URL with `blob` scheme:
  411. ///
  412. /// ```rust
  413. /// use url::{Host, Origin, Url};
  414. ///
  415. /// let url = Url::parse("blob:https://example.com/foo").unwrap();
  416. /// assert_eq!(url.origin(),
  417. /// Origin::Tuple("https".into(),
  418. /// Host::Domain("example.com".into()),
  419. /// 443));
  420. /// ```
  421. ///
  422. /// URL with `file` scheme:
  423. ///
  424. /// ```rust
  425. /// use url::{Host, Origin, Url};
  426. ///
  427. /// let url = Url::parse("file:///tmp/foo").unwrap();
  428. /// assert!(!url.origin().is_tuple());
  429. ///
  430. /// let other_url = Url::parse("file:///tmp/foo").unwrap();
  431. /// assert!(url.origin() != other_url.origin());
  432. /// ```
  433. ///
  434. /// URL with other scheme:
  435. ///
  436. /// ```rust
  437. /// use url::{Host, Origin, Url};
  438. ///
  439. /// let url = Url::parse("foo:bar").unwrap();
  440. /// assert!(!url.origin().is_tuple());
  441. /// ```
  442. #[inline]
  443. pub fn origin(&self) -> Origin {
  444. origin::url_origin(self)
  445. }
  446. /// Return the scheme of this URL, lower-cased, as an ASCII string without the ':' delimiter.
  447. ///
  448. /// # Examples
  449. ///
  450. /// ```
  451. /// use url::Url;
  452. ///
  453. /// let url = Url::parse("file:///tmp/foo").unwrap();
  454. /// assert_eq!(url.scheme(), "file");
  455. /// ```
  456. #[inline]
  457. pub fn scheme(&self) -> &str {
  458. self.slice(..self.scheme_end)
  459. }
  460. /// Return whether the URL has an 'authority',
  461. /// which can contain a username, password, host, and port number.
  462. ///
  463. /// URLs that do *not* are either path-only like `unix:/run/foo.socket`
  464. /// or cannot-be-a-base like `data:text/plain,Stuff`.
  465. ///
  466. /// # Examples
  467. ///
  468. /// ```
  469. /// use url::Url;
  470. ///
  471. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  472. /// assert!(url.has_authority());
  473. ///
  474. /// let url = Url::parse("unix:/run/foo.socket").unwrap();
  475. /// assert!(!url.has_authority());
  476. ///
  477. /// let url = Url::parse("data:text/plain,Stuff").unwrap();
  478. /// assert!(!url.has_authority());
  479. /// ```
  480. #[inline]
  481. pub fn has_authority(&self) -> bool {
  482. debug_assert!(self.byte_at(self.scheme_end) == b':');
  483. self.slice(self.scheme_end..).starts_with("://")
  484. }
  485. /// Return whether this URL is a cannot-be-a-base URL,
  486. /// meaning that parsing a relative URL string with this URL as the base will return an error.
  487. ///
  488. /// This is the case if the scheme and `:` delimiter are not followed by a `/` slash,
  489. /// as is typically the case of `data:` and `mailto:` URLs.
  490. ///
  491. /// # Examples
  492. ///
  493. /// ```
  494. /// use url::Url;
  495. ///
  496. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  497. /// assert!(!url.cannot_be_a_base());
  498. ///
  499. /// let url = Url::parse("unix:/run/foo.socket").unwrap();
  500. /// assert!(!url.cannot_be_a_base());
  501. ///
  502. /// let url = Url::parse("data:text/plain,Stuff").unwrap();
  503. /// assert!(url.cannot_be_a_base());
  504. /// ```
  505. #[inline]
  506. pub fn cannot_be_a_base(&self) -> bool {
  507. !self.slice(self.path_start..).starts_with('/')
  508. }
  509. /// Return the username for this URL (typically the empty string)
  510. /// as a percent-encoded ASCII string.
  511. ///
  512. /// # Examples
  513. ///
  514. /// ```
  515. /// use url::Url;
  516. ///
  517. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  518. /// assert_eq!(url.username(), "rms");
  519. ///
  520. /// let url = Url::parse("ftp://:secret123@example.com").unwrap();
  521. /// assert_eq!(url.username(), "");
  522. ///
  523. /// let url = Url::parse("https://example.com").unwrap();
  524. /// assert_eq!(url.username(), "");
  525. /// ```
  526. pub fn username(&self) -> &str {
  527. if self.has_authority() {
  528. self.slice(self.scheme_end + ("://".len() as u32)..self.username_end)
  529. } else {
  530. ""
  531. }
  532. }
  533. /// Return the password for this URL, if any, as a percent-encoded ASCII string.
  534. ///
  535. /// # Examples
  536. ///
  537. /// ```
  538. /// use url::Url;
  539. ///
  540. /// let url = Url::parse("ftp://rms:secret123@example.com").unwrap();
  541. /// assert_eq!(url.password(), Some("secret123"));
  542. ///
  543. /// let url = Url::parse("ftp://:secret123@example.com").unwrap();
  544. /// assert_eq!(url.password(), Some("secret123"));
  545. ///
  546. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  547. /// assert_eq!(url.password(), None);
  548. ///
  549. /// let url = Url::parse("https://example.com").unwrap();
  550. /// assert_eq!(url.password(), None);
  551. /// ```
  552. pub fn password(&self) -> Option<&str> {
  553. // This ':' is not the one marking a port number since a host can not be empty.
  554. // (Except for file: URLs, which do not have port numbers.)
  555. if self.has_authority() && self.byte_at(self.username_end) == b':' {
  556. debug_assert!(self.byte_at(self.host_start - 1) == b'@');
  557. Some(self.slice(self.username_end + 1..self.host_start - 1))
  558. } else {
  559. None
  560. }
  561. }
  562. /// Equivalent to `url.host().is_some()`.
  563. ///
  564. /// # Examples
  565. ///
  566. /// ```
  567. /// use url::Url;
  568. ///
  569. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  570. /// assert!(url.has_host());
  571. ///
  572. /// let url = Url::parse("unix:/run/foo.socket").unwrap();
  573. /// assert!(!url.has_host());
  574. ///
  575. /// let url = Url::parse("data:text/plain,Stuff").unwrap();
  576. /// assert!(!url.has_host());
  577. /// ```
  578. pub fn has_host(&self) -> bool {
  579. !matches!(self.host, HostInternal::None)
  580. }
  581. /// Return the string representation of the host (domain or IP address) for this URL, if any.
  582. ///
  583. /// Non-ASCII domains are punycode-encoded per IDNA.
  584. /// IPv6 addresses are given between `[` and `]` brackets.
  585. ///
  586. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  587. /// don’t have a host.
  588. ///
  589. /// See also the `host` method.
  590. ///
  591. /// # Examples
  592. ///
  593. /// ```
  594. /// use url::Url;
  595. ///
  596. /// let url = Url::parse("https://127.0.0.1/index.html").unwrap();
  597. /// assert_eq!(url.host_str(), Some("127.0.0.1"));
  598. ///
  599. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  600. /// assert_eq!(url.host_str(), Some("example.com"));
  601. ///
  602. /// let url = Url::parse("unix:/run/foo.socket").unwrap();
  603. /// assert_eq!(url.host_str(), None);
  604. ///
  605. /// let url = Url::parse("data:text/plain,Stuff").unwrap();
  606. /// assert_eq!(url.host_str(), None);
  607. /// ```
  608. pub fn host_str(&self) -> Option<&str> {
  609. if self.has_host() {
  610. Some(self.slice(self.host_start..self.host_end))
  611. } else {
  612. None
  613. }
  614. }
  615. /// Return the parsed representation of the host for this URL.
  616. /// Non-ASCII domain labels are punycode-encoded per IDNA.
  617. ///
  618. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  619. /// don’t have a host.
  620. ///
  621. /// See also the `host_str` method.
  622. ///
  623. /// # Examples
  624. ///
  625. /// ```
  626. /// use url::Url;
  627. ///
  628. /// let url = Url::parse("https://127.0.0.1/index.html").unwrap();
  629. /// assert!(url.host().is_some());
  630. ///
  631. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  632. /// assert!(url.host().is_some());
  633. ///
  634. /// let url = Url::parse("unix:/run/foo.socket").unwrap();
  635. /// assert!(url.host().is_none());
  636. ///
  637. /// let url = Url::parse("data:text/plain,Stuff").unwrap();
  638. /// assert!(url.host().is_none());
  639. /// ```
  640. pub fn host(&self) -> Option<Host<&str>> {
  641. match self.host {
  642. HostInternal::None => None,
  643. HostInternal::Domain => Some(Host::Domain(self.slice(self.host_start..self.host_end))),
  644. HostInternal::Ipv4(address) => Some(Host::Ipv4(address)),
  645. HostInternal::Ipv6(address) => Some(Host::Ipv6(address)),
  646. }
  647. }
  648. /// If this URL has a host and it is a domain name (not an IP address), return it.
  649. ///
  650. /// # Examples
  651. ///
  652. /// ```
  653. /// use url::Url;
  654. ///
  655. /// let url = Url::parse("https://127.0.0.1/").unwrap();
  656. /// assert_eq!(url.domain(), None);
  657. ///
  658. /// let url = Url::parse("mailto:rms@example.net").unwrap();
  659. /// assert_eq!(url.domain(), None);
  660. ///
  661. /// let url = Url::parse("https://example.com/").unwrap();
  662. /// assert_eq!(url.domain(), Some("example.com"));
  663. /// ```
  664. pub fn domain(&self) -> Option<&str> {
  665. match self.host {
  666. HostInternal::Domain => Some(self.slice(self.host_start..self.host_end)),
  667. _ => None,
  668. }
  669. }
  670. /// Return the port number for this URL, if any.
  671. ///
  672. /// # Examples
  673. ///
  674. /// ```
  675. /// use url::Url;
  676. ///
  677. /// let url = Url::parse("https://example.com").unwrap();
  678. /// assert_eq!(url.port(), None);
  679. ///
  680. /// let url = Url::parse("ssh://example.com:22").unwrap();
  681. /// assert_eq!(url.port(), Some(22));
  682. /// ```
  683. #[inline]
  684. pub fn port(&self) -> Option<u16> {
  685. self.port
  686. }
  687. /// Return the port number for this URL, or the default port number if it is known.
  688. ///
  689. /// This method only knows the default port number
  690. /// of the `http`, `https`, `ws`, `wss`, `ftp`, and `gopher` schemes.
  691. ///
  692. /// For URLs in these schemes, this method always returns `Some(_)`.
  693. /// For other schemes, it is the same as `Url::port()`.
  694. ///
  695. /// # Examples
  696. ///
  697. /// ```
  698. /// use url::Url;
  699. ///
  700. /// let url = Url::parse("foo://example.com").unwrap();
  701. /// assert_eq!(url.port_or_known_default(), None);
  702. ///
  703. /// let url = Url::parse("foo://example.com:1456").unwrap();
  704. /// assert_eq!(url.port_or_known_default(), Some(1456));
  705. ///
  706. /// let url = Url::parse("https://example.com").unwrap();
  707. /// assert_eq!(url.port_or_known_default(), Some(443));
  708. /// ```
  709. #[inline]
  710. pub fn port_or_known_default(&self) -> Option<u16> {
  711. self.port.or_else(|| parser::default_port(self.scheme()))
  712. }
  713. /// If the URL has a host, return something that implements `ToSocketAddrs`.
  714. ///
  715. /// If the URL has no port number and the scheme’s default port number is not known
  716. /// (see `Url::port_or_known_default`),
  717. /// the closure is called to obtain a port number.
  718. /// Typically, this closure can match on the result `Url::scheme`
  719. /// to have per-scheme default port numbers,
  720. /// and panic for schemes it’s not prepared to handle.
  721. /// For example:
  722. ///
  723. /// ```rust
  724. /// # use url::Url;
  725. /// # use std::net::TcpStream;
  726. /// # use std::io;
  727. ///
  728. /// fn connect(url: &Url) -> io::Result<TcpStream> {
  729. /// TcpStream::connect(try!(url.with_default_port(default_port)))
  730. /// }
  731. ///
  732. /// fn default_port(url: &Url) -> Result<u16, ()> {
  733. /// match url.scheme() {
  734. /// "git" => Ok(9418),
  735. /// "git+ssh" => Ok(22),
  736. /// "git+https" => Ok(443),
  737. /// "git+http" => Ok(80),
  738. /// _ => Err(()),
  739. /// }
  740. /// }
  741. /// ```
  742. pub fn with_default_port<F>(&self, f: F) -> io::Result<HostAndPort<&str>>
  743. where F: FnOnce(&Url) -> Result<u16, ()> {
  744. Ok(HostAndPort {
  745. host: try!(self.host()
  746. .ok_or(())
  747. .or_else(|()| io_error("URL has no host"))),
  748. port: try!(self.port_or_known_default()
  749. .ok_or(())
  750. .or_else(|()| f(self))
  751. .or_else(|()| io_error("URL has no port number")))
  752. })
  753. }
  754. /// Return the path for this URL, as a percent-encoded ASCII string.
  755. /// For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with '/'.
  756. /// For other URLs, this starts with a '/' slash
  757. /// and continues with slash-separated path segments.
  758. pub fn path(&self) -> &str {
  759. match (self.query_start, self.fragment_start) {
  760. (None, None) => self.slice(self.path_start..),
  761. (Some(next_component_start), _) |
  762. (None, Some(next_component_start)) => {
  763. self.slice(self.path_start..next_component_start)
  764. }
  765. }
  766. }
  767. /// Unless this URL is cannot-be-a-base,
  768. /// return an iterator of '/' slash-separated path segments,
  769. /// each as a percent-encoded ASCII string.
  770. ///
  771. /// Return `None` for cannot-be-a-base URLs.
  772. ///
  773. /// When `Some` is returned, the iterator always contains at least one string
  774. /// (which may be empty).
  775. ///
  776. /// # Examples
  777. ///
  778. /// ```
  779. /// use url::Url;
  780. ///
  781. /// let url = Url::parse("https://example.com/foo/bar").unwrap();
  782. /// let mut path_segments = url.path_segments().unwrap();
  783. /// assert_eq!(path_segments.next(), Some("foo"));
  784. /// assert_eq!(path_segments.next(), Some("bar"));
  785. /// assert_eq!(path_segments.next(), None);
  786. ///
  787. /// let url = Url::parse("https://example.com").unwrap();
  788. /// let mut path_segments = url.path_segments().unwrap();
  789. /// assert_eq!(path_segments.next(), Some(""));
  790. /// assert_eq!(path_segments.next(), None);
  791. ///
  792. /// let url = Url::parse("data:text/plain,HelloWorld").unwrap();
  793. /// assert!(url.path_segments().is_none());
  794. /// ```
  795. pub fn path_segments(&self) -> Option<str::Split<char>> {
  796. let path = self.path();
  797. if path.starts_with('/') {
  798. Some(path[1..].split('/'))
  799. } else {
  800. None
  801. }
  802. }
  803. /// Return this URL’s query string, if any, as a percent-encoded ASCII string.
  804. pub fn query(&self) -> Option<&str> {
  805. match (self.query_start, self.fragment_start) {
  806. (None, _) => None,
  807. (Some(query_start), None) => {
  808. debug_assert!(self.byte_at(query_start) == b'?');
  809. Some(self.slice(query_start + 1..))
  810. }
  811. (Some(query_start), Some(fragment_start)) => {
  812. debug_assert!(self.byte_at(query_start) == b'?');
  813. Some(self.slice(query_start + 1..fragment_start))
  814. }
  815. }
  816. }
  817. /// Parse the URL’s query string, if any, as `application/x-www-form-urlencoded`
  818. /// and return an iterator of (key, value) pairs.
  819. #[inline]
  820. pub fn query_pairs(&self) -> form_urlencoded::Parse {
  821. form_urlencoded::parse(self.query().unwrap_or("").as_bytes())
  822. }
  823. /// Return this URL’s fragment identifier, if any.
  824. ///
  825. /// **Note:** the parser did *not* percent-encode this component,
  826. /// but the input may have been percent-encoded already.
  827. pub fn fragment(&self) -> Option<&str> {
  828. self.fragment_start.map(|start| {
  829. debug_assert!(self.byte_at(start) == b'#');
  830. self.slice(start + 1..)
  831. })
  832. }
  833. fn mutate<F: FnOnce(&mut Parser) -> R, R>(&mut self, f: F) -> R {
  834. let mut parser = Parser::for_setter(mem::replace(&mut self.serialization, String::new()));
  835. let result = f(&mut parser);
  836. self.serialization = parser.serialization;
  837. result
  838. }
  839. /// Change this URL’s fragment identifier.
  840. pub fn set_fragment(&mut self, fragment: Option<&str>) {
  841. // Remove any previous fragment
  842. if let Some(start) = self.fragment_start {
  843. debug_assert!(self.byte_at(start) == b'#');
  844. self.serialization.truncate(start as usize);
  845. }
  846. // Write the new one
  847. if let Some(input) = fragment {
  848. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  849. self.serialization.push('#');
  850. self.mutate(|parser| parser.parse_fragment(parser::Input::new(input)))
  851. } else {
  852. self.fragment_start = None
  853. }
  854. }
  855. fn take_fragment(&mut self) -> Option<String> {
  856. self.fragment_start.take().map(|start| {
  857. debug_assert!(self.byte_at(start) == b'#');
  858. let fragment = self.slice(start + 1..).to_owned();
  859. self.serialization.truncate(start as usize);
  860. fragment
  861. })
  862. }
  863. fn restore_already_parsed_fragment(&mut self, fragment: Option<String>) {
  864. if let Some(ref fragment) = fragment {
  865. assert!(self.fragment_start.is_none());
  866. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  867. self.serialization.push('#');
  868. self.serialization.push_str(fragment);
  869. }
  870. }
  871. /// Change this URL’s query string.
  872. pub fn set_query(&mut self, query: Option<&str>) {
  873. let fragment = self.take_fragment();
  874. // Remove any previous query
  875. if let Some(start) = self.query_start.take() {
  876. debug_assert!(self.byte_at(start) == b'?');
  877. self.serialization.truncate(start as usize);
  878. }
  879. // Write the new query, if any
  880. if let Some(input) = query {
  881. self.query_start = Some(to_u32(self.serialization.len()).unwrap());
  882. self.serialization.push('?');
  883. let scheme_end = self.scheme_end;
  884. self.mutate(|parser| parser.parse_query(scheme_end, parser::Input::new(input)));
  885. }
  886. self.restore_already_parsed_fragment(fragment);
  887. }
  888. /// Manipulate this URL’s query string, viewed as a sequence of name/value pairs
  889. /// in `application/x-www-form-urlencoded` syntax.
  890. ///
  891. /// The return value has a method-chaining API:
  892. ///
  893. /// ```rust
  894. /// # use url::Url;
  895. /// let mut url = Url::parse("https://example.net?lang=fr#nav").unwrap();
  896. /// assert_eq!(url.query(), Some("lang=fr"));
  897. ///
  898. /// url.query_pairs_mut().append_pair("foo", "bar");
  899. /// assert_eq!(url.query(), Some("lang=fr&foo=bar"));
  900. /// assert_eq!(url.as_str(), "https://example.net/?lang=fr&foo=bar#nav");
  901. ///
  902. /// url.query_pairs_mut()
  903. /// .clear()
  904. /// .append_pair("foo", "bar & baz")
  905. /// .append_pair("saisons", "\u{00C9}t\u{00E9}+hiver");
  906. /// assert_eq!(url.query(), Some("foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver"));
  907. /// assert_eq!(url.as_str(),
  908. /// "https://example.net/?foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver#nav");
  909. /// ```
  910. ///
  911. /// Note: `url.query_pairs_mut().clear();` is equivalent to `url.set_query(Some(""))`,
  912. /// not `url.set_query(None)`.
  913. ///
  914. /// The state of `Url` is unspecified if this return value is leaked without being dropped.
  915. pub fn query_pairs_mut(&mut self) -> form_urlencoded::Serializer<UrlQuery> {
  916. let fragment = self.take_fragment();
  917. let query_start;
  918. if let Some(start) = self.query_start {
  919. debug_assert!(self.byte_at(start) == b'?');
  920. query_start = start as usize;
  921. } else {
  922. query_start = self.serialization.len();
  923. self.query_start = Some(to_u32(query_start).unwrap());
  924. self.serialization.push('?');
  925. }
  926. let query = UrlQuery { url: self, fragment: fragment };
  927. form_urlencoded::Serializer::for_suffix(query, query_start + "?".len())
  928. }
  929. fn take_after_path(&mut self) -> String {
  930. match (self.query_start, self.fragment_start) {
  931. (Some(i), _) | (None, Some(i)) => {
  932. let after_path = self.slice(i..).to_owned();
  933. self.serialization.truncate(i as usize);
  934. after_path
  935. },
  936. (None, None) => String::new(),
  937. }
  938. }
  939. /// Change this URL’s path.
  940. pub fn set_path(&mut self, mut path: &str) {
  941. let after_path = self.take_after_path();
  942. let old_after_path_pos = to_u32(self.serialization.len()).unwrap();
  943. let cannot_be_a_base = self.cannot_be_a_base();
  944. let scheme_type = SchemeType::from(self.scheme());
  945. self.serialization.truncate(self.path_start as usize);
  946. self.mutate(|parser| {
  947. if cannot_be_a_base {
  948. if path.starts_with('/') {
  949. parser.serialization.push_str("%2F");
  950. path = &path[1..];
  951. }
  952. parser.parse_cannot_be_a_base_path(parser::Input::new(path));
  953. } else {
  954. let mut has_host = true; // FIXME
  955. parser.parse_path_start(scheme_type, &mut has_host, parser::Input::new(path));
  956. }
  957. });
  958. self.restore_after_path(old_after_path_pos, &after_path);
  959. }
  960. /// Return an object with methods to manipulate this URL’s path segments.
  961. ///
  962. /// Return `Err(())` if this URL is cannot-be-a-base.
  963. pub fn path_segments_mut(&mut self) -> Result<PathSegmentsMut, ()> {
  964. if self.cannot_be_a_base() {
  965. Err(())
  966. } else {
  967. Ok(path_segments::new(self))
  968. }
  969. }
  970. fn restore_after_path(&mut self, old_after_path_position: u32, after_path: &str) {
  971. let new_after_path_position = to_u32(self.serialization.len()).unwrap();
  972. let adjust = |index: &mut u32| {
  973. *index -= old_after_path_position;
  974. *index += new_after_path_position;
  975. };
  976. if let Some(ref mut index) = self.query_start { adjust(index) }
  977. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  978. self.serialization.push_str(after_path)
  979. }
  980. /// Change this URL’s port number.
  981. ///
  982. /// If this URL is cannot-be-a-base, does not have a host, or has the `file` scheme;
  983. /// do nothing and return `Err`.
  984. ///
  985. /// # Examples
  986. ///
  987. /// ```
  988. /// use url::Url;
  989. ///
  990. /// let mut url = Url::parse("ssh://example.net:2048/").unwrap();
  991. ///
  992. /// url.set_port(Some(4096)).unwrap();
  993. /// assert_eq!(url.as_str(), "ssh://example.net:4096/");
  994. ///
  995. /// url.set_port(None).unwrap();
  996. /// assert_eq!(url.as_str(), "ssh://example.net/");
  997. /// ```
  998. ///
  999. /// Cannot set port for cannot-be-a-base URLs:
  1000. ///
  1001. /// ```
  1002. /// use url::Url;
  1003. ///
  1004. /// let mut url = Url::parse("mailto:rms@example.net").unwrap();
  1005. ///
  1006. /// let result = url.set_port(Some(80));
  1007. /// assert!(result.is_err());
  1008. ///
  1009. /// let result = url.set_port(None);
  1010. /// assert!(result.is_err());
  1011. /// ```
  1012. pub fn set_port(&mut self, mut port: Option<u16>) -> Result<(), ()> {
  1013. if !self.has_host() || self.scheme() == "file" {
  1014. return Err(())
  1015. }
  1016. if port.is_some() && port == parser::default_port(self.scheme()) {
  1017. port = None
  1018. }
  1019. self.set_port_internal(port);
  1020. Ok(())
  1021. }
  1022. fn set_port_internal(&mut self, port: Option<u16>) {
  1023. match (self.port, port) {
  1024. (None, None) => {}
  1025. (Some(_), None) => {
  1026. self.serialization.drain(self.host_end as usize .. self.path_start as usize);
  1027. let offset = self.path_start - self.host_end;
  1028. self.path_start = self.host_end;
  1029. if let Some(ref mut index) = self.query_start { *index -= offset }
  1030. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  1031. }
  1032. (Some(old), Some(new)) if old == new => {}
  1033. (_, Some(new)) => {
  1034. let path_and_after = self.slice(self.path_start..).to_owned();
  1035. self.serialization.truncate(self.host_end as usize);
  1036. write!(&mut self.serialization, ":{}", new).unwrap();
  1037. let old_path_start = self.path_start;
  1038. let new_path_start = to_u32(self.serialization.len()).unwrap();
  1039. self.path_start = new_path_start;
  1040. let adjust = |index: &mut u32| {
  1041. *index -= old_path_start;
  1042. *index += new_path_start;
  1043. };
  1044. if let Some(ref mut index) = self.query_start { adjust(index) }
  1045. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1046. self.serialization.push_str(&path_and_after);
  1047. }
  1048. }
  1049. self.port = port;
  1050. }
  1051. /// Change this URL’s host.
  1052. ///
  1053. /// If this URL is cannot-be-a-base or there is an error parsing the given `host`,
  1054. /// do nothing and return `Err`.
  1055. ///
  1056. /// Removing the host (calling this with `None`)
  1057. /// will also remove any username, password, and port number.
  1058. ///
  1059. /// # Examples
  1060. ///
  1061. /// Change host:
  1062. ///
  1063. /// ```
  1064. /// use url::Url;
  1065. ///
  1066. /// let mut url = Url::parse("https://example.net").unwrap();
  1067. /// let result = url.set_host(Some("rust-lang.org"));
  1068. /// assert!(result.is_ok());
  1069. /// assert_eq!(url.as_str(), "https://rust-lang.org/");
  1070. /// ```
  1071. ///
  1072. /// Remove host:
  1073. ///
  1074. /// ```
  1075. /// use url::Url;
  1076. ///
  1077. /// let mut url = Url::parse("foo://example.net").unwrap();
  1078. /// let result = url.set_host(None);
  1079. /// assert!(result.is_ok());
  1080. /// assert_eq!(url.as_str(), "foo:/");
  1081. /// ```
  1082. ///
  1083. /// Cannot remove host for 'special' schemes (e.g. `http`):
  1084. ///
  1085. /// ```
  1086. /// use url::Url;
  1087. ///
  1088. /// let mut url = Url::parse("https://example.net").unwrap();
  1089. /// let result = url.set_host(None);
  1090. /// assert!(result.is_err());
  1091. /// assert_eq!(url.as_str(), "https://example.net/");
  1092. /// ```
  1093. ///
  1094. /// Cannot change or remove host for cannot-be-a-base URLs:
  1095. ///
  1096. /// ```
  1097. /// use url::Url;
  1098. ///
  1099. /// let mut url = Url::parse("mailto:rms@example.net").unwrap();
  1100. ///
  1101. /// let result = url.set_host(Some("rust-lang.org"));
  1102. /// assert!(result.is_err());
  1103. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1104. ///
  1105. /// let result = url.set_host(None);
  1106. /// assert!(result.is_err());
  1107. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1108. /// ```
  1109. pub fn set_host(&mut self, host: Option<&str>) -> Result<(), ParseError> {
  1110. if self.cannot_be_a_base() {
  1111. return Err(ParseError::SetHostOnCannotBeABaseUrl)
  1112. }
  1113. if let Some(host) = host {
  1114. if host == "" && SchemeType::from(self.scheme()).is_special() {
  1115. return Err(ParseError::EmptyHost);
  1116. }
  1117. self.set_host_internal(try!(Host::parse(host)), None)
  1118. } else if self.has_host() {
  1119. if SchemeType::from(self.scheme()).is_special() {
  1120. return Err(ParseError::EmptyHost)
  1121. }
  1122. debug_assert!(self.byte_at(self.scheme_end) == b':');
  1123. debug_assert!(self.byte_at(self.path_start) == b'/');
  1124. let new_path_start = self.scheme_end + 1;
  1125. self.serialization.drain(new_path_start as usize..self.path_start as usize);
  1126. let offset = self.path_start - new_path_start;
  1127. self.path_start = new_path_start;
  1128. self.username_end = new_path_start;
  1129. self.host_start = new_path_start;
  1130. self.host_end = new_path_start;
  1131. self.port = None;
  1132. if let Some(ref mut index) = self.query_start { *index -= offset }
  1133. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  1134. }
  1135. Ok(())
  1136. }
  1137. /// opt_new_port: None means leave unchanged, Some(None) means remove any port number.
  1138. fn set_host_internal(&mut self, host: Host<String>, opt_new_port: Option<Option<u16>>) {
  1139. let old_suffix_pos = if opt_new_port.is_some() { self.path_start } else { self.host_end };
  1140. let suffix = self.slice(old_suffix_pos..).to_owned();
  1141. self.serialization.truncate(self.host_start as usize);
  1142. if !self.has_authority() {
  1143. debug_assert!(self.slice(self.scheme_end..self.host_start) == ":");
  1144. debug_assert!(self.username_end == self.host_start);
  1145. self.serialization.push('/');
  1146. self.serialization.push('/');
  1147. self.username_end += 2;
  1148. self.host_start += 2;
  1149. }
  1150. write!(&mut self.serialization, "{}", host).unwrap();
  1151. self.host_end = to_u32(self.serialization.len()).unwrap();
  1152. self.host = host.into();
  1153. if let Some(new_port) = opt_new_port {
  1154. self.port = new_port;
  1155. if let Some(port) = new_port {
  1156. write!(&mut self.serialization, ":{}", port).unwrap();
  1157. }
  1158. }
  1159. let new_suffix_pos = to_u32(self.serialization.len()).unwrap();
  1160. self.serialization.push_str(&suffix);
  1161. let adjust = |index: &mut u32| {
  1162. *index -= old_suffix_pos;
  1163. *index += new_suffix_pos;
  1164. };
  1165. adjust(&mut self.path_start);
  1166. if let Some(ref mut index) = self.query_start { adjust(index) }
  1167. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1168. }
  1169. /// Change this URL’s host to the given IP address.
  1170. ///
  1171. /// If this URL is cannot-be-a-base, do nothing and return `Err`.
  1172. ///
  1173. /// Compared to `Url::set_host`, this skips the host parser.
  1174. pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ()> {
  1175. if self.cannot_be_a_base() {
  1176. return Err(())
  1177. }
  1178. let address = match address {
  1179. IpAddr::V4(address) => Host::Ipv4(address),
  1180. IpAddr::V6(address) => Host::Ipv6(address),
  1181. };
  1182. self.set_host_internal(address, None);
  1183. Ok(())
  1184. }
  1185. /// Change this URL’s password.
  1186. ///
  1187. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1188. pub fn set_password(&mut self, password: Option<&str>) -> Result<(), ()> {
  1189. if !self.has_host() {
  1190. return Err(())
  1191. }
  1192. if let Some(password) = password {
  1193. let host_and_after = self.slice(self.host_start..).to_owned();
  1194. self.serialization.truncate(self.username_end as usize);
  1195. self.serialization.push(':');
  1196. self.serialization.extend(utf8_percent_encode(password, USERINFO_ENCODE_SET));
  1197. self.serialization.push('@');
  1198. let old_host_start = self.host_start;
  1199. let new_host_start = to_u32(self.serialization.len()).unwrap();
  1200. let adjust = |index: &mut u32| {
  1201. *index -= old_host_start;
  1202. *index += new_host_start;
  1203. };
  1204. self.host_start = new_host_start;
  1205. adjust(&mut self.host_end);
  1206. adjust(&mut self.path_start);
  1207. if let Some(ref mut index) = self.query_start { adjust(index) }
  1208. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1209. self.serialization.push_str(&host_and_after);
  1210. } else if self.byte_at(self.username_end) == b':' { // If there is a password to remove
  1211. let has_username_or_password = self.byte_at(self.host_start - 1) == b'@';
  1212. debug_assert!(has_username_or_password);
  1213. let username_start = self.scheme_end + 3;
  1214. let empty_username = username_start == self.username_end;
  1215. let start = self.username_end; // Remove the ':'
  1216. let end = if empty_username {
  1217. self.host_start // Remove the '@' as well
  1218. } else {
  1219. self.host_start - 1 // Keep the '@' to separate the username from the host
  1220. };
  1221. self.serialization.drain(start as usize .. end as usize);
  1222. let offset = end - start;
  1223. self.host_start -= offset;
  1224. self.host_end -= offset;
  1225. self.path_start -= offset;
  1226. if let Some(ref mut index) = self.query_start { *index -= offset }
  1227. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  1228. }
  1229. Ok(())
  1230. }
  1231. /// Change this URL’s username.
  1232. ///
  1233. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1234. pub fn set_username(&mut self, username: &str) -> Result<(), ()> {
  1235. if !self.has_host() {
  1236. return Err(())
  1237. }
  1238. let username_start = self.scheme_end + 3;
  1239. debug_assert!(self.slice(self.scheme_end..username_start) == "://");
  1240. if self.slice(username_start..self.username_end) == username {
  1241. return Ok(())
  1242. }
  1243. let after_username = self.slice(self.username_end..).to_owned();
  1244. self.serialization.truncate(username_start as usize);
  1245. self.serialization.extend(utf8_percent_encode(username, USERINFO_ENCODE_SET));
  1246. let mut removed_bytes = self.username_end;
  1247. self.username_end = to_u32(self.serialization.len()).unwrap();
  1248. let mut added_bytes = self.username_end;
  1249. let new_username_is_empty = self.username_end == username_start;
  1250. match (new_username_is_empty, after_username.chars().next()) {
  1251. (true, Some('@')) => {
  1252. removed_bytes += 1;
  1253. self.serialization.push_str(&after_username[1..]);
  1254. }
  1255. (false, Some('@')) | (_, Some(':')) | (true, _) => {
  1256. self.serialization.push_str(&after_username);
  1257. }
  1258. (false, _) => {
  1259. added_bytes += 1;
  1260. self.serialization.push('@');
  1261. self.serialization.push_str(&after_username);
  1262. }
  1263. }
  1264. let adjust = |index: &mut u32| {
  1265. *index -= removed_bytes;
  1266. *index += added_bytes;
  1267. };
  1268. adjust(&mut self.host_start);
  1269. adjust(&mut self.host_end);
  1270. adjust(&mut self.path_start);
  1271. if let Some(ref mut index) = self.query_start { adjust(index) }
  1272. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1273. Ok(())
  1274. }
  1275. /// Change this URL’s scheme.
  1276. ///
  1277. /// Do nothing and return `Err` if:
  1278. /// * The new scheme is not in `[a-zA-Z][a-zA-Z0-9+.-]+`
  1279. /// * This URL is cannot-be-a-base and the new scheme is one of
  1280. /// `http`, `https`, `ws`, `wss`, `ftp`, or `gopher`
  1281. ///
  1282. /// # Examples
  1283. ///
  1284. /// Change the URL’s scheme from `https` to `foo`:
  1285. ///
  1286. /// ```
  1287. /// use url::Url;
  1288. ///
  1289. /// let mut url = Url::parse("https://example.net").unwrap();
  1290. /// let result = url.set_scheme("foo");
  1291. /// assert_eq!(url.as_str(), "foo://example.net/");
  1292. /// assert!(result.is_ok());
  1293. /// ```
  1294. ///
  1295. ///
  1296. /// Cannot change URL’s scheme from `https` to `foõ`:
  1297. ///
  1298. /// ```
  1299. /// use url::Url;
  1300. ///
  1301. /// let mut url = Url::parse("https://example.net").unwrap();
  1302. /// let result = url.set_scheme("foõ");
  1303. /// assert_eq!(url.as_str(), "https://example.net/");
  1304. /// assert!(result.is_err());
  1305. /// ```
  1306. ///
  1307. /// Cannot change URL’s scheme from `mailto` (cannot-be-a-base) to `https`:
  1308. ///
  1309. /// ```
  1310. /// use url::Url;
  1311. ///
  1312. /// let mut url = Url::parse("mailto:rms@example.net").unwrap();
  1313. /// let result = url.set_scheme("https");
  1314. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1315. /// assert!(result.is_err());
  1316. /// ```
  1317. pub fn set_scheme(&mut self, scheme: &str) -> Result<(), ()> {
  1318. let mut parser = Parser::for_setter(String::new());
  1319. let remaining = try!(parser.parse_scheme(parser::Input::new(scheme)));
  1320. if !remaining.is_empty() ||
  1321. (!self.has_host() && SchemeType::from(&parser.serialization).is_special()) {
  1322. return Err(())
  1323. }
  1324. let old_scheme_end = self.scheme_end;
  1325. let new_scheme_end = to_u32(parser.serialization.len()).unwrap();
  1326. let adjust = |index: &mut u32| {
  1327. *index -= old_scheme_end;
  1328. *index += new_scheme_end;
  1329. };
  1330. self.scheme_end = new_scheme_end;
  1331. adjust(&mut self.username_end);
  1332. adjust(&mut self.host_start);
  1333. adjust(&mut self.host_end);
  1334. adjust(&mut self.path_start);
  1335. if let Some(ref mut index) = self.query_start { adjust(index) }
  1336. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1337. parser.serialization.push_str(self.slice(old_scheme_end..));
  1338. self.serialization = parser.serialization;
  1339. Ok(())
  1340. }
  1341. /// Convert a file name as `std::path::Path` into an URL in the `file` scheme.
  1342. ///
  1343. /// This returns `Err` if the given path is not absolute or,
  1344. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`).
  1345. ///
  1346. /// # Examples
  1347. ///
  1348. /// On Unix-like platforms:
  1349. ///
  1350. /// ```
  1351. /// # if cfg!(unix) {
  1352. /// use url::Url;
  1353. ///
  1354. /// let url = Url::from_file_path("/tmp/foo.txt").unwrap();
  1355. /// assert_eq!(url.as_str(), "file:///tmp/foo.txt");
  1356. ///
  1357. /// let url = Url::from_file_path("../foo.txt");
  1358. /// assert!(url.is_err());
  1359. ///
  1360. /// let url = Url::from_file_path("https://google.com/");
  1361. /// assert!(url.is_err());
  1362. /// # }
  1363. /// ```
  1364. pub fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  1365. let mut serialization = "file://".to_owned();
  1366. let path_start = serialization.len() as u32;
  1367. try!(path_to_file_url_segments(path.as_ref(), &mut serialization));
  1368. Ok(Url {
  1369. serialization: serialization,
  1370. scheme_end: "file".len() as u32,
  1371. username_end: path_start,
  1372. host_start: path_start,
  1373. host_end: path_start,
  1374. host: HostInternal::None,
  1375. port: None,
  1376. path_start: path_start,
  1377. query_start: None,
  1378. fragment_start: None,
  1379. })
  1380. }
  1381. /// Convert a directory name as `std::path::Path` into an URL in the `file` scheme.
  1382. ///
  1383. /// This returns `Err` if the given path is not absolute or,
  1384. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`).
  1385. ///
  1386. /// Compared to `from_file_path`, this ensure that URL’s the path has a trailing slash
  1387. /// so that the entire path is considered when using this URL as a base URL.
  1388. ///
  1389. /// For example:
  1390. ///
  1391. /// * `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
  1392. /// as the base URL is `file:///var/www/index.html`
  1393. /// * `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www"))`
  1394. /// as the base URL is `file:///var/index.html`, which might not be what was intended.
  1395. ///
  1396. /// Note that `std::path` does not consider trailing slashes significant
  1397. /// and usually does not include them (e.g. in `Path::parent()`).
  1398. pub fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  1399. let mut url = try!(Url::from_file_path(path));
  1400. if !url.serialization.ends_with('/') {
  1401. url.serialization.push('/')
  1402. }
  1403. Ok(url)
  1404. }
  1405. /// Assuming the URL is in the `file` scheme or similar,
  1406. /// convert its path to an absolute `std::path::Path`.
  1407. ///
  1408. /// **Note:** This does not actually check the URL’s `scheme`,
  1409. /// and may give nonsensical results for other schemes.
  1410. /// It is the user’s responsibility to check the URL’s scheme before calling this.
  1411. ///
  1412. /// ```
  1413. /// # use url::Url;
  1414. /// # let url = Url::parse("file:///etc/passwd").unwrap();
  1415. /// let path = url.to_file_path();
  1416. /// ```
  1417. ///
  1418. /// Returns `Err` if the host is neither empty nor `"localhost"`,
  1419. /// or if `Path::new_opt()` returns `None`.
  1420. /// (That is, if the percent-decoded path contains a NUL byte or,
  1421. /// for a Windows path, is not UTF-8.)
  1422. #[inline]
  1423. pub fn to_file_path(&self) -> Result<PathBuf, ()> {
  1424. // FIXME: Figure out what to do w.r.t host.
  1425. if matches!(self.host(), None | Some(Host::Domain("localhost"))) {
  1426. if let Some(segments) = self.path_segments() {
  1427. return file_url_segments_to_pathbuf(segments)
  1428. }
  1429. }
  1430. Err(())
  1431. }
  1432. // Private helper methods:
  1433. #[inline]
  1434. fn slice<R>(&self, range: R) -> &str where R: RangeArg {
  1435. range.slice_of(&self.serialization)
  1436. }
  1437. #[inline]
  1438. fn byte_at(&self, i: u32) -> u8 {
  1439. self.serialization.as_bytes()[i as usize]
  1440. }
  1441. }
  1442. /// Return an error if `Url::host` or `Url::port_or_known_default` return `None`.
  1443. impl ToSocketAddrs for Url {
  1444. type Iter = SocketAddrs;
  1445. fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
  1446. try!(self.with_default_port(|_| Err(()))).to_socket_addrs()
  1447. }
  1448. }
  1449. /// Parse a string as an URL, without a base URL or encoding override.
  1450. impl str::FromStr for Url {
  1451. type Err = ParseError;
  1452. #[inline]
  1453. fn from_str(input: &str) -> Result<Url, ::ParseError> {
  1454. Url::parse(input)
  1455. }
  1456. }
  1457. /// Display the serialization of this URL.
  1458. impl fmt::Display for Url {
  1459. #[inline]
  1460. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  1461. fmt::Display::fmt(&self.serialization, formatter)
  1462. }
  1463. }
  1464. /// Debug the serialization of this URL.
  1465. impl fmt::Debug for Url {
  1466. #[inline]
  1467. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  1468. fmt::Debug::fmt(&self.serialization, formatter)
  1469. }
  1470. }
  1471. /// URLs compare like their serialization.
  1472. impl Eq for Url {}
  1473. /// URLs compare like their serialization.
  1474. impl PartialEq for Url {
  1475. #[inline]
  1476. fn eq(&self, other: &Self) -> bool {
  1477. self.serialization == other.serialization
  1478. }
  1479. }
  1480. /// URLs compare like their serialization.
  1481. impl Ord for Url {
  1482. #[inline]
  1483. fn cmp(&self, other: &Self) -> cmp::Ordering {
  1484. self.serialization.cmp(&other.serialization)
  1485. }
  1486. }
  1487. /// URLs compare like their serialization.
  1488. impl PartialOrd for Url {
  1489. #[inline]
  1490. fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
  1491. self.serialization.partial_cmp(&other.serialization)
  1492. }
  1493. }
  1494. /// URLs hash like their serialization.
  1495. impl hash::Hash for Url {
  1496. #[inline]
  1497. fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
  1498. hash::Hash::hash(&self.serialization, state)
  1499. }
  1500. }
  1501. /// Return the serialization of this URL.
  1502. impl AsRef<str> for Url {
  1503. #[inline]
  1504. fn as_ref(&self) -> &str {
  1505. &self.serialization
  1506. }
  1507. }
  1508. trait RangeArg {
  1509. fn slice_of<'a>(&self, s: &'a str) -> &'a str;
  1510. }
  1511. impl RangeArg for Range<u32> {
  1512. #[inline]
  1513. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  1514. &s[self.start as usize .. self.end as usize]
  1515. }
  1516. }
  1517. impl RangeArg for RangeFrom<u32> {
  1518. #[inline]
  1519. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  1520. &s[self.start as usize ..]
  1521. }
  1522. }
  1523. impl RangeArg for RangeTo<u32> {
  1524. #[inline]
  1525. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  1526. &s[.. self.end as usize]
  1527. }
  1528. }
  1529. #[cfg(feature="rustc-serialize")]
  1530. impl rustc_serialize::Encodable for Url {
  1531. fn encode<S: rustc_serialize::Encoder>(&self, encoder: &mut S) -> Result<(), S::Error> {
  1532. encoder.emit_str(self.as_str())
  1533. }
  1534. }
  1535. #[cfg(feature="rustc-serialize")]
  1536. impl rustc_serialize::Decodable for Url {
  1537. fn decode<D: rustc_serialize::Decoder>(decoder: &mut D) -> Result<Url, D::Error> {
  1538. Url::parse(&*try!(decoder.read_str())).map_err(|error| {
  1539. decoder.error(&format!("URL parsing error: {}", error))
  1540. })
  1541. }
  1542. }
  1543. /// Serializes this URL into a `serde` stream.
  1544. ///
  1545. /// This implementation is only available if the `serde` Cargo feature is enabled.
  1546. #[cfg(feature="serde")]
  1547. impl serde::Serialize for Url {
  1548. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
  1549. serializer.serialize_str(self.as_str())
  1550. }
  1551. }
  1552. /// Deserializes this URL from a `serde` stream.
  1553. ///
  1554. /// This implementation is only available if the `serde` Cargo feature is enabled.
  1555. #[cfg(feature="serde")]
  1556. impl serde::Deserialize for Url {
  1557. fn deserialize<D>(deserializer: &mut D) -> Result<Url, D::Error> where D: serde::Deserializer {
  1558. let string_representation: String = try!(serde::Deserialize::deserialize(deserializer));
  1559. Url::parse(&string_representation).map_err(|err| {
  1560. serde::Error::invalid_value(err.description())
  1561. })
  1562. }
  1563. }
  1564. #[cfg(any(unix, target_os = "redox"))]
  1565. fn path_to_file_url_segments(path: &Path, serialization: &mut String) -> Result<(), ()> {
  1566. use std::os::unix::prelude::OsStrExt;
  1567. if !path.is_absolute() {
  1568. return Err(())
  1569. }
  1570. let mut empty = true;
  1571. // skip the root component
  1572. for component in path.components().skip(1) {
  1573. empty = false;
  1574. serialization.push('/');
  1575. serialization.extend(percent_encode(
  1576. component.as_os_str().as_bytes(), PATH_SEGMENT_ENCODE_SET));
  1577. }
  1578. if empty {
  1579. // An URL’s path must not be empty.
  1580. serialization.push('/');
  1581. }
  1582. Ok(())
  1583. }
  1584. #[cfg(windows)]
  1585. fn path_to_file_url_segments(path: &Path, serialization: &mut String) -> Result<(), ()> {
  1586. path_to_file_url_segments_windows(path, serialization)
  1587. }
  1588. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  1589. #[cfg_attr(not(windows), allow(dead_code))]
  1590. fn path_to_file_url_segments_windows(path: &Path, serialization: &mut String) -> Result<(), ()> {
  1591. use std::path::{Prefix, Component};
  1592. if !path.is_absolute() {
  1593. return Err(())
  1594. }
  1595. let mut components = path.components();
  1596. let disk = match components.next() {
  1597. Some(Component::Prefix(ref p)) => match p.kind() {
  1598. Prefix::Disk(byte) => byte,
  1599. Prefix::VerbatimDisk(byte) => byte,
  1600. _ => return Err(()),
  1601. },
  1602. // FIXME: do something with UNC and other prefixes?
  1603. _ => return Err(())
  1604. };
  1605. // Start with the prefix, e.g. "C:"
  1606. serialization.push('/');
  1607. serialization.push(disk as char);
  1608. serialization.push(':');
  1609. for component in components {
  1610. if component == Component::RootDir { continue }
  1611. // FIXME: somehow work with non-unicode?
  1612. let component = try!(component.as_os_str().to_str().ok_or(()));
  1613. serialization.push('/');
  1614. serialization.extend(percent_encode(component.as_bytes(), PATH_SEGMENT_ENCODE_SET));
  1615. }
  1616. Ok(())
  1617. }
  1618. #[cfg(any(unix, target_os = "redox"))]
  1619. fn file_url_segments_to_pathbuf(segments: str::Split<char>) -> Result<PathBuf, ()> {
  1620. use std::ffi::OsStr;
  1621. use std::os::unix::prelude::OsStrExt;
  1622. use std::path::PathBuf;
  1623. let mut bytes = Vec::new();
  1624. for segment in segments {
  1625. bytes.push(b'/');
  1626. bytes.extend(percent_decode(segment.as_bytes()));
  1627. }
  1628. let os_str = OsStr::from_bytes(&bytes);
  1629. let path = PathBuf::from(os_str);
  1630. debug_assert!(path.is_absolute(),
  1631. "to_file_path() failed to produce an absolute Path");
  1632. Ok(path)
  1633. }
  1634. #[cfg(windows)]
  1635. fn file_url_segments_to_pathbuf(segments: str::Split<char>) -> Result<PathBuf, ()> {
  1636. file_url_segments_to_pathbuf_windows(segments)
  1637. }
  1638. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  1639. #[cfg_attr(not(windows), allow(dead_code))]
  1640. fn file_url_segments_to_pathbuf_windows(mut segments: str::Split<char>) -> Result<PathBuf, ()> {
  1641. let first = try!(segments.next().ok_or(()));
  1642. let mut string = match first.len() {
  1643. 2 => {
  1644. if !first.starts_with(parser::ascii_alpha) || first.as_bytes()[1] != b':' {
  1645. return Err(())
  1646. }
  1647. first.to_owned()
  1648. },
  1649. 4 => {
  1650. if !first.starts_with(parser::ascii_alpha) {
  1651. return Err(())
  1652. }
  1653. let bytes = first.as_bytes();
  1654. if bytes[1] != b'%' || bytes[2] != b'3' || (bytes[3] != b'a' && bytes[3] != b'A') {
  1655. return Err(())
  1656. }
  1657. first[0..1].to_owned() + ":"
  1658. },
  1659. _ => return Err(()),
  1660. };
  1661. for segment in segments {
  1662. string.push('\\');
  1663. // Currently non-unicode windows paths cannot be represented
  1664. match String::from_utf8(percent_decode(segment.as_bytes()).collect()) {
  1665. Ok(s) => string.push_str(&s),
  1666. Err(..) => return Err(()),
  1667. }
  1668. }
  1669. let path = PathBuf::from(string);
  1670. debug_assert!(path.is_absolute(),
  1671. "to_file_path() failed to produce an absolute Path");
  1672. Ok(path)
  1673. }
  1674. fn io_error<T>(reason: &str) -> io::Result<T> {
  1675. Err(io::Error::new(io::ErrorKind::InvalidData, reason))
  1676. }
  1677. /// Implementation detail of `Url::query_pairs_mut`. Typically not used directly.
  1678. pub struct UrlQuery<'a> {
  1679. url: &'a mut Url,
  1680. fragment: Option<String>,
  1681. }
  1682. impl<'a> Drop for UrlQuery<'a> {
  1683. fn drop(&mut self) {
  1684. self.url.restore_already_parsed_fragment(self.fragment.take())
  1685. }
  1686. }