lib.rs 95 KB

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