lib.rs 101 KB

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