lib.rs 64 KB

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