lib.rs 103 KB

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