lib.rs 79 KB

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