lib.rs 83 KB

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