lib.rs 82 KB

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