lib.rs 99 KB

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