lib.rs 99 KB

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