lib.rs 88 KB

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