lib.rs 105 KB

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