lib.rs 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753
  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, Position};
  20. # use url::ParseError;
  21. # fn run() -> Result<(), ParseError> {
  22. let issue_list_url = Url::parse(
  23. "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"
  24. )?;
  25. assert!(issue_list_url.scheme() == "https");
  26. assert!(issue_list_url.username() == "");
  27. assert!(issue_list_url.password() == None);
  28. assert!(issue_list_url.host_str() == Some("github.com"));
  29. assert!(issue_list_url.host() == Some(Host::Domain("github.com")));
  30. assert!(issue_list_url.port() == None);
  31. assert!(issue_list_url.path() == "/rust-lang/rust/issues");
  32. assert!(issue_list_url.path_segments().map(|c| c.collect::<Vec<_>>()) ==
  33. Some(vec!["rust-lang", "rust", "issues"]));
  34. assert!(issue_list_url.query() == Some("labels=E-easy&state=open"));
  35. assert!(&issue_list_url[Position::BeforePath..] == "/rust-lang/rust/issues?labels=E-easy&state=open");
  36. assert!(issue_list_url.fragment() == None);
  37. assert!(!issue_list_url.cannot_be_a_base());
  38. # Ok(())
  39. # }
  40. # run().unwrap();
  41. ```
  42. Some URLs are said to be *cannot-be-a-base*:
  43. they don’t have a username, password, host, or port,
  44. and their "path" is an arbitrary string rather than slash-separated segments:
  45. ```
  46. use url::Url;
  47. # use url::ParseError;
  48. # fn run() -> Result<(), ParseError> {
  49. let data_url = Url::parse("data:text/plain,Hello?World#")?;
  50. assert!(data_url.cannot_be_a_base());
  51. assert!(data_url.scheme() == "data");
  52. assert!(data_url.path() == "text/plain,Hello");
  53. assert!(data_url.path_segments().is_none());
  54. assert!(data_url.query() == Some("World"));
  55. assert!(data_url.fragment() == Some(""));
  56. # Ok(())
  57. # }
  58. # run().unwrap();
  59. ```
  60. ## Serde
  61. Enable the `serde` feature to include `Deserialize` and `Serialize` implementations for `url::Url`.
  62. # Base URL
  63. Many contexts allow URL *references* that can be relative to a *base URL*:
  64. ```html
  65. <link rel="stylesheet" href="../main.css">
  66. ```
  67. Since parsed URLs are absolute, giving a base is required for parsing relative URLs:
  68. ```
  69. use url::{Url, ParseError};
  70. assert!(Url::parse("../main.css") == Err(ParseError::RelativeUrlWithoutBase))
  71. ```
  72. Use the `join` method on an `Url` to use it as a base URL:
  73. ```
  74. use url::Url;
  75. # use url::ParseError;
  76. # fn run() -> Result<(), ParseError> {
  77. let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html")?;
  78. let css_url = this_document.join("../main.css")?;
  79. assert_eq!(css_url.as_str(), "http://servo.github.io/rust-url/main.css");
  80. # Ok(())
  81. # }
  82. # run().unwrap();
  83. ```
  84. # Feature: `serde`
  85. If you enable the `serde` feature, [`Url`](struct.Url.html) will implement
  86. [`serde::Serialize`](https://docs.rs/serde/1/serde/trait.Serialize.html) and
  87. [`serde::Deserialize`](https://docs.rs/serde/1/serde/trait.Deserialize.html).
  88. See [serde documentation](https://serde.rs) for more information.
  89. ```toml
  90. url = { version = "2", features = ["serde"] }
  91. ```
  92. */
  93. #![doc(html_root_url = "https://docs.rs/url/2.2.1")]
  94. #[macro_use]
  95. extern crate matches;
  96. pub use form_urlencoded;
  97. #[cfg(feature = "serde")]
  98. extern crate serde;
  99. use crate::host::HostInternal;
  100. use crate::parser::{to_u32, Context, Parser, SchemeType, PATH_SEGMENT, USERINFO};
  101. use percent_encoding::{percent_decode, percent_encode, utf8_percent_encode};
  102. use std::borrow::Borrow;
  103. use std::cmp;
  104. use std::fmt::{self, Write};
  105. use std::hash;
  106. use std::io;
  107. use std::mem;
  108. use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
  109. use std::ops::{Range, RangeFrom, RangeTo};
  110. use std::path::{Path, PathBuf};
  111. use std::str;
  112. use std::convert::TryFrom;
  113. pub use crate::host::Host;
  114. pub use crate::origin::{OpaqueOrigin, Origin};
  115. pub use crate::parser::{ParseError, SyntaxViolation};
  116. pub use crate::path_segments::PathSegmentsMut;
  117. pub use crate::slicing::Position;
  118. pub use form_urlencoded::EncodingOverride;
  119. mod host;
  120. mod origin;
  121. mod parser;
  122. mod path_segments;
  123. mod slicing;
  124. #[doc(hidden)]
  125. pub mod quirks;
  126. /// A parsed URL record.
  127. #[derive(Clone)]
  128. pub struct Url {
  129. /// Syntax in pseudo-BNF:
  130. ///
  131. /// url = scheme ":" [ hierarchical | non-hierarchical ] [ "?" query ]? [ "#" fragment ]?
  132. /// non-hierarchical = non-hierarchical-path
  133. /// non-hierarchical-path = /* Does not start with "/" */
  134. /// hierarchical = authority? hierarchical-path
  135. /// authority = "//" userinfo? host [ ":" port ]?
  136. /// userinfo = username [ ":" password ]? "@"
  137. /// hierarchical-path = [ "/" path-segment ]+
  138. serialization: String,
  139. // Components
  140. scheme_end: u32, // Before ':'
  141. username_end: u32, // Before ':' (if a password is given) or '@' (if not)
  142. host_start: u32,
  143. host_end: u32,
  144. host: HostInternal,
  145. port: Option<u16>,
  146. path_start: u32, // Before initial '/', if any
  147. query_start: Option<u32>, // Before '?', unlike Position::QueryStart
  148. fragment_start: Option<u32>, // Before '#', unlike Position::FragmentStart
  149. }
  150. /// Full configuration for the URL parser.
  151. #[derive(Copy, Clone)]
  152. pub struct ParseOptions<'a> {
  153. base_url: Option<&'a Url>,
  154. encoding_override: EncodingOverride<'a>,
  155. violation_fn: Option<&'a dyn Fn(SyntaxViolation)>,
  156. }
  157. impl<'a> ParseOptions<'a> {
  158. /// Change the base URL
  159. pub fn base_url(mut self, new: Option<&'a Url>) -> Self {
  160. self.base_url = new;
  161. self
  162. }
  163. /// Override the character encoding of query strings.
  164. /// This is a legacy concept only relevant for HTML.
  165. pub fn encoding_override(mut self, new: EncodingOverride<'a>) -> Self {
  166. self.encoding_override = new;
  167. self
  168. }
  169. /// Call the provided function or closure for a non-fatal `SyntaxViolation`
  170. /// when it occurs during parsing. Note that since the provided function is
  171. /// `Fn`, the caller might need to utilize _interior mutability_, such as with
  172. /// a `RefCell`, to collect the violations.
  173. ///
  174. /// ## Example
  175. /// ```
  176. /// use std::cell::RefCell;
  177. /// use url::{Url, SyntaxViolation};
  178. /// # use url::ParseError;
  179. /// # fn run() -> Result<(), url::ParseError> {
  180. /// let violations = RefCell::new(Vec::new());
  181. /// let url = Url::options()
  182. /// .syntax_violation_callback(Some(&|v| violations.borrow_mut().push(v)))
  183. /// .parse("https:////example.com")?;
  184. /// assert_eq!(url.as_str(), "https://example.com/");
  185. /// assert_eq!(violations.into_inner(),
  186. /// vec!(SyntaxViolation::ExpectedDoubleSlash));
  187. /// # Ok(())
  188. /// # }
  189. /// # run().unwrap();
  190. /// ```
  191. pub fn syntax_violation_callback(mut self, new: Option<&'a dyn Fn(SyntaxViolation)>) -> Self {
  192. self.violation_fn = new;
  193. self
  194. }
  195. /// Parse an URL string with the configuration so far.
  196. pub fn parse(self, input: &str) -> Result<Url, crate::ParseError> {
  197. Parser {
  198. serialization: String::with_capacity(input.len()),
  199. base_url: self.base_url,
  200. query_encoding_override: self.encoding_override,
  201. violation_fn: self.violation_fn,
  202. context: Context::UrlParser,
  203. }
  204. .parse_url(input)
  205. }
  206. }
  207. impl Url {
  208. /// Parse an absolute URL from a string.
  209. ///
  210. /// # Examples
  211. ///
  212. /// ```rust
  213. /// use url::Url;
  214. /// # use url::ParseError;
  215. ///
  216. /// # fn run() -> Result<(), ParseError> {
  217. /// let url = Url::parse("https://example.net")?;
  218. /// # Ok(())
  219. /// # }
  220. /// # run().unwrap();
  221. /// ```
  222. ///
  223. /// # Errors
  224. ///
  225. /// If the function can not parse an absolute URL from the given string,
  226. /// a [`ParseError`] variant will be returned.
  227. ///
  228. /// [`ParseError`]: enum.ParseError.html
  229. #[inline]
  230. pub fn parse(input: &str) -> Result<Url, crate::ParseError> {
  231. Url::options().parse(input)
  232. }
  233. /// Parse an absolute URL from a string and add params to its query string.
  234. ///
  235. /// Existing params are not removed.
  236. ///
  237. /// # Examples
  238. ///
  239. /// ```rust
  240. /// use url::Url;
  241. /// # use url::ParseError;
  242. ///
  243. /// # fn run() -> Result<(), ParseError> {
  244. /// let url = Url::parse_with_params("https://example.net?dont=clobberme",
  245. /// &[("lang", "rust"), ("browser", "servo")])?;
  246. /// assert_eq!("https://example.net/?dont=clobberme&lang=rust&browser=servo", url.as_str());
  247. /// # Ok(())
  248. /// # }
  249. /// # run().unwrap();
  250. /// ```
  251. ///
  252. /// # Errors
  253. ///
  254. /// If the function can not parse an absolute URL from the given string,
  255. /// a [`ParseError`] variant will be returned.
  256. ///
  257. /// [`ParseError`]: enum.ParseError.html
  258. #[inline]
  259. pub fn parse_with_params<I, K, V>(input: &str, iter: I) -> Result<Url, crate::ParseError>
  260. where
  261. I: IntoIterator,
  262. I::Item: Borrow<(K, V)>,
  263. K: AsRef<str>,
  264. V: AsRef<str>,
  265. {
  266. let mut url = Url::options().parse(input);
  267. if let Ok(ref mut url) = url {
  268. url.query_pairs_mut().extend_pairs(iter);
  269. }
  270. url
  271. }
  272. /// Parse a string as an URL, with this URL as the base URL.
  273. ///
  274. /// Note: a trailing slash is significant.
  275. /// Without it, the last path component is considered to be a “file” name
  276. /// to be removed to get at the “directory” that is used as the base:
  277. ///
  278. /// # Examples
  279. ///
  280. /// ```rust
  281. /// use url::Url;
  282. /// # use url::ParseError;
  283. ///
  284. /// # fn run() -> Result<(), ParseError> {
  285. /// let base = Url::parse("https://example.net/a/b.html")?;
  286. /// let url = base.join("c.png")?;
  287. /// assert_eq!(url.as_str(), "https://example.net/a/c.png"); // Not /a/b.html/c.png
  288. ///
  289. /// let base = Url::parse("https://example.net/a/b/")?;
  290. /// let url = base.join("c.png")?;
  291. /// assert_eq!(url.as_str(), "https://example.net/a/b/c.png");
  292. /// # Ok(())
  293. /// # }
  294. /// # run().unwrap();
  295. /// ```
  296. ///
  297. /// # Errors
  298. ///
  299. /// If the function can not parse an URL from the given string
  300. /// with this URL as the base URL, a [`ParseError`] variant will be returned.
  301. ///
  302. /// [`ParseError`]: enum.ParseError.html
  303. #[inline]
  304. pub fn join(&self, input: &str) -> Result<Url, crate::ParseError> {
  305. Url::options().base_url(Some(self)).parse(input)
  306. }
  307. /// Return a default `ParseOptions` that can fully configure the URL parser.
  308. ///
  309. /// # Examples
  310. ///
  311. /// Get default `ParseOptions`, then change base url
  312. ///
  313. /// ```rust
  314. /// use url::Url;
  315. /// # use url::ParseError;
  316. /// # fn run() -> Result<(), ParseError> {
  317. /// let options = Url::options();
  318. /// let api = Url::parse("https://api.example.com")?;
  319. /// let base_url = options.base_url(Some(&api));
  320. /// let version_url = base_url.parse("version.json")?;
  321. /// assert_eq!(version_url.as_str(), "https://api.example.com/version.json");
  322. /// # Ok(())
  323. /// # }
  324. /// # run().unwrap();
  325. /// ```
  326. pub fn options<'a>() -> ParseOptions<'a> {
  327. ParseOptions {
  328. base_url: None,
  329. encoding_override: None,
  330. violation_fn: None,
  331. }
  332. }
  333. /// Return the serialization of this URL.
  334. ///
  335. /// This is fast since that serialization is already stored in the `Url` struct.
  336. ///
  337. /// # Examples
  338. ///
  339. /// ```rust
  340. /// use url::Url;
  341. /// # use url::ParseError;
  342. ///
  343. /// # fn run() -> Result<(), ParseError> {
  344. /// let url_str = "https://example.net/";
  345. /// let url = Url::parse(url_str)?;
  346. /// assert_eq!(url.as_str(), url_str);
  347. /// # Ok(())
  348. /// # }
  349. /// # run().unwrap();
  350. /// ```
  351. #[inline]
  352. pub fn as_str(&self) -> &str {
  353. &self.serialization
  354. }
  355. /// Return the serialization of this URL.
  356. ///
  357. /// This consumes the `Url` and takes ownership of the `String` stored in it.
  358. ///
  359. /// # Examples
  360. ///
  361. /// ```rust
  362. /// use url::Url;
  363. /// # use url::ParseError;
  364. ///
  365. /// # fn run() -> Result<(), ParseError> {
  366. /// let url_str = "https://example.net/";
  367. /// let url = Url::parse(url_str)?;
  368. /// assert_eq!(String::from(url), url_str);
  369. /// # Ok(())
  370. /// # }
  371. /// # run().unwrap();
  372. /// ```
  373. #[inline]
  374. #[deprecated(since = "2.3.0", note = "use Into<String>")]
  375. pub fn into_string(self) -> String {
  376. self.into()
  377. }
  378. /// For internal testing, not part of the public API.
  379. ///
  380. /// Methods of the `Url` struct assume a number of invariants.
  381. /// This checks each of these invariants and panic if one is not met.
  382. /// This is for testing rust-url itself.
  383. #[doc(hidden)]
  384. pub fn check_invariants(&self) -> Result<(), String> {
  385. macro_rules! assert {
  386. ($x: expr) => {
  387. if !$x {
  388. return Err(format!(
  389. "!( {} ) for URL {:?}",
  390. stringify!($x),
  391. self.serialization
  392. ));
  393. }
  394. };
  395. }
  396. macro_rules! assert_eq {
  397. ($a: expr, $b: expr) => {
  398. {
  399. let a = $a;
  400. let b = $b;
  401. if a != b {
  402. return Err(format!("{:?} != {:?} ({} != {}) for URL {:?}",
  403. a, b, stringify!($a), stringify!($b),
  404. self.serialization))
  405. }
  406. }
  407. }
  408. }
  409. assert!(self.scheme_end >= 1);
  410. assert!(matches!(self.byte_at(0), b'a'..=b'z' | b'A'..=b'Z'));
  411. assert!(self
  412. .slice(1..self.scheme_end)
  413. .chars()
  414. .all(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '+' | '-' | '.')));
  415. assert_eq!(self.byte_at(self.scheme_end), b':');
  416. if self.slice(self.scheme_end + 1..).starts_with("//") {
  417. // URL with authority
  418. if self.username_end != self.serialization.len() as u32 {
  419. match self.byte_at(self.username_end) {
  420. b':' => {
  421. assert!(self.host_start >= self.username_end + 2);
  422. assert_eq!(self.byte_at(self.host_start - 1), b'@');
  423. }
  424. b'@' => assert!(self.host_start == self.username_end + 1),
  425. _ => assert_eq!(self.username_end, self.scheme_end + 3),
  426. }
  427. }
  428. assert!(self.host_start >= self.username_end);
  429. assert!(self.host_end >= self.host_start);
  430. let host_str = self.slice(self.host_start..self.host_end);
  431. match self.host {
  432. HostInternal::None => assert_eq!(host_str, ""),
  433. HostInternal::Ipv4(address) => assert_eq!(host_str, address.to_string()),
  434. HostInternal::Ipv6(address) => {
  435. let h: Host<String> = Host::Ipv6(address);
  436. assert_eq!(host_str, h.to_string())
  437. }
  438. HostInternal::Domain => {
  439. if SchemeType::from(self.scheme()).is_special() {
  440. assert!(!host_str.is_empty())
  441. }
  442. }
  443. }
  444. if self.path_start == self.host_end {
  445. assert_eq!(self.port, None);
  446. } else {
  447. assert_eq!(self.byte_at(self.host_end), b':');
  448. let port_str = self.slice(self.host_end + 1..self.path_start);
  449. assert_eq!(
  450. self.port,
  451. Some(port_str.parse::<u16>().expect("Couldn't parse port?"))
  452. );
  453. }
  454. assert!(
  455. self.path_start as usize == self.serialization.len()
  456. || matches!(self.byte_at(self.path_start), b'/' | b'#' | b'?')
  457. );
  458. } else {
  459. // Anarchist URL (no authority)
  460. assert_eq!(self.username_end, self.scheme_end + 1);
  461. assert_eq!(self.host_start, self.scheme_end + 1);
  462. assert_eq!(self.host_end, self.scheme_end + 1);
  463. assert_eq!(self.host, HostInternal::None);
  464. assert_eq!(self.port, None);
  465. assert_eq!(self.path_start, self.scheme_end + 1);
  466. }
  467. if let Some(start) = self.query_start {
  468. assert!(start >= self.path_start);
  469. assert_eq!(self.byte_at(start), b'?');
  470. }
  471. if let Some(start) = self.fragment_start {
  472. assert!(start >= self.path_start);
  473. assert_eq!(self.byte_at(start), b'#');
  474. }
  475. if let (Some(query_start), Some(fragment_start)) = (self.query_start, self.fragment_start) {
  476. assert!(fragment_start > query_start);
  477. }
  478. let other = Url::parse(self.as_str()).expect("Failed to parse myself?");
  479. assert_eq!(&self.serialization, &other.serialization);
  480. assert_eq!(self.scheme_end, other.scheme_end);
  481. assert_eq!(self.username_end, other.username_end);
  482. assert_eq!(self.host_start, other.host_start);
  483. assert_eq!(self.host_end, other.host_end);
  484. assert!(
  485. self.host == other.host ||
  486. // XXX No host round-trips to empty host.
  487. // See https://github.com/whatwg/url/issues/79
  488. (self.host_str(), other.host_str()) == (None, Some(""))
  489. );
  490. assert_eq!(self.port, other.port);
  491. assert_eq!(self.path_start, other.path_start);
  492. assert_eq!(self.query_start, other.query_start);
  493. assert_eq!(self.fragment_start, other.fragment_start);
  494. Ok(())
  495. }
  496. /// Return the origin of this URL (<https://url.spec.whatwg.org/#origin>)
  497. ///
  498. /// Note: this returns an opaque origin for `file:` URLs, which causes
  499. /// `url.origin() != url.origin()`.
  500. ///
  501. /// # Examples
  502. ///
  503. /// URL with `ftp` scheme:
  504. ///
  505. /// ```rust
  506. /// use url::{Host, Origin, Url};
  507. /// # use url::ParseError;
  508. ///
  509. /// # fn run() -> Result<(), ParseError> {
  510. /// let url = Url::parse("ftp://example.com/foo")?;
  511. /// assert_eq!(url.origin(),
  512. /// Origin::Tuple("ftp".into(),
  513. /// Host::Domain("example.com".into()),
  514. /// 21));
  515. /// # Ok(())
  516. /// # }
  517. /// # run().unwrap();
  518. /// ```
  519. ///
  520. /// URL with `blob` scheme:
  521. ///
  522. /// ```rust
  523. /// use url::{Host, Origin, Url};
  524. /// # use url::ParseError;
  525. ///
  526. /// # fn run() -> Result<(), ParseError> {
  527. /// let url = Url::parse("blob:https://example.com/foo")?;
  528. /// assert_eq!(url.origin(),
  529. /// Origin::Tuple("https".into(),
  530. /// Host::Domain("example.com".into()),
  531. /// 443));
  532. /// # Ok(())
  533. /// # }
  534. /// # run().unwrap();
  535. /// ```
  536. ///
  537. /// URL with `file` scheme:
  538. ///
  539. /// ```rust
  540. /// use url::{Host, Origin, Url};
  541. /// # use url::ParseError;
  542. ///
  543. /// # fn run() -> Result<(), ParseError> {
  544. /// let url = Url::parse("file:///tmp/foo")?;
  545. /// assert!(!url.origin().is_tuple());
  546. ///
  547. /// let other_url = Url::parse("file:///tmp/foo")?;
  548. /// assert!(url.origin() != other_url.origin());
  549. /// # Ok(())
  550. /// # }
  551. /// # run().unwrap();
  552. /// ```
  553. ///
  554. /// URL with other scheme:
  555. ///
  556. /// ```rust
  557. /// use url::{Host, Origin, Url};
  558. /// # use url::ParseError;
  559. ///
  560. /// # fn run() -> Result<(), ParseError> {
  561. /// let url = Url::parse("foo:bar")?;
  562. /// assert!(!url.origin().is_tuple());
  563. /// # Ok(())
  564. /// # }
  565. /// # run().unwrap();
  566. /// ```
  567. #[inline]
  568. pub fn origin(&self) -> Origin {
  569. origin::url_origin(self)
  570. }
  571. /// Return the scheme of this URL, lower-cased, as an ASCII string without the ':' delimiter.
  572. ///
  573. /// # Examples
  574. ///
  575. /// ```
  576. /// use url::Url;
  577. /// # use url::ParseError;
  578. ///
  579. /// # fn run() -> Result<(), ParseError> {
  580. /// let url = Url::parse("file:///tmp/foo")?;
  581. /// assert_eq!(url.scheme(), "file");
  582. /// # Ok(())
  583. /// # }
  584. /// # run().unwrap();
  585. /// ```
  586. #[inline]
  587. pub fn scheme(&self) -> &str {
  588. self.slice(..self.scheme_end)
  589. }
  590. /// Return whether the URL has an 'authority',
  591. /// which can contain a username, password, host, and port number.
  592. ///
  593. /// URLs that do *not* are either path-only like `unix:/run/foo.socket`
  594. /// or cannot-be-a-base like `data:text/plain,Stuff`.
  595. ///
  596. /// # Examples
  597. ///
  598. /// ```
  599. /// use url::Url;
  600. /// # use url::ParseError;
  601. ///
  602. /// # fn run() -> Result<(), ParseError> {
  603. /// let url = Url::parse("ftp://rms@example.com")?;
  604. /// assert!(url.has_authority());
  605. ///
  606. /// let url = Url::parse("unix:/run/foo.socket")?;
  607. /// assert!(!url.has_authority());
  608. ///
  609. /// let url = Url::parse("data:text/plain,Stuff")?;
  610. /// assert!(!url.has_authority());
  611. /// # Ok(())
  612. /// # }
  613. /// # run().unwrap();
  614. /// ```
  615. #[inline]
  616. pub fn has_authority(&self) -> bool {
  617. debug_assert!(self.byte_at(self.scheme_end) == b':');
  618. self.slice(self.scheme_end..).starts_with("://")
  619. }
  620. /// Return whether this URL is a cannot-be-a-base URL,
  621. /// meaning that parsing a relative URL string with this URL as the base will return an error.
  622. ///
  623. /// This is the case if the scheme and `:` delimiter are not followed by a `/` slash,
  624. /// as is typically the case of `data:` and `mailto:` URLs.
  625. ///
  626. /// # Examples
  627. ///
  628. /// ```
  629. /// use url::Url;
  630. /// # use url::ParseError;
  631. ///
  632. /// # fn run() -> Result<(), ParseError> {
  633. /// let url = Url::parse("ftp://rms@example.com")?;
  634. /// assert!(!url.cannot_be_a_base());
  635. ///
  636. /// let url = Url::parse("unix:/run/foo.socket")?;
  637. /// assert!(!url.cannot_be_a_base());
  638. ///
  639. /// let url = Url::parse("data:text/plain,Stuff")?;
  640. /// assert!(url.cannot_be_a_base());
  641. /// # Ok(())
  642. /// # }
  643. /// # run().unwrap();
  644. /// ```
  645. #[inline]
  646. pub fn cannot_be_a_base(&self) -> bool {
  647. !self.slice(self.scheme_end + 1..).starts_with('/')
  648. }
  649. /// Return the username for this URL (typically the empty string)
  650. /// as a percent-encoded ASCII string.
  651. ///
  652. /// # Examples
  653. ///
  654. /// ```
  655. /// use url::Url;
  656. /// # use url::ParseError;
  657. ///
  658. /// # fn run() -> Result<(), ParseError> {
  659. /// let url = Url::parse("ftp://rms@example.com")?;
  660. /// assert_eq!(url.username(), "rms");
  661. ///
  662. /// let url = Url::parse("ftp://:secret123@example.com")?;
  663. /// assert_eq!(url.username(), "");
  664. ///
  665. /// let url = Url::parse("https://example.com")?;
  666. /// assert_eq!(url.username(), "");
  667. /// # Ok(())
  668. /// # }
  669. /// # run().unwrap();
  670. /// ```
  671. pub fn username(&self) -> &str {
  672. let scheme_separator_len = "://".len() as u32;
  673. if self.has_authority() && self.username_end > self.scheme_end + scheme_separator_len {
  674. self.slice(self.scheme_end + scheme_separator_len..self.username_end)
  675. } else {
  676. ""
  677. }
  678. }
  679. /// Return the password for this URL, if any, as a percent-encoded ASCII string.
  680. ///
  681. /// # Examples
  682. ///
  683. /// ```
  684. /// use url::Url;
  685. /// # use url::ParseError;
  686. ///
  687. /// # fn run() -> Result<(), ParseError> {
  688. /// let url = Url::parse("ftp://rms:secret123@example.com")?;
  689. /// assert_eq!(url.password(), Some("secret123"));
  690. ///
  691. /// let url = Url::parse("ftp://:secret123@example.com")?;
  692. /// assert_eq!(url.password(), Some("secret123"));
  693. ///
  694. /// let url = Url::parse("ftp://rms@example.com")?;
  695. /// assert_eq!(url.password(), None);
  696. ///
  697. /// let url = Url::parse("https://example.com")?;
  698. /// assert_eq!(url.password(), None);
  699. /// # Ok(())
  700. /// # }
  701. /// # run().unwrap();
  702. /// ```
  703. pub fn password(&self) -> Option<&str> {
  704. // This ':' is not the one marking a port number since a host can not be empty.
  705. // (Except for file: URLs, which do not have port numbers.)
  706. if self.has_authority()
  707. && self.username_end != self.serialization.len() as u32
  708. && self.byte_at(self.username_end) == b':'
  709. {
  710. debug_assert!(self.byte_at(self.host_start - 1) == b'@');
  711. Some(self.slice(self.username_end + 1..self.host_start - 1))
  712. } else {
  713. None
  714. }
  715. }
  716. /// Equivalent to `url.host().is_some()`.
  717. ///
  718. /// # Examples
  719. ///
  720. /// ```
  721. /// use url::Url;
  722. /// # use url::ParseError;
  723. ///
  724. /// # fn run() -> Result<(), ParseError> {
  725. /// let url = Url::parse("ftp://rms@example.com")?;
  726. /// assert!(url.has_host());
  727. ///
  728. /// let url = Url::parse("unix:/run/foo.socket")?;
  729. /// assert!(!url.has_host());
  730. ///
  731. /// let url = Url::parse("data:text/plain,Stuff")?;
  732. /// assert!(!url.has_host());
  733. /// # Ok(())
  734. /// # }
  735. /// # run().unwrap();
  736. /// ```
  737. pub fn has_host(&self) -> bool {
  738. !matches!(self.host, HostInternal::None)
  739. }
  740. /// Return the string representation of the host (domain or IP address) for this URL, if any.
  741. ///
  742. /// Non-ASCII domains are punycode-encoded per IDNA if this is the host
  743. /// of a special URL, or percent encoded for non-special URLs.
  744. /// IPv6 addresses are given between `[` and `]` brackets.
  745. ///
  746. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  747. /// don’t have a host.
  748. ///
  749. /// See also the `host` method.
  750. ///
  751. /// # Examples
  752. ///
  753. /// ```
  754. /// use url::Url;
  755. /// # use url::ParseError;
  756. ///
  757. /// # fn run() -> Result<(), ParseError> {
  758. /// let url = Url::parse("https://127.0.0.1/index.html")?;
  759. /// assert_eq!(url.host_str(), Some("127.0.0.1"));
  760. ///
  761. /// let url = Url::parse("ftp://rms@example.com")?;
  762. /// assert_eq!(url.host_str(), Some("example.com"));
  763. ///
  764. /// let url = Url::parse("unix:/run/foo.socket")?;
  765. /// assert_eq!(url.host_str(), None);
  766. ///
  767. /// let url = Url::parse("data:text/plain,Stuff")?;
  768. /// assert_eq!(url.host_str(), None);
  769. /// # Ok(())
  770. /// # }
  771. /// # run().unwrap();
  772. /// ```
  773. pub fn host_str(&self) -> Option<&str> {
  774. if self.has_host() {
  775. Some(self.slice(self.host_start..self.host_end))
  776. } else {
  777. None
  778. }
  779. }
  780. /// Return the parsed representation of the host for this URL.
  781. /// Non-ASCII domain labels are punycode-encoded per IDNA if this is the host
  782. /// of a special URL, or percent encoded for non-special URLs.
  783. ///
  784. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  785. /// don’t have a host.
  786. ///
  787. /// See also the `host_str` method.
  788. ///
  789. /// # Examples
  790. ///
  791. /// ```
  792. /// use url::Url;
  793. /// # use url::ParseError;
  794. ///
  795. /// # fn run() -> Result<(), ParseError> {
  796. /// let url = Url::parse("https://127.0.0.1/index.html")?;
  797. /// assert!(url.host().is_some());
  798. ///
  799. /// let url = Url::parse("ftp://rms@example.com")?;
  800. /// assert!(url.host().is_some());
  801. ///
  802. /// let url = Url::parse("unix:/run/foo.socket")?;
  803. /// assert!(url.host().is_none());
  804. ///
  805. /// let url = Url::parse("data:text/plain,Stuff")?;
  806. /// assert!(url.host().is_none());
  807. /// # Ok(())
  808. /// # }
  809. /// # run().unwrap();
  810. /// ```
  811. pub fn host(&self) -> Option<Host<&str>> {
  812. match self.host {
  813. HostInternal::None => None,
  814. HostInternal::Domain => Some(Host::Domain(self.slice(self.host_start..self.host_end))),
  815. HostInternal::Ipv4(address) => Some(Host::Ipv4(address)),
  816. HostInternal::Ipv6(address) => Some(Host::Ipv6(address)),
  817. }
  818. }
  819. /// If this URL has a host and it is a domain name (not an IP address), return it.
  820. /// Non-ASCII domains are punycode-encoded per IDNA if this is the host
  821. /// of a special URL, or percent encoded for non-special URLs.
  822. ///
  823. /// # Examples
  824. ///
  825. /// ```
  826. /// use url::Url;
  827. /// # use url::ParseError;
  828. ///
  829. /// # fn run() -> Result<(), ParseError> {
  830. /// let url = Url::parse("https://127.0.0.1/")?;
  831. /// assert_eq!(url.domain(), None);
  832. ///
  833. /// let url = Url::parse("mailto:rms@example.net")?;
  834. /// assert_eq!(url.domain(), None);
  835. ///
  836. /// let url = Url::parse("https://example.com/")?;
  837. /// assert_eq!(url.domain(), Some("example.com"));
  838. /// # Ok(())
  839. /// # }
  840. /// # run().unwrap();
  841. /// ```
  842. pub fn domain(&self) -> Option<&str> {
  843. match self.host {
  844. HostInternal::Domain => Some(self.slice(self.host_start..self.host_end)),
  845. _ => None,
  846. }
  847. }
  848. /// Return the port number for this URL, if any.
  849. ///
  850. /// Note that default port numbers are never reflected by the serialization,
  851. /// use the `port_or_known_default()` method if you want a default port number returned.
  852. ///
  853. /// # Examples
  854. ///
  855. /// ```
  856. /// use url::Url;
  857. /// # use url::ParseError;
  858. ///
  859. /// # fn run() -> Result<(), ParseError> {
  860. /// let url = Url::parse("https://example.com")?;
  861. /// assert_eq!(url.port(), None);
  862. ///
  863. /// let url = Url::parse("https://example.com:443/")?;
  864. /// assert_eq!(url.port(), None);
  865. ///
  866. /// let url = Url::parse("ssh://example.com:22")?;
  867. /// assert_eq!(url.port(), Some(22));
  868. /// # Ok(())
  869. /// # }
  870. /// # run().unwrap();
  871. /// ```
  872. #[inline]
  873. pub fn port(&self) -> Option<u16> {
  874. self.port
  875. }
  876. /// Return the port number for this URL, or the default port number if it is known.
  877. ///
  878. /// This method only knows the default port number
  879. /// of the `http`, `https`, `ws`, `wss` and `ftp` schemes.
  880. ///
  881. /// For URLs in these schemes, this method always returns `Some(_)`.
  882. /// For other schemes, it is the same as `Url::port()`.
  883. ///
  884. /// # Examples
  885. ///
  886. /// ```
  887. /// use url::Url;
  888. /// # use url::ParseError;
  889. ///
  890. /// # fn run() -> Result<(), ParseError> {
  891. /// let url = Url::parse("foo://example.com")?;
  892. /// assert_eq!(url.port_or_known_default(), None);
  893. ///
  894. /// let url = Url::parse("foo://example.com:1456")?;
  895. /// assert_eq!(url.port_or_known_default(), Some(1456));
  896. ///
  897. /// let url = Url::parse("https://example.com")?;
  898. /// assert_eq!(url.port_or_known_default(), Some(443));
  899. /// # Ok(())
  900. /// # }
  901. /// # run().unwrap();
  902. /// ```
  903. #[inline]
  904. pub fn port_or_known_default(&self) -> Option<u16> {
  905. self.port.or_else(|| parser::default_port(self.scheme()))
  906. }
  907. /// Resolve a URL’s host and port number to `SocketAddr`.
  908. ///
  909. /// If the URL has the default port number of a scheme that is unknown to this library,
  910. /// `default_port_number` provides an opportunity to provide the actual port number.
  911. /// In non-example code this should be implemented either simply as `|| None`,
  912. /// or by matching on the URL’s `.scheme()`.
  913. ///
  914. /// If the host is a domain, it is resolved using the standard library’s DNS support.
  915. ///
  916. /// # Examples
  917. ///
  918. /// ```no_run
  919. /// let url = url::Url::parse("https://example.net/").unwrap();
  920. /// let addrs = url.socket_addrs(|| None).unwrap();
  921. /// std::net::TcpStream::connect(&*addrs)
  922. /// # ;
  923. /// ```
  924. ///
  925. /// ```
  926. /// /// With application-specific known default port numbers
  927. /// fn socket_addrs(url: url::Url) -> std::io::Result<Vec<std::net::SocketAddr>> {
  928. /// url.socket_addrs(|| match url.scheme() {
  929. /// "socks5" | "socks5h" => Some(1080),
  930. /// _ => None,
  931. /// })
  932. /// }
  933. /// ```
  934. pub fn socket_addrs(
  935. &self,
  936. default_port_number: impl Fn() -> Option<u16>,
  937. ) -> io::Result<Vec<SocketAddr>> {
  938. // Note: trying to avoid the Vec allocation by returning `impl AsRef<[SocketAddr]>`
  939. // causes borrowck issues because the return value borrows `default_port_number`:
  940. //
  941. // https://github.com/rust-lang/rfcs/blob/master/text/1951-expand-impl-trait.md#scoping-for-type-and-lifetime-parameters
  942. //
  943. // > This RFC proposes that *all* type parameters are considered in scope
  944. // > for `impl Trait` in return position
  945. fn io_result<T>(opt: Option<T>, message: &str) -> io::Result<T> {
  946. opt.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, message))
  947. }
  948. let host = io_result(self.host(), "No host name in the URL")?;
  949. let port = io_result(
  950. self.port_or_known_default().or_else(default_port_number),
  951. "No port number in the URL",
  952. )?;
  953. Ok(match host {
  954. Host::Domain(domain) => (domain, port).to_socket_addrs()?.collect(),
  955. Host::Ipv4(ip) => vec![(ip, port).into()],
  956. Host::Ipv6(ip) => vec![(ip, port).into()],
  957. })
  958. }
  959. /// Return the path for this URL, as a percent-encoded ASCII string.
  960. /// For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with '/'.
  961. /// For other URLs, this starts with a '/' slash
  962. /// and continues with slash-separated path segments.
  963. ///
  964. /// # Examples
  965. ///
  966. /// ```rust
  967. /// use url::{Url, ParseError};
  968. ///
  969. /// # fn run() -> Result<(), ParseError> {
  970. /// let url = Url::parse("https://example.com/api/versions?page=2")?;
  971. /// assert_eq!(url.path(), "/api/versions");
  972. ///
  973. /// let url = Url::parse("https://example.com")?;
  974. /// assert_eq!(url.path(), "/");
  975. ///
  976. /// let url = Url::parse("https://example.com/countries/việt nam")?;
  977. /// assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam");
  978. /// # Ok(())
  979. /// # }
  980. /// # run().unwrap();
  981. /// ```
  982. pub fn path(&self) -> &str {
  983. match (self.query_start, self.fragment_start) {
  984. (None, None) => self.slice(self.path_start..),
  985. (Some(next_component_start), _) | (None, Some(next_component_start)) => {
  986. self.slice(self.path_start..next_component_start)
  987. }
  988. }
  989. }
  990. /// Unless this URL is cannot-be-a-base,
  991. /// return an iterator of '/' slash-separated path segments,
  992. /// each as a percent-encoded ASCII string.
  993. ///
  994. /// Return `None` for cannot-be-a-base URLs.
  995. ///
  996. /// When `Some` is returned, the iterator always contains at least one string
  997. /// (which may be empty).
  998. ///
  999. /// # Examples
  1000. ///
  1001. /// ```
  1002. /// use url::Url;
  1003. /// # use std::error::Error;
  1004. ///
  1005. /// # fn run() -> Result<(), Box<dyn Error>> {
  1006. /// let url = Url::parse("https://example.com/foo/bar")?;
  1007. /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
  1008. /// assert_eq!(path_segments.next(), Some("foo"));
  1009. /// assert_eq!(path_segments.next(), Some("bar"));
  1010. /// assert_eq!(path_segments.next(), None);
  1011. ///
  1012. /// let url = Url::parse("https://example.com")?;
  1013. /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
  1014. /// assert_eq!(path_segments.next(), Some(""));
  1015. /// assert_eq!(path_segments.next(), None);
  1016. ///
  1017. /// let url = Url::parse("data:text/plain,HelloWorld")?;
  1018. /// assert!(url.path_segments().is_none());
  1019. ///
  1020. /// let url = Url::parse("https://example.com/countries/việt nam")?;
  1021. /// let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?;
  1022. /// assert_eq!(path_segments.next(), Some("countries"));
  1023. /// assert_eq!(path_segments.next(), Some("vi%E1%BB%87t%20nam"));
  1024. /// # Ok(())
  1025. /// # }
  1026. /// # run().unwrap();
  1027. /// ```
  1028. #[allow(clippy::manual_strip)] // introduced in 1.45, MSRV is 1.36
  1029. pub fn path_segments(&self) -> Option<str::Split<'_, char>> {
  1030. let path = self.path();
  1031. if path.starts_with('/') {
  1032. Some(path[1..].split('/'))
  1033. } else {
  1034. None
  1035. }
  1036. }
  1037. /// Return this URL’s query string, if any, as a percent-encoded ASCII string.
  1038. ///
  1039. /// # Examples
  1040. ///
  1041. /// ```rust
  1042. /// use url::Url;
  1043. /// # use url::ParseError;
  1044. ///
  1045. /// fn run() -> Result<(), ParseError> {
  1046. /// let url = Url::parse("https://example.com/products?page=2")?;
  1047. /// let query = url.query();
  1048. /// assert_eq!(query, Some("page=2"));
  1049. ///
  1050. /// let url = Url::parse("https://example.com/products")?;
  1051. /// let query = url.query();
  1052. /// assert!(query.is_none());
  1053. ///
  1054. /// let url = Url::parse("https://example.com/?country=español")?;
  1055. /// let query = url.query();
  1056. /// assert_eq!(query, Some("country=espa%C3%B1ol"));
  1057. /// # Ok(())
  1058. /// # }
  1059. /// # run().unwrap();
  1060. /// ```
  1061. pub fn query(&self) -> Option<&str> {
  1062. match (self.query_start, self.fragment_start) {
  1063. (None, _) => None,
  1064. (Some(query_start), None) => {
  1065. debug_assert!(self.byte_at(query_start) == b'?');
  1066. Some(self.slice(query_start + 1..))
  1067. }
  1068. (Some(query_start), Some(fragment_start)) => {
  1069. debug_assert!(self.byte_at(query_start) == b'?');
  1070. Some(self.slice(query_start + 1..fragment_start))
  1071. }
  1072. }
  1073. }
  1074. /// Parse the URL’s query string, if any, as `application/x-www-form-urlencoded`
  1075. /// and return an iterator of (key, value) pairs.
  1076. ///
  1077. /// # Examples
  1078. ///
  1079. /// ```rust
  1080. /// use std::borrow::Cow;
  1081. ///
  1082. /// use url::Url;
  1083. /// # use url::ParseError;
  1084. ///
  1085. /// # fn run() -> Result<(), ParseError> {
  1086. /// let url = Url::parse("https://example.com/products?page=2&sort=desc")?;
  1087. /// let mut pairs = url.query_pairs();
  1088. ///
  1089. /// assert_eq!(pairs.count(), 2);
  1090. ///
  1091. /// assert_eq!(pairs.next(), Some((Cow::Borrowed("page"), Cow::Borrowed("2"))));
  1092. /// assert_eq!(pairs.next(), Some((Cow::Borrowed("sort"), Cow::Borrowed("desc"))));
  1093. /// # Ok(())
  1094. /// # }
  1095. /// # run().unwrap();
  1096. ///
  1097. #[inline]
  1098. pub fn query_pairs(&self) -> form_urlencoded::Parse<'_> {
  1099. form_urlencoded::parse(self.query().unwrap_or("").as_bytes())
  1100. }
  1101. /// Return this URL’s fragment identifier, if any.
  1102. ///
  1103. /// A fragment is the part of the URL after the `#` symbol.
  1104. /// The fragment is optional and, if present, contains a fragment identifier
  1105. /// that identifies a secondary resource, such as a section heading
  1106. /// of a document.
  1107. ///
  1108. /// In HTML, the fragment identifier is usually the id attribute of a an element
  1109. /// that is scrolled to on load. Browsers typically will not send the fragment portion
  1110. /// of a URL to the server.
  1111. ///
  1112. /// **Note:** the parser did *not* percent-encode this component,
  1113. /// but the input may have been percent-encoded already.
  1114. ///
  1115. /// # Examples
  1116. ///
  1117. /// ```rust
  1118. /// use url::Url;
  1119. /// # use url::ParseError;
  1120. ///
  1121. /// # fn run() -> Result<(), ParseError> {
  1122. /// let url = Url::parse("https://example.com/data.csv#row=4")?;
  1123. ///
  1124. /// assert_eq!(url.fragment(), Some("row=4"));
  1125. ///
  1126. /// let url = Url::parse("https://example.com/data.csv#cell=4,1-6,2")?;
  1127. ///
  1128. /// assert_eq!(url.fragment(), Some("cell=4,1-6,2"));
  1129. /// # Ok(())
  1130. /// # }
  1131. /// # run().unwrap();
  1132. /// ```
  1133. pub fn fragment(&self) -> Option<&str> {
  1134. self.fragment_start.map(|start| {
  1135. debug_assert!(self.byte_at(start) == b'#');
  1136. self.slice(start + 1..)
  1137. })
  1138. }
  1139. fn mutate<F: FnOnce(&mut Parser<'_>) -> R, R>(&mut self, f: F) -> R {
  1140. let mut parser = Parser::for_setter(mem::replace(&mut self.serialization, String::new()));
  1141. let result = f(&mut parser);
  1142. self.serialization = parser.serialization;
  1143. result
  1144. }
  1145. /// Change this URL’s fragment identifier.
  1146. ///
  1147. /// # Examples
  1148. ///
  1149. /// ```rust
  1150. /// use url::Url;
  1151. /// # use url::ParseError;
  1152. ///
  1153. /// # fn run() -> Result<(), ParseError> {
  1154. /// let mut url = Url::parse("https://example.com/data.csv")?;
  1155. /// assert_eq!(url.as_str(), "https://example.com/data.csv");
  1156. /// url.set_fragment(Some("cell=4,1-6,2"));
  1157. /// assert_eq!(url.as_str(), "https://example.com/data.csv#cell=4,1-6,2");
  1158. /// assert_eq!(url.fragment(), Some("cell=4,1-6,2"));
  1159. ///
  1160. /// url.set_fragment(None);
  1161. /// assert_eq!(url.as_str(), "https://example.com/data.csv");
  1162. /// assert!(url.fragment().is_none());
  1163. /// # Ok(())
  1164. /// # }
  1165. /// # run().unwrap();
  1166. /// ```
  1167. pub fn set_fragment(&mut self, fragment: Option<&str>) {
  1168. // Remove any previous fragment
  1169. if let Some(start) = self.fragment_start {
  1170. debug_assert!(self.byte_at(start) == b'#');
  1171. self.serialization.truncate(start as usize);
  1172. }
  1173. // Write the new one
  1174. if let Some(input) = fragment {
  1175. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  1176. self.serialization.push('#');
  1177. self.mutate(|parser| parser.parse_fragment(parser::Input::no_trim(input)))
  1178. } else {
  1179. self.fragment_start = None
  1180. }
  1181. }
  1182. fn take_fragment(&mut self) -> Option<String> {
  1183. self.fragment_start.take().map(|start| {
  1184. debug_assert!(self.byte_at(start) == b'#');
  1185. let fragment = self.slice(start + 1..).to_owned();
  1186. self.serialization.truncate(start as usize);
  1187. fragment
  1188. })
  1189. }
  1190. fn restore_already_parsed_fragment(&mut self, fragment: Option<String>) {
  1191. if let Some(ref fragment) = fragment {
  1192. assert!(self.fragment_start.is_none());
  1193. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  1194. self.serialization.push('#');
  1195. self.serialization.push_str(fragment);
  1196. }
  1197. }
  1198. /// Change this URL’s query string.
  1199. ///
  1200. /// # Examples
  1201. ///
  1202. /// ```rust
  1203. /// use url::Url;
  1204. /// # use url::ParseError;
  1205. ///
  1206. /// # fn run() -> Result<(), ParseError> {
  1207. /// let mut url = Url::parse("https://example.com/products")?;
  1208. /// assert_eq!(url.as_str(), "https://example.com/products");
  1209. ///
  1210. /// url.set_query(Some("page=2"));
  1211. /// assert_eq!(url.as_str(), "https://example.com/products?page=2");
  1212. /// assert_eq!(url.query(), Some("page=2"));
  1213. /// # Ok(())
  1214. /// # }
  1215. /// # run().unwrap();
  1216. /// ```
  1217. pub fn set_query(&mut self, query: Option<&str>) {
  1218. let fragment = self.take_fragment();
  1219. // Remove any previous query
  1220. if let Some(start) = self.query_start.take() {
  1221. debug_assert!(self.byte_at(start) == b'?');
  1222. self.serialization.truncate(start as usize);
  1223. }
  1224. // Write the new query, if any
  1225. if let Some(input) = query {
  1226. self.query_start = Some(to_u32(self.serialization.len()).unwrap());
  1227. self.serialization.push('?');
  1228. let scheme_type = SchemeType::from(self.scheme());
  1229. let scheme_end = self.scheme_end;
  1230. self.mutate(|parser| {
  1231. let vfn = parser.violation_fn;
  1232. parser.parse_query(
  1233. scheme_type,
  1234. scheme_end,
  1235. parser::Input::trim_tab_and_newlines(input, vfn),
  1236. )
  1237. });
  1238. }
  1239. self.restore_already_parsed_fragment(fragment);
  1240. }
  1241. /// Manipulate this URL’s query string, viewed as a sequence of name/value pairs
  1242. /// in `application/x-www-form-urlencoded` syntax.
  1243. ///
  1244. /// The return value has a method-chaining API:
  1245. ///
  1246. /// ```rust
  1247. /// # use url::{Url, ParseError};
  1248. ///
  1249. /// # fn run() -> Result<(), ParseError> {
  1250. /// let mut url = Url::parse("https://example.net?lang=fr#nav")?;
  1251. /// assert_eq!(url.query(), Some("lang=fr"));
  1252. ///
  1253. /// url.query_pairs_mut().append_pair("foo", "bar");
  1254. /// assert_eq!(url.query(), Some("lang=fr&foo=bar"));
  1255. /// assert_eq!(url.as_str(), "https://example.net/?lang=fr&foo=bar#nav");
  1256. ///
  1257. /// url.query_pairs_mut()
  1258. /// .clear()
  1259. /// .append_pair("foo", "bar & baz")
  1260. /// .append_pair("saisons", "\u{00C9}t\u{00E9}+hiver");
  1261. /// assert_eq!(url.query(), Some("foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver"));
  1262. /// assert_eq!(url.as_str(),
  1263. /// "https://example.net/?foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver#nav");
  1264. /// # Ok(())
  1265. /// # }
  1266. /// # run().unwrap();
  1267. /// ```
  1268. ///
  1269. /// Note: `url.query_pairs_mut().clear();` is equivalent to `url.set_query(Some(""))`,
  1270. /// not `url.set_query(None)`.
  1271. ///
  1272. /// The state of `Url` is unspecified if this return value is leaked without being dropped.
  1273. pub fn query_pairs_mut(&mut self) -> form_urlencoded::Serializer<'_, UrlQuery<'_>> {
  1274. let fragment = self.take_fragment();
  1275. let query_start;
  1276. if let Some(start) = self.query_start {
  1277. debug_assert!(self.byte_at(start) == b'?');
  1278. query_start = start as usize;
  1279. } else {
  1280. query_start = self.serialization.len();
  1281. self.query_start = Some(to_u32(query_start).unwrap());
  1282. self.serialization.push('?');
  1283. }
  1284. let query = UrlQuery {
  1285. url: Some(self),
  1286. fragment,
  1287. };
  1288. form_urlencoded::Serializer::for_suffix(query, query_start + "?".len())
  1289. }
  1290. fn take_after_path(&mut self) -> String {
  1291. match (self.query_start, self.fragment_start) {
  1292. (Some(i), _) | (None, Some(i)) => {
  1293. let after_path = self.slice(i..).to_owned();
  1294. self.serialization.truncate(i as usize);
  1295. after_path
  1296. }
  1297. (None, None) => String::new(),
  1298. }
  1299. }
  1300. /// Change this URL’s path.
  1301. ///
  1302. /// # Examples
  1303. ///
  1304. /// ```rust
  1305. /// use url::Url;
  1306. /// # use url::ParseError;
  1307. ///
  1308. /// # fn run() -> Result<(), ParseError> {
  1309. /// let mut url = Url::parse("https://example.com")?;
  1310. /// url.set_path("api/comments");
  1311. /// assert_eq!(url.as_str(), "https://example.com/api/comments");
  1312. /// assert_eq!(url.path(), "/api/comments");
  1313. ///
  1314. /// let mut url = Url::parse("https://example.com/api")?;
  1315. /// url.set_path("data/report.csv");
  1316. /// assert_eq!(url.as_str(), "https://example.com/data/report.csv");
  1317. /// assert_eq!(url.path(), "/data/report.csv");
  1318. /// # Ok(())
  1319. /// # }
  1320. /// # run().unwrap();
  1321. /// ```
  1322. pub fn set_path(&mut self, mut path: &str) {
  1323. let after_path = self.take_after_path();
  1324. let old_after_path_pos = to_u32(self.serialization.len()).unwrap();
  1325. let cannot_be_a_base = self.cannot_be_a_base();
  1326. let scheme_type = SchemeType::from(self.scheme());
  1327. self.serialization.truncate(self.path_start as usize);
  1328. self.mutate(|parser| {
  1329. if cannot_be_a_base {
  1330. if path.starts_with('/') {
  1331. parser.serialization.push_str("%2F");
  1332. path = &path[1..];
  1333. }
  1334. parser.parse_cannot_be_a_base_path(parser::Input::new(path));
  1335. } else {
  1336. let mut has_host = true; // FIXME
  1337. parser.parse_path_start(scheme_type, &mut has_host, parser::Input::new(path));
  1338. }
  1339. });
  1340. self.restore_after_path(old_after_path_pos, &after_path);
  1341. }
  1342. /// Return an object with methods to manipulate this URL’s path segments.
  1343. ///
  1344. /// Return `Err(())` if this URL is cannot-be-a-base.
  1345. #[allow(clippy::result_map_unit_fn)]
  1346. pub fn path_segments_mut(&mut self) -> Result<PathSegmentsMut<'_>, ()> {
  1347. if self.cannot_be_a_base() {
  1348. Err(())
  1349. } else {
  1350. Ok(path_segments::new(self))
  1351. }
  1352. }
  1353. fn restore_after_path(&mut self, old_after_path_position: u32, after_path: &str) {
  1354. let new_after_path_position = to_u32(self.serialization.len()).unwrap();
  1355. let adjust = |index: &mut u32| {
  1356. *index -= old_after_path_position;
  1357. *index += new_after_path_position;
  1358. };
  1359. if let Some(ref mut index) = self.query_start {
  1360. adjust(index)
  1361. }
  1362. if let Some(ref mut index) = self.fragment_start {
  1363. adjust(index)
  1364. }
  1365. self.serialization.push_str(after_path)
  1366. }
  1367. /// Change this URL’s port number.
  1368. ///
  1369. /// Note that default port numbers are not reflected in the serialization.
  1370. ///
  1371. /// If this URL is cannot-be-a-base, does not have a host, or has the `file` scheme;
  1372. /// do nothing and return `Err`.
  1373. ///
  1374. /// # Examples
  1375. ///
  1376. /// ```
  1377. /// use url::Url;
  1378. /// # use std::error::Error;
  1379. ///
  1380. /// # fn run() -> Result<(), Box<dyn Error>> {
  1381. /// let mut url = Url::parse("ssh://example.net:2048/")?;
  1382. ///
  1383. /// url.set_port(Some(4096)).map_err(|_| "cannot be base")?;
  1384. /// assert_eq!(url.as_str(), "ssh://example.net:4096/");
  1385. ///
  1386. /// url.set_port(None).map_err(|_| "cannot be base")?;
  1387. /// assert_eq!(url.as_str(), "ssh://example.net/");
  1388. /// # Ok(())
  1389. /// # }
  1390. /// # run().unwrap();
  1391. /// ```
  1392. ///
  1393. /// Known default port numbers are not reflected:
  1394. ///
  1395. /// ```rust
  1396. /// use url::Url;
  1397. /// # use std::error::Error;
  1398. ///
  1399. /// # fn run() -> Result<(), Box<dyn Error>> {
  1400. /// let mut url = Url::parse("https://example.org/")?;
  1401. ///
  1402. /// url.set_port(Some(443)).map_err(|_| "cannot be base")?;
  1403. /// assert!(url.port().is_none());
  1404. /// # Ok(())
  1405. /// # }
  1406. /// # run().unwrap();
  1407. /// ```
  1408. ///
  1409. /// Cannot set port for cannot-be-a-base URLs:
  1410. ///
  1411. /// ```
  1412. /// use url::Url;
  1413. /// # use url::ParseError;
  1414. ///
  1415. /// # fn run() -> Result<(), ParseError> {
  1416. /// let mut url = Url::parse("mailto:rms@example.net")?;
  1417. ///
  1418. /// let result = url.set_port(Some(80));
  1419. /// assert!(result.is_err());
  1420. ///
  1421. /// let result = url.set_port(None);
  1422. /// assert!(result.is_err());
  1423. /// # Ok(())
  1424. /// # }
  1425. /// # run().unwrap();
  1426. /// ```
  1427. #[allow(clippy::result_map_unit_fn)]
  1428. pub fn set_port(&mut self, mut port: Option<u16>) -> Result<(), ()> {
  1429. // has_host implies !cannot_be_a_base
  1430. if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
  1431. return Err(());
  1432. }
  1433. if port.is_some() && port == parser::default_port(self.scheme()) {
  1434. port = None
  1435. }
  1436. self.set_port_internal(port);
  1437. Ok(())
  1438. }
  1439. fn set_port_internal(&mut self, port: Option<u16>) {
  1440. match (self.port, port) {
  1441. (None, None) => {}
  1442. (Some(_), None) => {
  1443. self.serialization
  1444. .drain(self.host_end as usize..self.path_start as usize);
  1445. let offset = self.path_start - self.host_end;
  1446. self.path_start = self.host_end;
  1447. if let Some(ref mut index) = self.query_start {
  1448. *index -= offset
  1449. }
  1450. if let Some(ref mut index) = self.fragment_start {
  1451. *index -= offset
  1452. }
  1453. }
  1454. (Some(old), Some(new)) if old == new => {}
  1455. (_, Some(new)) => {
  1456. let path_and_after = self.slice(self.path_start..).to_owned();
  1457. self.serialization.truncate(self.host_end as usize);
  1458. write!(&mut self.serialization, ":{}", new).unwrap();
  1459. let old_path_start = self.path_start;
  1460. let new_path_start = to_u32(self.serialization.len()).unwrap();
  1461. self.path_start = new_path_start;
  1462. let adjust = |index: &mut u32| {
  1463. *index -= old_path_start;
  1464. *index += new_path_start;
  1465. };
  1466. if let Some(ref mut index) = self.query_start {
  1467. adjust(index)
  1468. }
  1469. if let Some(ref mut index) = self.fragment_start {
  1470. adjust(index)
  1471. }
  1472. self.serialization.push_str(&path_and_after);
  1473. }
  1474. }
  1475. self.port = port;
  1476. }
  1477. /// Change this URL’s host.
  1478. ///
  1479. /// Removing the host (calling this with `None`)
  1480. /// will also remove any username, password, and port number.
  1481. ///
  1482. /// # Examples
  1483. ///
  1484. /// Change host:
  1485. ///
  1486. /// ```
  1487. /// use url::Url;
  1488. /// # use url::ParseError;
  1489. ///
  1490. /// # fn run() -> Result<(), ParseError> {
  1491. /// let mut url = Url::parse("https://example.net")?;
  1492. /// let result = url.set_host(Some("rust-lang.org"));
  1493. /// assert!(result.is_ok());
  1494. /// assert_eq!(url.as_str(), "https://rust-lang.org/");
  1495. /// # Ok(())
  1496. /// # }
  1497. /// # run().unwrap();
  1498. /// ```
  1499. ///
  1500. /// Remove host:
  1501. ///
  1502. /// ```
  1503. /// use url::Url;
  1504. /// # use url::ParseError;
  1505. ///
  1506. /// # fn run() -> Result<(), ParseError> {
  1507. /// let mut url = Url::parse("foo://example.net")?;
  1508. /// let result = url.set_host(None);
  1509. /// assert!(result.is_ok());
  1510. /// assert_eq!(url.as_str(), "foo:/");
  1511. /// # Ok(())
  1512. /// # }
  1513. /// # run().unwrap();
  1514. /// ```
  1515. ///
  1516. /// Cannot remove host for 'special' schemes (e.g. `http`):
  1517. ///
  1518. /// ```
  1519. /// use url::Url;
  1520. /// # use url::ParseError;
  1521. ///
  1522. /// # fn run() -> Result<(), ParseError> {
  1523. /// let mut url = Url::parse("https://example.net")?;
  1524. /// let result = url.set_host(None);
  1525. /// assert!(result.is_err());
  1526. /// assert_eq!(url.as_str(), "https://example.net/");
  1527. /// # Ok(())
  1528. /// # }
  1529. /// # run().unwrap();
  1530. /// ```
  1531. ///
  1532. /// Cannot change or remove host for cannot-be-a-base URLs:
  1533. ///
  1534. /// ```
  1535. /// use url::Url;
  1536. /// # use url::ParseError;
  1537. ///
  1538. /// # fn run() -> Result<(), ParseError> {
  1539. /// let mut url = Url::parse("mailto:rms@example.net")?;
  1540. ///
  1541. /// let result = url.set_host(Some("rust-lang.org"));
  1542. /// assert!(result.is_err());
  1543. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1544. ///
  1545. /// let result = url.set_host(None);
  1546. /// assert!(result.is_err());
  1547. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1548. /// # Ok(())
  1549. /// # }
  1550. /// # run().unwrap();
  1551. /// ```
  1552. ///
  1553. /// # Errors
  1554. ///
  1555. /// If this URL is cannot-be-a-base or there is an error parsing the given `host`,
  1556. /// a [`ParseError`] variant will be returned.
  1557. ///
  1558. /// [`ParseError`]: enum.ParseError.html
  1559. pub fn set_host(&mut self, host: Option<&str>) -> Result<(), ParseError> {
  1560. if self.cannot_be_a_base() {
  1561. return Err(ParseError::SetHostOnCannotBeABaseUrl);
  1562. }
  1563. if let Some(host) = host {
  1564. if host.is_empty() && SchemeType::from(self.scheme()).is_special() {
  1565. return Err(ParseError::EmptyHost);
  1566. }
  1567. let mut host_substr = host;
  1568. // Otherwise, if c is U+003A (:) and the [] flag is unset, then
  1569. if !host.starts_with('[') || !host.ends_with(']') {
  1570. match host.find(':') {
  1571. Some(0) => {
  1572. // If buffer is the empty string, validation error, return failure.
  1573. return Err(ParseError::InvalidDomainCharacter);
  1574. }
  1575. // Let host be the result of host parsing buffer
  1576. Some(colon_index) => {
  1577. host_substr = &host[..colon_index];
  1578. }
  1579. None => {}
  1580. }
  1581. }
  1582. if SchemeType::from(self.scheme()).is_special() {
  1583. self.set_host_internal(Host::parse(host_substr)?, None);
  1584. } else {
  1585. self.set_host_internal(Host::parse_opaque(host_substr)?, None);
  1586. }
  1587. } else if self.has_host() {
  1588. let scheme_type = SchemeType::from(self.scheme());
  1589. if scheme_type.is_special() {
  1590. return Err(ParseError::EmptyHost);
  1591. } else if self.serialization.len() == self.path_start as usize {
  1592. self.serialization.push('/');
  1593. }
  1594. debug_assert!(self.byte_at(self.scheme_end) == b':');
  1595. debug_assert!(self.byte_at(self.path_start) == b'/');
  1596. let new_path_start = self.scheme_end + 1;
  1597. self.serialization
  1598. .drain(new_path_start as usize..self.path_start as usize);
  1599. let offset = self.path_start - new_path_start;
  1600. self.path_start = new_path_start;
  1601. self.username_end = new_path_start;
  1602. self.host_start = new_path_start;
  1603. self.host_end = new_path_start;
  1604. self.port = None;
  1605. if let Some(ref mut index) = self.query_start {
  1606. *index -= offset
  1607. }
  1608. if let Some(ref mut index) = self.fragment_start {
  1609. *index -= offset
  1610. }
  1611. }
  1612. Ok(())
  1613. }
  1614. /// opt_new_port: None means leave unchanged, Some(None) means remove any port number.
  1615. fn set_host_internal(&mut self, host: Host<String>, opt_new_port: Option<Option<u16>>) {
  1616. let old_suffix_pos = if opt_new_port.is_some() {
  1617. self.path_start
  1618. } else {
  1619. self.host_end
  1620. };
  1621. let suffix = self.slice(old_suffix_pos..).to_owned();
  1622. self.serialization.truncate(self.host_start as usize);
  1623. if !self.has_authority() {
  1624. debug_assert!(self.slice(self.scheme_end..self.host_start) == ":");
  1625. debug_assert!(self.username_end == self.host_start);
  1626. self.serialization.push('/');
  1627. self.serialization.push('/');
  1628. self.username_end += 2;
  1629. self.host_start += 2;
  1630. }
  1631. write!(&mut self.serialization, "{}", host).unwrap();
  1632. self.host_end = to_u32(self.serialization.len()).unwrap();
  1633. self.host = host.into();
  1634. if let Some(new_port) = opt_new_port {
  1635. self.port = new_port;
  1636. if let Some(port) = new_port {
  1637. write!(&mut self.serialization, ":{}", port).unwrap();
  1638. }
  1639. }
  1640. let new_suffix_pos = to_u32(self.serialization.len()).unwrap();
  1641. self.serialization.push_str(&suffix);
  1642. let adjust = |index: &mut u32| {
  1643. *index -= old_suffix_pos;
  1644. *index += new_suffix_pos;
  1645. };
  1646. adjust(&mut self.path_start);
  1647. if let Some(ref mut index) = self.query_start {
  1648. adjust(index)
  1649. }
  1650. if let Some(ref mut index) = self.fragment_start {
  1651. adjust(index)
  1652. }
  1653. }
  1654. /// Change this URL’s host to the given IP address.
  1655. ///
  1656. /// If this URL is cannot-be-a-base, do nothing and return `Err`.
  1657. ///
  1658. /// Compared to `Url::set_host`, this skips the host parser.
  1659. ///
  1660. /// # Examples
  1661. ///
  1662. /// ```rust
  1663. /// use url::{Url, ParseError};
  1664. ///
  1665. /// # fn run() -> Result<(), ParseError> {
  1666. /// let mut url = Url::parse("http://example.com")?;
  1667. /// url.set_ip_host("127.0.0.1".parse().unwrap());
  1668. /// assert_eq!(url.host_str(), Some("127.0.0.1"));
  1669. /// assert_eq!(url.as_str(), "http://127.0.0.1/");
  1670. /// # Ok(())
  1671. /// # }
  1672. /// # run().unwrap();
  1673. /// ```
  1674. ///
  1675. /// Cannot change URL's from mailto(cannot-be-base) to ip:
  1676. ///
  1677. /// ```rust
  1678. /// use url::{Url, ParseError};
  1679. ///
  1680. /// # fn run() -> Result<(), ParseError> {
  1681. /// let mut url = Url::parse("mailto:rms@example.com")?;
  1682. /// let result = url.set_ip_host("127.0.0.1".parse().unwrap());
  1683. ///
  1684. /// assert_eq!(url.as_str(), "mailto:rms@example.com");
  1685. /// assert!(result.is_err());
  1686. /// # Ok(())
  1687. /// # }
  1688. /// # run().unwrap();
  1689. /// ```
  1690. ///
  1691. #[allow(clippy::result_map_unit_fn)]
  1692. pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ()> {
  1693. if self.cannot_be_a_base() {
  1694. return Err(());
  1695. }
  1696. let address = match address {
  1697. IpAddr::V4(address) => Host::Ipv4(address),
  1698. IpAddr::V6(address) => Host::Ipv6(address),
  1699. };
  1700. self.set_host_internal(address, None);
  1701. Ok(())
  1702. }
  1703. /// Change this URL’s password.
  1704. ///
  1705. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1706. ///
  1707. /// # Examples
  1708. ///
  1709. /// ```rust
  1710. /// use url::{Url, ParseError};
  1711. ///
  1712. /// # fn run() -> Result<(), ParseError> {
  1713. /// let mut url = Url::parse("mailto:rmz@example.com")?;
  1714. /// let result = url.set_password(Some("secret_password"));
  1715. /// assert!(result.is_err());
  1716. ///
  1717. /// let mut url = Url::parse("ftp://user1:secret1@example.com")?;
  1718. /// let result = url.set_password(Some("secret_password"));
  1719. /// assert_eq!(url.password(), Some("secret_password"));
  1720. ///
  1721. /// let mut url = Url::parse("ftp://user2:@example.com")?;
  1722. /// let result = url.set_password(Some("secret2"));
  1723. /// assert!(result.is_ok());
  1724. /// assert_eq!(url.password(), Some("secret2"));
  1725. /// # Ok(())
  1726. /// # }
  1727. /// # run().unwrap();
  1728. /// ```
  1729. #[allow(clippy::result_map_unit_fn)]
  1730. pub fn set_password(&mut self, password: Option<&str>) -> Result<(), ()> {
  1731. // has_host implies !cannot_be_a_base
  1732. if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
  1733. return Err(());
  1734. }
  1735. if let Some(password) = password {
  1736. let host_and_after = self.slice(self.host_start..).to_owned();
  1737. self.serialization.truncate(self.username_end as usize);
  1738. self.serialization.push(':');
  1739. self.serialization
  1740. .extend(utf8_percent_encode(password, USERINFO));
  1741. self.serialization.push('@');
  1742. let old_host_start = self.host_start;
  1743. let new_host_start = to_u32(self.serialization.len()).unwrap();
  1744. let adjust = |index: &mut u32| {
  1745. *index -= old_host_start;
  1746. *index += new_host_start;
  1747. };
  1748. self.host_start = new_host_start;
  1749. adjust(&mut self.host_end);
  1750. adjust(&mut self.path_start);
  1751. if let Some(ref mut index) = self.query_start {
  1752. adjust(index)
  1753. }
  1754. if let Some(ref mut index) = self.fragment_start {
  1755. adjust(index)
  1756. }
  1757. self.serialization.push_str(&host_and_after);
  1758. } else if self.byte_at(self.username_end) == b':' {
  1759. // If there is a password to remove
  1760. let has_username_or_password = self.byte_at(self.host_start - 1) == b'@';
  1761. debug_assert!(has_username_or_password);
  1762. let username_start = self.scheme_end + 3;
  1763. let empty_username = username_start == self.username_end;
  1764. let start = self.username_end; // Remove the ':'
  1765. let end = if empty_username {
  1766. self.host_start // Remove the '@' as well
  1767. } else {
  1768. self.host_start - 1 // Keep the '@' to separate the username from the host
  1769. };
  1770. self.serialization.drain(start as usize..end as usize);
  1771. let offset = end - start;
  1772. self.host_start -= offset;
  1773. self.host_end -= offset;
  1774. self.path_start -= offset;
  1775. if let Some(ref mut index) = self.query_start {
  1776. *index -= offset
  1777. }
  1778. if let Some(ref mut index) = self.fragment_start {
  1779. *index -= offset
  1780. }
  1781. }
  1782. Ok(())
  1783. }
  1784. /// Change this URL’s username.
  1785. ///
  1786. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1787. /// # Examples
  1788. ///
  1789. /// Cannot setup username from mailto(cannot-be-base)
  1790. ///
  1791. /// ```rust
  1792. /// use url::{Url, ParseError};
  1793. ///
  1794. /// # fn run() -> Result<(), ParseError> {
  1795. /// let mut url = Url::parse("mailto:rmz@example.com")?;
  1796. /// let result = url.set_username("user1");
  1797. /// assert_eq!(url.as_str(), "mailto:rmz@example.com");
  1798. /// assert!(result.is_err());
  1799. /// # Ok(())
  1800. /// # }
  1801. /// # run().unwrap();
  1802. /// ```
  1803. ///
  1804. /// Setup username to user1
  1805. ///
  1806. /// ```rust
  1807. /// use url::{Url, ParseError};
  1808. ///
  1809. /// # fn run() -> Result<(), ParseError> {
  1810. /// let mut url = Url::parse("ftp://:secre1@example.com/")?;
  1811. /// let result = url.set_username("user1");
  1812. /// assert!(result.is_ok());
  1813. /// assert_eq!(url.username(), "user1");
  1814. /// assert_eq!(url.as_str(), "ftp://user1:secre1@example.com/");
  1815. /// # Ok(())
  1816. /// # }
  1817. /// # run().unwrap();
  1818. /// ```
  1819. #[allow(clippy::result_map_unit_fn)]
  1820. pub fn set_username(&mut self, username: &str) -> Result<(), ()> {
  1821. // has_host implies !cannot_be_a_base
  1822. if !self.has_host() || self.host() == Some(Host::Domain("")) || self.scheme() == "file" {
  1823. return Err(());
  1824. }
  1825. let username_start = self.scheme_end + 3;
  1826. debug_assert!(self.slice(self.scheme_end..username_start) == "://");
  1827. if self.slice(username_start..self.username_end) == username {
  1828. return Ok(());
  1829. }
  1830. let after_username = self.slice(self.username_end..).to_owned();
  1831. self.serialization.truncate(username_start as usize);
  1832. self.serialization
  1833. .extend(utf8_percent_encode(username, USERINFO));
  1834. let mut removed_bytes = self.username_end;
  1835. self.username_end = to_u32(self.serialization.len()).unwrap();
  1836. let mut added_bytes = self.username_end;
  1837. let new_username_is_empty = self.username_end == username_start;
  1838. match (new_username_is_empty, after_username.chars().next()) {
  1839. (true, Some('@')) => {
  1840. removed_bytes += 1;
  1841. self.serialization.push_str(&after_username[1..]);
  1842. }
  1843. (false, Some('@')) | (_, Some(':')) | (true, _) => {
  1844. self.serialization.push_str(&after_username);
  1845. }
  1846. (false, _) => {
  1847. added_bytes += 1;
  1848. self.serialization.push('@');
  1849. self.serialization.push_str(&after_username);
  1850. }
  1851. }
  1852. let adjust = |index: &mut u32| {
  1853. *index -= removed_bytes;
  1854. *index += added_bytes;
  1855. };
  1856. adjust(&mut self.host_start);
  1857. adjust(&mut self.host_end);
  1858. adjust(&mut self.path_start);
  1859. if let Some(ref mut index) = self.query_start {
  1860. adjust(index)
  1861. }
  1862. if let Some(ref mut index) = self.fragment_start {
  1863. adjust(index)
  1864. }
  1865. Ok(())
  1866. }
  1867. /// Change this URL’s scheme.
  1868. ///
  1869. /// Do nothing and return `Err` under the following circumstances:
  1870. ///
  1871. /// * If the new scheme is not in `[a-zA-Z][a-zA-Z0-9+.-]+`
  1872. /// * If this URL is cannot-be-a-base and the new scheme is one of
  1873. /// `http`, `https`, `ws`, `wss` or `ftp`
  1874. /// * If either the old or new scheme is `http`, `https`, `ws`,
  1875. /// `wss` or `ftp` and the other is not one of these
  1876. /// * If the new scheme is `file` and this URL includes credentials
  1877. /// or has a non-null port
  1878. /// * If this URL's scheme is `file` and its host is empty or null
  1879. ///
  1880. /// See also [the URL specification's section on legal scheme state
  1881. /// overrides](https://url.spec.whatwg.org/#scheme-state).
  1882. ///
  1883. /// # Examples
  1884. ///
  1885. /// Change the URL’s scheme from `https` to `foo`:
  1886. ///
  1887. /// ```
  1888. /// use url::Url;
  1889. /// # use url::ParseError;
  1890. ///
  1891. /// # fn run() -> Result<(), ParseError> {
  1892. /// let mut url = Url::parse("https://example.net")?;
  1893. /// let result = url.set_scheme("http");
  1894. /// assert_eq!(url.as_str(), "http://example.net/");
  1895. /// assert!(result.is_ok());
  1896. /// # Ok(())
  1897. /// # }
  1898. /// # run().unwrap();
  1899. /// ```
  1900. /// Change the URL’s scheme from `foo` to `bar`:
  1901. ///
  1902. /// ```
  1903. /// use url::Url;
  1904. /// # use url::ParseError;
  1905. ///
  1906. /// # fn run() -> Result<(), ParseError> {
  1907. /// let mut url = Url::parse("foo://example.net")?;
  1908. /// let result = url.set_scheme("bar");
  1909. /// assert_eq!(url.as_str(), "bar://example.net");
  1910. /// assert!(result.is_ok());
  1911. /// # Ok(())
  1912. /// # }
  1913. /// # run().unwrap();
  1914. /// ```
  1915. ///
  1916. /// Cannot change URL’s scheme from `https` to `foõ`:
  1917. ///
  1918. /// ```
  1919. /// use url::Url;
  1920. /// # use url::ParseError;
  1921. ///
  1922. /// # fn run() -> Result<(), ParseError> {
  1923. /// let mut url = Url::parse("https://example.net")?;
  1924. /// let result = url.set_scheme("foõ");
  1925. /// assert_eq!(url.as_str(), "https://example.net/");
  1926. /// assert!(result.is_err());
  1927. /// # Ok(())
  1928. /// # }
  1929. /// # run().unwrap();
  1930. /// ```
  1931. ///
  1932. /// Cannot change URL’s scheme from `mailto` (cannot-be-a-base) to `https`:
  1933. ///
  1934. /// ```
  1935. /// use url::Url;
  1936. /// # use url::ParseError;
  1937. ///
  1938. /// # fn run() -> Result<(), ParseError> {
  1939. /// let mut url = Url::parse("mailto:rms@example.net")?;
  1940. /// let result = url.set_scheme("https");
  1941. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1942. /// assert!(result.is_err());
  1943. /// # Ok(())
  1944. /// # }
  1945. /// # run().unwrap();
  1946. /// ```
  1947. /// Cannot change the URL’s scheme from `foo` to `https`:
  1948. ///
  1949. /// ```
  1950. /// use url::Url;
  1951. /// # use url::ParseError;
  1952. ///
  1953. /// # fn run() -> Result<(), ParseError> {
  1954. /// let mut url = Url::parse("foo://example.net")?;
  1955. /// let result = url.set_scheme("https");
  1956. /// assert_eq!(url.as_str(), "foo://example.net");
  1957. /// assert!(result.is_err());
  1958. /// # Ok(())
  1959. /// # }
  1960. /// # run().unwrap();
  1961. /// ```
  1962. /// Cannot change the URL’s scheme from `http` to `foo`:
  1963. ///
  1964. /// ```
  1965. /// use url::Url;
  1966. /// # use url::ParseError;
  1967. ///
  1968. /// # fn run() -> Result<(), ParseError> {
  1969. /// let mut url = Url::parse("http://example.net")?;
  1970. /// let result = url.set_scheme("foo");
  1971. /// assert_eq!(url.as_str(), "http://example.net/");
  1972. /// assert!(result.is_err());
  1973. /// # Ok(())
  1974. /// # }
  1975. /// # run().unwrap();
  1976. /// ```
  1977. #[allow(clippy::result_map_unit_fn, clippy::suspicious_operation_groupings)]
  1978. pub fn set_scheme(&mut self, scheme: &str) -> Result<(), ()> {
  1979. let mut parser = Parser::for_setter(String::new());
  1980. let remaining = parser.parse_scheme(parser::Input::new(scheme))?;
  1981. let new_scheme_type = SchemeType::from(&parser.serialization);
  1982. let old_scheme_type = SchemeType::from(self.scheme());
  1983. // If url’s scheme is a special scheme and buffer is not a special scheme, then return.
  1984. if (new_scheme_type.is_special() && !old_scheme_type.is_special()) ||
  1985. // If url’s scheme is not a special scheme and buffer is a special scheme, then return.
  1986. (!new_scheme_type.is_special() && old_scheme_type.is_special()) ||
  1987. // If url includes credentials or has a non-null port, and buffer is "file", then return.
  1988. // If url’s scheme is "file" and its host is an empty host or null, then return.
  1989. (new_scheme_type.is_file() && self.has_authority())
  1990. {
  1991. return Err(());
  1992. }
  1993. if !remaining.is_empty() || (!self.has_host() && new_scheme_type.is_special()) {
  1994. return Err(());
  1995. }
  1996. let old_scheme_end = self.scheme_end;
  1997. let new_scheme_end = to_u32(parser.serialization.len()).unwrap();
  1998. let adjust = |index: &mut u32| {
  1999. *index -= old_scheme_end;
  2000. *index += new_scheme_end;
  2001. };
  2002. self.scheme_end = new_scheme_end;
  2003. adjust(&mut self.username_end);
  2004. adjust(&mut self.host_start);
  2005. adjust(&mut self.host_end);
  2006. adjust(&mut self.path_start);
  2007. if let Some(ref mut index) = self.query_start {
  2008. adjust(index)
  2009. }
  2010. if let Some(ref mut index) = self.fragment_start {
  2011. adjust(index)
  2012. }
  2013. parser.serialization.push_str(self.slice(old_scheme_end..));
  2014. self.serialization = parser.serialization;
  2015. // Update the port so it can be removed
  2016. // If it is the scheme's default
  2017. // we don't mind it silently failing
  2018. // if there was no port in the first place
  2019. let previous_port = self.port();
  2020. let _ = self.set_port(previous_port);
  2021. Ok(())
  2022. }
  2023. /// Convert a file name as `std::path::Path` into an URL in the `file` scheme.
  2024. ///
  2025. /// This returns `Err` if the given path is not absolute or,
  2026. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`) or a UNC prefix (`\\`).
  2027. ///
  2028. /// # Examples
  2029. ///
  2030. /// On Unix-like platforms:
  2031. ///
  2032. /// ```
  2033. /// # if cfg!(unix) {
  2034. /// use url::Url;
  2035. ///
  2036. /// # fn run() -> Result<(), ()> {
  2037. /// let url = Url::from_file_path("/tmp/foo.txt")?;
  2038. /// assert_eq!(url.as_str(), "file:///tmp/foo.txt");
  2039. ///
  2040. /// let url = Url::from_file_path("../foo.txt");
  2041. /// assert!(url.is_err());
  2042. ///
  2043. /// let url = Url::from_file_path("https://google.com/");
  2044. /// assert!(url.is_err());
  2045. /// # Ok(())
  2046. /// # }
  2047. /// # run().unwrap();
  2048. /// # }
  2049. /// ```
  2050. #[cfg(any(unix, windows, target_os = "redox"))]
  2051. #[allow(clippy::result_map_unit_fn)]
  2052. pub fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  2053. let mut serialization = "file://".to_owned();
  2054. let host_start = serialization.len() as u32;
  2055. let (host_end, host) = path_to_file_url_segments(path.as_ref(), &mut serialization)?;
  2056. Ok(Url {
  2057. serialization,
  2058. scheme_end: "file".len() as u32,
  2059. username_end: host_start,
  2060. host_start,
  2061. host_end,
  2062. host,
  2063. port: None,
  2064. path_start: host_end,
  2065. query_start: None,
  2066. fragment_start: None,
  2067. })
  2068. }
  2069. /// Convert a directory name as `std::path::Path` into an URL in the `file` scheme.
  2070. ///
  2071. /// This returns `Err` if the given path is not absolute or,
  2072. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`) or a UNC prefix (`\\`).
  2073. ///
  2074. /// Compared to `from_file_path`, this ensure that URL’s the path has a trailing slash
  2075. /// so that the entire path is considered when using this URL as a base URL.
  2076. ///
  2077. /// For example:
  2078. ///
  2079. /// * `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
  2080. /// as the base URL is `file:///var/www/index.html`
  2081. /// * `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www"))`
  2082. /// as the base URL is `file:///var/index.html`, which might not be what was intended.
  2083. ///
  2084. /// Note that `std::path` does not consider trailing slashes significant
  2085. /// and usually does not include them (e.g. in `Path::parent()`).
  2086. #[cfg(any(unix, windows, target_os = "redox"))]
  2087. #[allow(clippy::result_map_unit_fn)]
  2088. pub fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  2089. let mut url = Url::from_file_path(path)?;
  2090. if !url.serialization.ends_with('/') {
  2091. url.serialization.push('/')
  2092. }
  2093. Ok(url)
  2094. }
  2095. /// Serialize with Serde using the internal representation of the `Url` struct.
  2096. ///
  2097. /// The corresponding `deserialize_internal` method sacrifices some invariant-checking
  2098. /// for speed, compared to the `Deserialize` trait impl.
  2099. ///
  2100. /// This method is only available if the `serde` Cargo feature is enabled.
  2101. #[cfg(feature = "serde")]
  2102. #[deny(unused)]
  2103. pub fn serialize_internal<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  2104. where
  2105. S: serde::Serializer,
  2106. {
  2107. use serde::Serialize;
  2108. // Destructuring first lets us ensure that adding or removing fields forces this method
  2109. // to be updated
  2110. let Url {
  2111. ref serialization,
  2112. ref scheme_end,
  2113. ref username_end,
  2114. ref host_start,
  2115. ref host_end,
  2116. ref host,
  2117. ref port,
  2118. ref path_start,
  2119. ref query_start,
  2120. ref fragment_start,
  2121. } = *self;
  2122. (
  2123. serialization,
  2124. scheme_end,
  2125. username_end,
  2126. host_start,
  2127. host_end,
  2128. host,
  2129. port,
  2130. path_start,
  2131. query_start,
  2132. fragment_start,
  2133. )
  2134. .serialize(serializer)
  2135. }
  2136. /// Serialize with Serde using the internal representation of the `Url` struct.
  2137. ///
  2138. /// The corresponding `deserialize_internal` method sacrifices some invariant-checking
  2139. /// for speed, compared to the `Deserialize` trait impl.
  2140. ///
  2141. /// This method is only available if the `serde` Cargo feature is enabled.
  2142. #[cfg(feature = "serde")]
  2143. #[deny(unused)]
  2144. pub fn deserialize_internal<'de, D>(deserializer: D) -> Result<Self, D::Error>
  2145. where
  2146. D: serde::Deserializer<'de>,
  2147. {
  2148. use serde::de::{Deserialize, Error, Unexpected};
  2149. let (
  2150. serialization,
  2151. scheme_end,
  2152. username_end,
  2153. host_start,
  2154. host_end,
  2155. host,
  2156. port,
  2157. path_start,
  2158. query_start,
  2159. fragment_start,
  2160. ) = Deserialize::deserialize(deserializer)?;
  2161. let url = Url {
  2162. serialization,
  2163. scheme_end,
  2164. username_end,
  2165. host_start,
  2166. host_end,
  2167. host,
  2168. port,
  2169. path_start,
  2170. query_start,
  2171. fragment_start,
  2172. };
  2173. if cfg!(debug_assertions) {
  2174. url.check_invariants().map_err(|reason| {
  2175. let reason: &str = &reason;
  2176. Error::invalid_value(Unexpected::Other("value"), &reason)
  2177. })?
  2178. }
  2179. Ok(url)
  2180. }
  2181. /// Assuming the URL is in the `file` scheme or similar,
  2182. /// convert its path to an absolute `std::path::Path`.
  2183. ///
  2184. /// **Note:** This does not actually check the URL’s `scheme`,
  2185. /// and may give nonsensical results for other schemes.
  2186. /// It is the user’s responsibility to check the URL’s scheme before calling this.
  2187. ///
  2188. /// ```
  2189. /// # use url::Url;
  2190. /// # let url = Url::parse("file:///etc/passwd").unwrap();
  2191. /// let path = url.to_file_path();
  2192. /// ```
  2193. ///
  2194. /// Returns `Err` if the host is neither empty nor `"localhost"` (except on Windows, where
  2195. /// `file:` URLs may have a non-local host),
  2196. /// or if `Path::new_opt()` returns `None`.
  2197. /// (That is, if the percent-decoded path contains a NUL byte or,
  2198. /// for a Windows path, is not UTF-8.)
  2199. #[inline]
  2200. #[cfg(any(unix, windows, target_os = "redox"))]
  2201. #[allow(clippy::result_map_unit_fn)]
  2202. pub fn to_file_path(&self) -> Result<PathBuf, ()> {
  2203. if let Some(segments) = self.path_segments() {
  2204. let host = match self.host() {
  2205. None | Some(Host::Domain("localhost")) => None,
  2206. Some(_) if cfg!(windows) && self.scheme() == "file" => {
  2207. Some(&self.serialization[self.host_start as usize..self.host_end as usize])
  2208. }
  2209. _ => return Err(()),
  2210. };
  2211. return file_url_segments_to_pathbuf(host, segments);
  2212. }
  2213. Err(())
  2214. }
  2215. // Private helper methods:
  2216. #[inline]
  2217. fn slice<R>(&self, range: R) -> &str
  2218. where
  2219. R: RangeArg,
  2220. {
  2221. range.slice_of(&self.serialization)
  2222. }
  2223. #[inline]
  2224. fn byte_at(&self, i: u32) -> u8 {
  2225. self.serialization.as_bytes()[i as usize]
  2226. }
  2227. }
  2228. /// Parse a string as an URL, without a base URL or encoding override.
  2229. impl str::FromStr for Url {
  2230. type Err = ParseError;
  2231. #[inline]
  2232. fn from_str(input: &str) -> Result<Url, crate::ParseError> {
  2233. Url::parse(input)
  2234. }
  2235. }
  2236. impl<'a> TryFrom<&'a str> for Url {
  2237. type Error = ParseError;
  2238. fn try_from(s: &'a str) -> Result<Self, Self::Error> {
  2239. Url::parse(s)
  2240. }
  2241. }
  2242. /// Display the serialization of this URL.
  2243. impl fmt::Display for Url {
  2244. #[inline]
  2245. fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
  2246. fmt::Display::fmt(&self.serialization, formatter)
  2247. }
  2248. }
  2249. /// String converstion.
  2250. impl From<Url> for String {
  2251. fn from(value: Url) -> String {
  2252. value.serialization
  2253. }
  2254. }
  2255. /// Debug the serialization of this URL.
  2256. impl fmt::Debug for Url {
  2257. #[inline]
  2258. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  2259. formatter
  2260. .debug_struct("Url")
  2261. .field("scheme", &self.scheme())
  2262. .field("username", &self.username())
  2263. .field("password", &self.password())
  2264. .field("host", &self.host())
  2265. .field("port", &self.port())
  2266. .field("path", &self.path())
  2267. .field("query", &self.query())
  2268. .field("fragment", &self.fragment())
  2269. .finish()
  2270. }
  2271. }
  2272. /// URLs compare like their serialization.
  2273. impl Eq for Url {}
  2274. /// URLs compare like their serialization.
  2275. impl PartialEq for Url {
  2276. #[inline]
  2277. fn eq(&self, other: &Self) -> bool {
  2278. self.serialization == other.serialization
  2279. }
  2280. }
  2281. /// URLs compare like their serialization.
  2282. impl Ord for Url {
  2283. #[inline]
  2284. fn cmp(&self, other: &Self) -> cmp::Ordering {
  2285. self.serialization.cmp(&other.serialization)
  2286. }
  2287. }
  2288. /// URLs compare like their serialization.
  2289. impl PartialOrd for Url {
  2290. #[inline]
  2291. fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
  2292. self.serialization.partial_cmp(&other.serialization)
  2293. }
  2294. }
  2295. /// URLs hash like their serialization.
  2296. impl hash::Hash for Url {
  2297. #[inline]
  2298. fn hash<H>(&self, state: &mut H)
  2299. where
  2300. H: hash::Hasher,
  2301. {
  2302. hash::Hash::hash(&self.serialization, state)
  2303. }
  2304. }
  2305. /// Return the serialization of this URL.
  2306. impl AsRef<str> for Url {
  2307. #[inline]
  2308. fn as_ref(&self) -> &str {
  2309. &self.serialization
  2310. }
  2311. }
  2312. trait RangeArg {
  2313. fn slice_of<'a>(&self, s: &'a str) -> &'a str;
  2314. }
  2315. impl RangeArg for Range<u32> {
  2316. #[inline]
  2317. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  2318. &s[self.start as usize..self.end as usize]
  2319. }
  2320. }
  2321. impl RangeArg for RangeFrom<u32> {
  2322. #[inline]
  2323. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  2324. &s[self.start as usize..]
  2325. }
  2326. }
  2327. impl RangeArg for RangeTo<u32> {
  2328. #[inline]
  2329. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  2330. &s[..self.end as usize]
  2331. }
  2332. }
  2333. /// Serializes this URL into a `serde` stream.
  2334. ///
  2335. /// This implementation is only available if the `serde` Cargo feature is enabled.
  2336. #[cfg(feature = "serde")]
  2337. impl serde::Serialize for Url {
  2338. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  2339. where
  2340. S: serde::Serializer,
  2341. {
  2342. serializer.serialize_str(self.as_str())
  2343. }
  2344. }
  2345. /// Deserializes this URL from a `serde` stream.
  2346. ///
  2347. /// This implementation is only available if the `serde` Cargo feature is enabled.
  2348. #[cfg(feature = "serde")]
  2349. impl<'de> serde::Deserialize<'de> for Url {
  2350. fn deserialize<D>(deserializer: D) -> Result<Url, D::Error>
  2351. where
  2352. D: serde::Deserializer<'de>,
  2353. {
  2354. use serde::de::{Error, Unexpected, Visitor};
  2355. struct UrlVisitor;
  2356. impl<'de> Visitor<'de> for UrlVisitor {
  2357. type Value = Url;
  2358. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  2359. formatter.write_str("a string representing an URL")
  2360. }
  2361. fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
  2362. where
  2363. E: Error,
  2364. {
  2365. Url::parse(s).map_err(|err| {
  2366. let err_s = format!("{}", err);
  2367. Error::invalid_value(Unexpected::Str(s), &err_s.as_str())
  2368. })
  2369. }
  2370. }
  2371. deserializer.deserialize_str(UrlVisitor)
  2372. }
  2373. }
  2374. #[cfg(any(unix, target_os = "redox"))]
  2375. fn path_to_file_url_segments(
  2376. path: &Path,
  2377. serialization: &mut String,
  2378. ) -> Result<(u32, HostInternal), ()> {
  2379. use std::os::unix::prelude::OsStrExt;
  2380. if !path.is_absolute() {
  2381. return Err(());
  2382. }
  2383. let host_end = to_u32(serialization.len()).unwrap();
  2384. let mut empty = true;
  2385. // skip the root component
  2386. for component in path.components().skip(1) {
  2387. empty = false;
  2388. serialization.push('/');
  2389. serialization.extend(percent_encode(
  2390. component.as_os_str().as_bytes(),
  2391. PATH_SEGMENT,
  2392. ));
  2393. }
  2394. if empty {
  2395. // An URL’s path must not be empty.
  2396. serialization.push('/');
  2397. }
  2398. Ok((host_end, HostInternal::None))
  2399. }
  2400. #[cfg(windows)]
  2401. fn path_to_file_url_segments(
  2402. path: &Path,
  2403. serialization: &mut String,
  2404. ) -> Result<(u32, HostInternal), ()> {
  2405. path_to_file_url_segments_windows(path, serialization)
  2406. }
  2407. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  2408. #[cfg_attr(not(windows), allow(dead_code))]
  2409. fn path_to_file_url_segments_windows(
  2410. path: &Path,
  2411. serialization: &mut String,
  2412. ) -> Result<(u32, HostInternal), ()> {
  2413. use std::path::{Component, Prefix};
  2414. if !path.is_absolute() {
  2415. return Err(());
  2416. }
  2417. let mut components = path.components();
  2418. let host_start = serialization.len() + 1;
  2419. let host_end;
  2420. let host_internal;
  2421. match components.next() {
  2422. Some(Component::Prefix(ref p)) => match p.kind() {
  2423. Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => {
  2424. host_end = to_u32(serialization.len()).unwrap();
  2425. host_internal = HostInternal::None;
  2426. serialization.push('/');
  2427. serialization.push(letter as char);
  2428. serialization.push(':');
  2429. }
  2430. Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => {
  2431. let host = Host::parse(server.to_str().ok_or(())?).map_err(|_| ())?;
  2432. write!(serialization, "{}", host).unwrap();
  2433. host_end = to_u32(serialization.len()).unwrap();
  2434. host_internal = host.into();
  2435. serialization.push('/');
  2436. let share = share.to_str().ok_or(())?;
  2437. serialization.extend(percent_encode(share.as_bytes(), PATH_SEGMENT));
  2438. }
  2439. _ => return Err(()),
  2440. },
  2441. _ => return Err(()),
  2442. }
  2443. let mut path_only_has_prefix = true;
  2444. for component in components {
  2445. if component == Component::RootDir {
  2446. continue;
  2447. }
  2448. path_only_has_prefix = false;
  2449. // FIXME: somehow work with non-unicode?
  2450. let component = component.as_os_str().to_str().ok_or(())?;
  2451. serialization.push('/');
  2452. serialization.extend(percent_encode(component.as_bytes(), PATH_SEGMENT));
  2453. }
  2454. // A windows drive letter must end with a slash.
  2455. if serialization.len() > host_start
  2456. && parser::is_windows_drive_letter(&serialization[host_start..])
  2457. && path_only_has_prefix
  2458. {
  2459. serialization.push('/');
  2460. }
  2461. Ok((host_end, host_internal))
  2462. }
  2463. #[cfg(any(unix, target_os = "redox"))]
  2464. fn file_url_segments_to_pathbuf(
  2465. host: Option<&str>,
  2466. segments: str::Split<'_, char>,
  2467. ) -> Result<PathBuf, ()> {
  2468. use std::ffi::OsStr;
  2469. use std::os::unix::prelude::OsStrExt;
  2470. if host.is_some() {
  2471. return Err(());
  2472. }
  2473. let mut bytes = if cfg!(target_os = "redox") {
  2474. b"file:".to_vec()
  2475. } else {
  2476. Vec::new()
  2477. };
  2478. for segment in segments {
  2479. bytes.push(b'/');
  2480. bytes.extend(percent_decode(segment.as_bytes()));
  2481. }
  2482. // A windows drive letter must end with a slash.
  2483. if bytes.len() > 2
  2484. && matches!(bytes[bytes.len() - 2], b'a'..=b'z' | b'A'..=b'Z')
  2485. && matches!(bytes[bytes.len() - 1], b':' | b'|')
  2486. {
  2487. bytes.push(b'/');
  2488. }
  2489. let os_str = OsStr::from_bytes(&bytes);
  2490. let path = PathBuf::from(os_str);
  2491. debug_assert!(
  2492. path.is_absolute(),
  2493. "to_file_path() failed to produce an absolute Path"
  2494. );
  2495. Ok(path)
  2496. }
  2497. #[cfg(windows)]
  2498. fn file_url_segments_to_pathbuf(
  2499. host: Option<&str>,
  2500. segments: str::Split<char>,
  2501. ) -> Result<PathBuf, ()> {
  2502. file_url_segments_to_pathbuf_windows(host, segments)
  2503. }
  2504. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  2505. #[cfg_attr(not(windows), allow(dead_code))]
  2506. fn file_url_segments_to_pathbuf_windows(
  2507. host: Option<&str>,
  2508. mut segments: str::Split<'_, char>,
  2509. ) -> Result<PathBuf, ()> {
  2510. let mut string = if let Some(host) = host {
  2511. r"\\".to_owned() + host
  2512. } else {
  2513. let first = segments.next().ok_or(())?;
  2514. match first.len() {
  2515. 2 => {
  2516. if !first.starts_with(parser::ascii_alpha) || first.as_bytes()[1] != b':' {
  2517. return Err(());
  2518. }
  2519. first.to_owned()
  2520. }
  2521. 4 => {
  2522. if !first.starts_with(parser::ascii_alpha) {
  2523. return Err(());
  2524. }
  2525. let bytes = first.as_bytes();
  2526. if bytes[1] != b'%' || bytes[2] != b'3' || (bytes[3] != b'a' && bytes[3] != b'A') {
  2527. return Err(());
  2528. }
  2529. first[0..1].to_owned() + ":"
  2530. }
  2531. _ => return Err(()),
  2532. }
  2533. };
  2534. for segment in segments {
  2535. string.push('\\');
  2536. // Currently non-unicode windows paths cannot be represented
  2537. match String::from_utf8(percent_decode(segment.as_bytes()).collect()) {
  2538. Ok(s) => string.push_str(&s),
  2539. Err(..) => return Err(()),
  2540. }
  2541. }
  2542. let path = PathBuf::from(string);
  2543. debug_assert!(
  2544. path.is_absolute(),
  2545. "to_file_path() failed to produce an absolute Path"
  2546. );
  2547. Ok(path)
  2548. }
  2549. /// Implementation detail of `Url::query_pairs_mut`. Typically not used directly.
  2550. #[derive(Debug)]
  2551. pub struct UrlQuery<'a> {
  2552. url: Option<&'a mut Url>,
  2553. fragment: Option<String>,
  2554. }
  2555. // `as_mut_string` string here exposes the internal serialization of an `Url`,
  2556. // which should not be exposed to users.
  2557. // We achieve that by not giving users direct access to `UrlQuery`:
  2558. // * Its fields are private
  2559. // (and so can not be constructed with struct literal syntax outside of this crate),
  2560. // * It has no constructor
  2561. // * It is only visible (on the type level) to users in the return type of
  2562. // `Url::query_pairs_mut` which is `Serializer<UrlQuery>`
  2563. // * `Serializer` keeps its target in a private field
  2564. // * Unlike in other `Target` impls, `UrlQuery::finished` does not return `Self`.
  2565. impl<'a> form_urlencoded::Target for UrlQuery<'a> {
  2566. fn as_mut_string(&mut self) -> &mut String {
  2567. &mut self.url.as_mut().unwrap().serialization
  2568. }
  2569. fn finish(mut self) -> &'a mut Url {
  2570. let url = self.url.take().unwrap();
  2571. url.restore_already_parsed_fragment(self.fragment.take());
  2572. url
  2573. }
  2574. type Finished = &'a mut Url;
  2575. }
  2576. impl<'a> Drop for UrlQuery<'a> {
  2577. fn drop(&mut self) {
  2578. if let Some(url) = self.url.take() {
  2579. url.restore_already_parsed_fragment(self.fragment.take())
  2580. }
  2581. }
  2582. }