lib.rs 99 KB

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