lib.rs 89 KB

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