lib.rs 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  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};
  20. let issue_list_url = Url::parse(
  21. "https://github.com/rust-lang/rust/issues?labels=E-easy&state=open"
  22. ).unwrap();
  23. assert!(issue_list_url.scheme() == "https");
  24. assert!(issue_list_url.username() == "");
  25. assert!(issue_list_url.password() == None);
  26. assert!(issue_list_url.host_str() == Some("github.com"));
  27. assert!(issue_list_url.host() == Some(Host::Domain("github.com")));
  28. assert!(issue_list_url.port() == None);
  29. assert!(issue_list_url.path() == "/rust-lang/rust/issues");
  30. assert!(issue_list_url.path_segments().map(|c| c.collect::<Vec<_>>()) ==
  31. Some(vec!["rust-lang", "rust", "issues"]));
  32. assert!(issue_list_url.query() == Some("labels=E-easy&state=open"));
  33. assert!(issue_list_url.fragment() == None);
  34. assert!(!issue_list_url.cannot_be_a_base());
  35. ```
  36. Some URLs are said to be *cannot-be-a-base*:
  37. they don’t have a username, password, host, or port,
  38. and their "path" is an arbitrary string rather than slash-separated segments:
  39. ```
  40. use url::Url;
  41. let data_url = Url::parse("data:text/plain,Hello?World#").unwrap();
  42. assert!(data_url.cannot_be_a_base());
  43. assert!(data_url.scheme() == "data");
  44. assert!(data_url.path() == "text/plain,Hello");
  45. assert!(data_url.path_segments().is_none());
  46. assert!(data_url.query() == Some("World"));
  47. assert!(data_url.fragment() == Some(""));
  48. ```
  49. # Base URL
  50. Many contexts allow URL *references* that can be relative to a *base URL*:
  51. ```html
  52. <link rel="stylesheet" href="../main.css">
  53. ```
  54. Since parsed URL are absolute, giving a base is required for parsing relative URLs:
  55. ```
  56. use url::{Url, ParseError};
  57. assert!(Url::parse("../main.css") == Err(ParseError::RelativeUrlWithoutBase))
  58. ```
  59. Use the `join` method on an `Url` to use it as a base URL:
  60. ```
  61. use url::Url;
  62. let this_document = Url::parse("http://servo.github.io/rust-url/url/index.html").unwrap();
  63. let css_url = this_document.join("../main.css").unwrap();
  64. assert_eq!(css_url.as_str(), "http://servo.github.io/rust-url/main.css")
  65. */
  66. #![doc(html_root_url = "https://docs.rs/url/1.4.0")]
  67. #[cfg(feature="rustc-serialize")] extern crate rustc_serialize;
  68. #[macro_use] extern crate matches;
  69. #[cfg(feature="serde")] extern crate serde;
  70. #[cfg(feature="heapsize")] #[macro_use] extern crate heapsize;
  71. pub extern crate idna;
  72. use encoding::EncodingOverride;
  73. #[cfg(feature = "heapsize")] use heapsize::HeapSizeOf;
  74. use host::HostInternal;
  75. use parser::{Parser, Context, SchemeType, to_u32};
  76. use percent_encoding::{PATH_SEGMENT_ENCODE_SET, USERINFO_ENCODE_SET,
  77. percent_encode, percent_decode, utf8_percent_encode};
  78. use std::borrow::Borrow;
  79. use std::cmp;
  80. #[cfg(feature = "serde")] use std::error::Error;
  81. use std::fmt::{self, Write};
  82. use std::hash;
  83. use std::io;
  84. use std::mem;
  85. use std::net::{ToSocketAddrs, IpAddr};
  86. use std::ops::{Range, RangeFrom, RangeTo};
  87. use std::path::{Path, PathBuf};
  88. use std::str;
  89. pub use origin::{Origin, OpaqueOrigin};
  90. pub use host::{Host, HostAndPort, SocketAddrs};
  91. pub use path_segments::PathSegmentsMut;
  92. pub use parser::ParseError;
  93. pub use slicing::Position;
  94. mod encoding;
  95. mod host;
  96. mod origin;
  97. mod path_segments;
  98. mod parser;
  99. mod slicing;
  100. pub mod form_urlencoded;
  101. pub mod percent_encoding;
  102. pub mod quirks;
  103. /// A parsed URL record.
  104. #[derive(Clone)]
  105. pub struct Url {
  106. /// Syntax in pseudo-BNF:
  107. ///
  108. /// url = scheme ":" [ hierarchical | non-hierarchical ] [ "?" query ]? [ "#" fragment ]?
  109. /// non-hierarchical = non-hierarchical-path
  110. /// non-hierarchical-path = /* Does not start with "/" */
  111. /// hierarchical = authority? hierarchical-path
  112. /// authority = "//" userinfo? host [ ":" port ]?
  113. /// userinfo = username [ ":" password ]? "@"
  114. /// hierarchical-path = [ "/" path-segment ]+
  115. serialization: String,
  116. // Components
  117. scheme_end: u32, // Before ':'
  118. username_end: u32, // Before ':' (if a password is given) or '@' (if not)
  119. host_start: u32,
  120. host_end: u32,
  121. host: HostInternal,
  122. port: Option<u16>,
  123. path_start: u32, // Before initial '/', if any
  124. query_start: Option<u32>, // Before '?', unlike Position::QueryStart
  125. fragment_start: Option<u32>, // Before '#', unlike Position::FragmentStart
  126. }
  127. #[cfg(feature = "heapsize")]
  128. impl HeapSizeOf for Url {
  129. fn heap_size_of_children(&self) -> usize {
  130. self.serialization.heap_size_of_children()
  131. }
  132. }
  133. /// Full configuration for the URL parser.
  134. #[derive(Copy, Clone)]
  135. pub struct ParseOptions<'a> {
  136. base_url: Option<&'a Url>,
  137. encoding_override: encoding::EncodingOverride,
  138. log_syntax_violation: Option<&'a Fn(&'static str)>,
  139. }
  140. impl<'a> ParseOptions<'a> {
  141. /// Change the base URL
  142. pub fn base_url(mut self, new: Option<&'a Url>) -> Self {
  143. self.base_url = new;
  144. self
  145. }
  146. /// Override the character encoding of query strings.
  147. /// This is a legacy concept only relevant for HTML.
  148. ///
  149. /// `EncodingRef` is defined in [rust-encoding](https://github.com/lifthrasiir/rust-encoding).
  150. ///
  151. /// This method is only available if the `query_encoding`
  152. /// [feature](http://doc.crates.io/manifest.html#the-features-section]) is enabled.
  153. #[cfg(feature = "query_encoding")]
  154. pub fn encoding_override(mut self, new: Option<encoding::EncodingRef>) -> Self {
  155. self.encoding_override = EncodingOverride::from_opt_encoding(new).to_output_encoding();
  156. self
  157. }
  158. /// Call the provided function or closure on non-fatal parse errors.
  159. pub fn log_syntax_violation(mut self, new: Option<&'a Fn(&'static str)>) -> Self {
  160. self.log_syntax_violation = new;
  161. self
  162. }
  163. /// Parse an URL string with the configuration so far.
  164. pub fn parse(self, input: &str) -> Result<Url, ::ParseError> {
  165. Parser {
  166. serialization: String::with_capacity(input.len()),
  167. base_url: self.base_url,
  168. query_encoding_override: self.encoding_override,
  169. log_syntax_violation: self.log_syntax_violation,
  170. context: Context::UrlParser,
  171. }.parse_url(input)
  172. }
  173. }
  174. impl Url {
  175. /// Parse an absolute URL from a string.
  176. ///
  177. /// # Examples
  178. ///
  179. /// ```rust
  180. /// use url::Url;
  181. ///
  182. /// let url = Url::parse("https://example.net").unwrap();
  183. /// ```
  184. #[inline]
  185. pub fn parse(input: &str) -> Result<Url, ::ParseError> {
  186. Url::options().parse(input)
  187. }
  188. /// Parse an absolute URL from a string and add params to its query string.
  189. ///
  190. /// Existing params are not removed.
  191. ///
  192. /// # Examples
  193. ///
  194. /// ```rust
  195. /// use url::Url;
  196. ///
  197. /// let url = Url::parse_with_params("https://example.net?dont=clobberme",
  198. /// &[("lang", "rust"), ("browser", "servo")]);
  199. /// ```
  200. #[inline]
  201. pub fn parse_with_params<I, K, V>(input: &str, iter: I) -> Result<Url, ::ParseError>
  202. where I: IntoIterator,
  203. I::Item: Borrow<(K, V)>,
  204. K: AsRef<str>,
  205. V: AsRef<str>
  206. {
  207. let mut url = Url::options().parse(input);
  208. if let Ok(ref mut url) = url {
  209. url.query_pairs_mut().extend_pairs(iter);
  210. }
  211. url
  212. }
  213. /// Parse a string as an URL, with this URL as the base URL.
  214. ///
  215. /// Note: a trailing slash is significant.
  216. /// Without it, the last path component is considered to be a “file” name
  217. /// to be removed to get at the “directory” that is used as the base:
  218. ///
  219. /// # Examples
  220. ///
  221. /// ```rust
  222. /// use url::Url;
  223. ///
  224. /// let base = Url::parse("https://example.net/a/b.html").unwrap();
  225. /// let url = base.join("c.png").unwrap();
  226. /// assert_eq!(url.as_str(), "https://example.net/a/c.png"); // Not /a/b.html/c.png
  227. ///
  228. /// let base = Url::parse("https://example.net/a/b/").unwrap();
  229. /// let url = base.join("c.png").unwrap();
  230. /// assert_eq!(url.as_str(), "https://example.net/a/b/c.png");
  231. /// ```
  232. #[inline]
  233. pub fn join(&self, input: &str) -> Result<Url, ::ParseError> {
  234. Url::options().base_url(Some(self)).parse(input)
  235. }
  236. /// Return a default `ParseOptions` that can fully configure the URL parser.
  237. pub fn options<'a>() -> ParseOptions<'a> {
  238. ParseOptions {
  239. base_url: None,
  240. encoding_override: EncodingOverride::utf8(),
  241. log_syntax_violation: None,
  242. }
  243. }
  244. /// Return the serialization of this URL.
  245. ///
  246. /// This is fast since that serialization is already stored in the `Url` struct.
  247. ///
  248. /// # Examples
  249. ///
  250. /// ```rust
  251. /// use url::Url;
  252. ///
  253. /// let url_str = "https://example.net/";
  254. /// let url = Url::parse(url_str).unwrap();
  255. /// assert_eq!(url.as_str(), url_str);
  256. /// ```
  257. #[inline]
  258. pub fn as_str(&self) -> &str {
  259. &self.serialization
  260. }
  261. /// Return the serialization of this URL.
  262. ///
  263. /// This consumes the `Url` and takes ownership of the `String` stored in it.
  264. ///
  265. /// # Examples
  266. ///
  267. /// ```rust
  268. /// use url::Url;
  269. ///
  270. /// let url_str = "https://example.net/";
  271. /// let url = Url::parse(url_str).unwrap();
  272. /// assert_eq!(url.into_string(), url_str);
  273. /// ```
  274. #[inline]
  275. pub fn into_string(self) -> String {
  276. self.serialization
  277. }
  278. /// For internal testing, not part of the public API.
  279. ///
  280. /// Methods of the `Url` struct assume a number of invariants.
  281. /// This checks each of these invariants and panic if one is not met.
  282. /// This is for testing rust-url itself.
  283. #[doc(hidden)]
  284. pub fn check_invariants(&self) -> Result<(), String> {
  285. macro_rules! assert {
  286. ($x: expr) => {
  287. if !$x {
  288. return Err(format!("!( {} ) for URL {:?}",
  289. stringify!($x), self.serialization))
  290. }
  291. }
  292. }
  293. macro_rules! assert_eq {
  294. ($a: expr, $b: expr) => {
  295. {
  296. let a = $a;
  297. let b = $b;
  298. if a != b {
  299. return Err(format!("{:?} != {:?} ({} != {}) for URL {:?}",
  300. a, b, stringify!($a), stringify!($b),
  301. self.serialization))
  302. }
  303. }
  304. }
  305. }
  306. assert!(self.scheme_end >= 1);
  307. assert!(matches!(self.byte_at(0), b'a'...b'z' | b'A'...b'Z'));
  308. assert!(self.slice(1..self.scheme_end).chars()
  309. .all(|c| matches!(c, 'a'...'z' | 'A'...'Z' | '0'...'9' | '+' | '-' | '.')));
  310. assert_eq!(self.byte_at(self.scheme_end), b':');
  311. if self.slice(self.scheme_end + 1 ..).starts_with("//") {
  312. // URL with authority
  313. match self.byte_at(self.username_end) {
  314. b':' => {
  315. assert!(self.host_start >= self.username_end + 2);
  316. assert_eq!(self.byte_at(self.host_start - 1), b'@');
  317. }
  318. b'@' => assert!(self.host_start == self.username_end + 1),
  319. _ => assert_eq!(self.username_end, self.scheme_end + 3),
  320. }
  321. assert!(self.host_start >= self.username_end);
  322. assert!(self.host_end >= self.host_start);
  323. let host_str = self.slice(self.host_start..self.host_end);
  324. match self.host {
  325. HostInternal::None => assert_eq!(host_str, ""),
  326. HostInternal::Ipv4(address) => assert_eq!(host_str, address.to_string()),
  327. HostInternal::Ipv6(address) => {
  328. let h: Host<String> = Host::Ipv6(address);
  329. assert_eq!(host_str, h.to_string())
  330. }
  331. HostInternal::Domain => {
  332. if SchemeType::from(self.scheme()).is_special() {
  333. assert!(!host_str.is_empty())
  334. }
  335. }
  336. }
  337. if self.path_start == self.host_end {
  338. assert_eq!(self.port, None);
  339. } else {
  340. assert_eq!(self.byte_at(self.host_end), b':');
  341. let port_str = self.slice(self.host_end + 1..self.path_start);
  342. assert_eq!(self.port, Some(port_str.parse::<u16>().expect("Couldn't parse port?")));
  343. }
  344. assert_eq!(self.byte_at(self.path_start), b'/');
  345. } else {
  346. // Anarchist URL (no authority)
  347. assert_eq!(self.username_end, self.scheme_end + 1);
  348. assert_eq!(self.host_start, self.scheme_end + 1);
  349. assert_eq!(self.host_end, self.scheme_end + 1);
  350. assert_eq!(self.host, HostInternal::None);
  351. assert_eq!(self.port, None);
  352. assert_eq!(self.path_start, self.scheme_end + 1);
  353. }
  354. if let Some(start) = self.query_start {
  355. assert!(start > self.path_start);
  356. assert_eq!(self.byte_at(start), b'?');
  357. }
  358. if let Some(start) = self.fragment_start {
  359. assert!(start > self.path_start);
  360. assert_eq!(self.byte_at(start), b'#');
  361. }
  362. if let (Some(query_start), Some(fragment_start)) = (self.query_start, self.fragment_start) {
  363. assert!(fragment_start > query_start);
  364. }
  365. let other = Url::parse(self.as_str()).expect("Failed to parse myself?");
  366. assert_eq!(&self.serialization, &other.serialization);
  367. assert_eq!(self.scheme_end, other.scheme_end);
  368. assert_eq!(self.username_end, other.username_end);
  369. assert_eq!(self.host_start, other.host_start);
  370. assert_eq!(self.host_end, other.host_end);
  371. assert!(self.host == other.host ||
  372. // XXX No host round-trips to empty host.
  373. // See https://github.com/whatwg/url/issues/79
  374. (self.host_str(), other.host_str()) == (None, Some("")));
  375. assert_eq!(self.port, other.port);
  376. assert_eq!(self.path_start, other.path_start);
  377. assert_eq!(self.query_start, other.query_start);
  378. assert_eq!(self.fragment_start, other.fragment_start);
  379. Ok(())
  380. }
  381. /// Return the origin of this URL (https://url.spec.whatwg.org/#origin)
  382. ///
  383. /// Note: this returns an opaque origin for `file:` URLs, which causes
  384. /// `url.origin() != url.origin()`.
  385. ///
  386. /// # Examples
  387. ///
  388. /// URL with `ftp` scheme:
  389. ///
  390. /// ```rust
  391. /// use url::{Host, Origin, Url};
  392. ///
  393. /// let url = Url::parse("ftp://example.com/foo").unwrap();
  394. /// assert_eq!(url.origin(),
  395. /// Origin::Tuple("ftp".into(),
  396. /// Host::Domain("example.com".into()),
  397. /// 21));
  398. /// ```
  399. ///
  400. /// URL with `blob` scheme:
  401. ///
  402. /// ```rust
  403. /// use url::{Host, Origin, Url};
  404. ///
  405. /// let url = Url::parse("blob:https://example.com/foo").unwrap();
  406. /// assert_eq!(url.origin(),
  407. /// Origin::Tuple("https".into(),
  408. /// Host::Domain("example.com".into()),
  409. /// 443));
  410. /// ```
  411. ///
  412. /// URL with `file` scheme:
  413. ///
  414. /// ```rust
  415. /// use url::{Host, Origin, Url};
  416. ///
  417. /// let url = Url::parse("file:///tmp/foo").unwrap();
  418. /// assert!(!url.origin().is_tuple());
  419. ///
  420. /// let other_url = Url::parse("file:///tmp/foo").unwrap();
  421. /// assert!(url.origin() != other_url.origin());
  422. /// ```
  423. ///
  424. /// URL with other scheme:
  425. ///
  426. /// ```rust
  427. /// use url::{Host, Origin, Url};
  428. ///
  429. /// let url = Url::parse("foo:bar").unwrap();
  430. /// assert!(!url.origin().is_tuple());
  431. /// ```
  432. #[inline]
  433. pub fn origin(&self) -> Origin {
  434. origin::url_origin(self)
  435. }
  436. /// Return the scheme of this URL, lower-cased, as an ASCII string without the ':' delimiter.
  437. ///
  438. /// # Examples
  439. ///
  440. /// ```
  441. /// use url::Url;
  442. ///
  443. /// let url = Url::parse("file:///tmp/foo").unwrap();
  444. /// assert_eq!(url.scheme(), "file");
  445. /// ```
  446. #[inline]
  447. pub fn scheme(&self) -> &str {
  448. self.slice(..self.scheme_end)
  449. }
  450. /// Return whether the URL has an 'authority',
  451. /// which can contain a username, password, host, and port number.
  452. ///
  453. /// URLs that do *not* are either path-only like `unix:/run/foo.socket`
  454. /// or cannot-be-a-base like `data:text/plain,Stuff`.
  455. ///
  456. /// # Examples
  457. ///
  458. /// ```
  459. /// use url::Url;
  460. ///
  461. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  462. /// assert!(url.has_authority());
  463. ///
  464. /// let url = Url::parse("unix:/run/foo.socket").unwrap();
  465. /// assert!(!url.has_authority());
  466. ///
  467. /// let url = Url::parse("data:text/plain,Stuff").unwrap();
  468. /// assert!(!url.has_authority());
  469. /// ```
  470. #[inline]
  471. pub fn has_authority(&self) -> bool {
  472. debug_assert!(self.byte_at(self.scheme_end) == b':');
  473. self.slice(self.scheme_end..).starts_with("://")
  474. }
  475. /// Return whether this URL is a cannot-be-a-base URL,
  476. /// meaning that parsing a relative URL string with this URL as the base will return an error.
  477. ///
  478. /// This is the case if the scheme and `:` delimiter are not followed by a `/` slash,
  479. /// as is typically the case of `data:` and `mailto:` URLs.
  480. ///
  481. /// # Examples
  482. ///
  483. /// ```
  484. /// use url::Url;
  485. ///
  486. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  487. /// assert!(!url.cannot_be_a_base());
  488. ///
  489. /// let url = Url::parse("unix:/run/foo.socket").unwrap();
  490. /// assert!(!url.cannot_be_a_base());
  491. ///
  492. /// let url = Url::parse("data:text/plain,Stuff").unwrap();
  493. /// assert!(url.cannot_be_a_base());
  494. /// ```
  495. #[inline]
  496. pub fn cannot_be_a_base(&self) -> bool {
  497. !self.slice(self.path_start..).starts_with('/')
  498. }
  499. /// Return the username for this URL (typically the empty string)
  500. /// as a percent-encoded ASCII string.
  501. ///
  502. /// # Examples
  503. ///
  504. /// ```
  505. /// use url::Url;
  506. ///
  507. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  508. /// assert_eq!(url.username(), "rms");
  509. ///
  510. /// let url = Url::parse("ftp://:secret123@example.com").unwrap();
  511. /// assert_eq!(url.username(), "");
  512. ///
  513. /// let url = Url::parse("https://example.com").unwrap();
  514. /// assert_eq!(url.username(), "");
  515. /// ```
  516. pub fn username(&self) -> &str {
  517. if self.has_authority() {
  518. self.slice(self.scheme_end + ("://".len() as u32)..self.username_end)
  519. } else {
  520. ""
  521. }
  522. }
  523. /// Return the password for this URL, if any, as a percent-encoded ASCII string.
  524. ///
  525. /// # Examples
  526. ///
  527. /// ```
  528. /// use url::Url;
  529. ///
  530. /// let url = Url::parse("ftp://rms:secret123@example.com").unwrap();
  531. /// assert_eq!(url.password(), Some("secret123"));
  532. ///
  533. /// let url = Url::parse("ftp://:secret123@example.com").unwrap();
  534. /// assert_eq!(url.password(), Some("secret123"));
  535. ///
  536. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  537. /// assert_eq!(url.password(), None);
  538. ///
  539. /// let url = Url::parse("https://example.com").unwrap();
  540. /// assert_eq!(url.password(), None);
  541. /// ```
  542. pub fn password(&self) -> Option<&str> {
  543. // This ':' is not the one marking a port number since a host can not be empty.
  544. // (Except for file: URLs, which do not have port numbers.)
  545. if self.has_authority() && self.byte_at(self.username_end) == b':' {
  546. debug_assert!(self.byte_at(self.host_start - 1) == b'@');
  547. Some(self.slice(self.username_end + 1..self.host_start - 1))
  548. } else {
  549. None
  550. }
  551. }
  552. /// Equivalent to `url.host().is_some()`.
  553. ///
  554. /// # Examples
  555. ///
  556. /// ```
  557. /// use url::Url;
  558. ///
  559. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  560. /// assert!(url.has_host());
  561. ///
  562. /// let url = Url::parse("unix:/run/foo.socket").unwrap();
  563. /// assert!(!url.has_host());
  564. ///
  565. /// let url = Url::parse("data:text/plain,Stuff").unwrap();
  566. /// assert!(!url.has_host());
  567. /// ```
  568. pub fn has_host(&self) -> bool {
  569. !matches!(self.host, HostInternal::None)
  570. }
  571. /// Return the string representation of the host (domain or IP address) for this URL, if any.
  572. ///
  573. /// Non-ASCII domains are punycode-encoded per IDNA.
  574. /// IPv6 addresses are given between `[` and `]` brackets.
  575. ///
  576. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  577. /// don’t have a host.
  578. ///
  579. /// See also the `host` method.
  580. ///
  581. /// # Examples
  582. ///
  583. /// ```
  584. /// use url::Url;
  585. ///
  586. /// let url = Url::parse("https://127.0.0.1/index.html").unwrap();
  587. /// assert_eq!(url.host_str(), Some("127.0.0.1"));
  588. ///
  589. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  590. /// assert_eq!(url.host_str(), Some("example.com"));
  591. ///
  592. /// let url = Url::parse("unix:/run/foo.socket").unwrap();
  593. /// assert_eq!(url.host_str(), None);
  594. ///
  595. /// let url = Url::parse("data:text/plain,Stuff").unwrap();
  596. /// assert_eq!(url.host_str(), None);
  597. /// ```
  598. pub fn host_str(&self) -> Option<&str> {
  599. if self.has_host() {
  600. Some(self.slice(self.host_start..self.host_end))
  601. } else {
  602. None
  603. }
  604. }
  605. /// Return the parsed representation of the host for this URL.
  606. /// Non-ASCII domain labels are punycode-encoded per IDNA.
  607. ///
  608. /// Cannot-be-a-base URLs (typical of `data:` and `mailto:`) and some `file:` URLs
  609. /// don’t have a host.
  610. ///
  611. /// See also the `host_str` method.
  612. ///
  613. /// # Examples
  614. ///
  615. /// ```
  616. /// use url::Url;
  617. ///
  618. /// let url = Url::parse("https://127.0.0.1/index.html").unwrap();
  619. /// assert!(url.host().is_some());
  620. ///
  621. /// let url = Url::parse("ftp://rms@example.com").unwrap();
  622. /// assert!(url.host().is_some());
  623. ///
  624. /// let url = Url::parse("unix:/run/foo.socket").unwrap();
  625. /// assert!(url.host().is_none());
  626. ///
  627. /// let url = Url::parse("data:text/plain,Stuff").unwrap();
  628. /// assert!(url.host().is_none());
  629. /// ```
  630. pub fn host(&self) -> Option<Host<&str>> {
  631. match self.host {
  632. HostInternal::None => None,
  633. HostInternal::Domain => Some(Host::Domain(self.slice(self.host_start..self.host_end))),
  634. HostInternal::Ipv4(address) => Some(Host::Ipv4(address)),
  635. HostInternal::Ipv6(address) => Some(Host::Ipv6(address)),
  636. }
  637. }
  638. /// If this URL has a host and it is a domain name (not an IP address), return it.
  639. ///
  640. /// # Examples
  641. ///
  642. /// ```
  643. /// use url::Url;
  644. ///
  645. /// let url = Url::parse("https://127.0.0.1/").unwrap();
  646. /// assert_eq!(url.domain(), None);
  647. ///
  648. /// let url = Url::parse("mailto:rms@example.net").unwrap();
  649. /// assert_eq!(url.domain(), None);
  650. ///
  651. /// let url = Url::parse("https://example.com/").unwrap();
  652. /// assert_eq!(url.domain(), Some("example.com"));
  653. /// ```
  654. pub fn domain(&self) -> Option<&str> {
  655. match self.host {
  656. HostInternal::Domain => Some(self.slice(self.host_start..self.host_end)),
  657. _ => None,
  658. }
  659. }
  660. /// Return the port number for this URL, if any.
  661. ///
  662. /// # Examples
  663. ///
  664. /// ```
  665. /// use url::Url;
  666. ///
  667. /// let url = Url::parse("https://example.com").unwrap();
  668. /// assert_eq!(url.port(), None);
  669. ///
  670. /// let url = Url::parse("ssh://example.com:22").unwrap();
  671. /// assert_eq!(url.port(), Some(22));
  672. /// ```
  673. #[inline]
  674. pub fn port(&self) -> Option<u16> {
  675. self.port
  676. }
  677. /// Return the port number for this URL, or the default port number if it is known.
  678. ///
  679. /// This method only knows the default port number
  680. /// of the `http`, `https`, `ws`, `wss`, `ftp`, and `gopher` schemes.
  681. ///
  682. /// For URLs in these schemes, this method always returns `Some(_)`.
  683. /// For other schemes, it is the same as `Url::port()`.
  684. ///
  685. /// # Examples
  686. ///
  687. /// ```
  688. /// use url::Url;
  689. ///
  690. /// let url = Url::parse("foo://example.com").unwrap();
  691. /// assert_eq!(url.port_or_known_default(), None);
  692. ///
  693. /// let url = Url::parse("foo://example.com:1456").unwrap();
  694. /// assert_eq!(url.port_or_known_default(), Some(1456));
  695. ///
  696. /// let url = Url::parse("https://example.com").unwrap();
  697. /// assert_eq!(url.port_or_known_default(), Some(443));
  698. /// ```
  699. #[inline]
  700. pub fn port_or_known_default(&self) -> Option<u16> {
  701. self.port.or_else(|| parser::default_port(self.scheme()))
  702. }
  703. /// If the URL has a host, return something that implements `ToSocketAddrs`.
  704. ///
  705. /// If the URL has no port number and the scheme’s default port number is not known
  706. /// (see `Url::port_or_known_default`),
  707. /// the closure is called to obtain a port number.
  708. /// Typically, this closure can match on the result `Url::scheme`
  709. /// to have per-scheme default port numbers,
  710. /// and panic for schemes it’s not prepared to handle.
  711. /// For example:
  712. ///
  713. /// ```rust
  714. /// # use url::Url;
  715. /// # use std::net::TcpStream;
  716. /// # use std::io;
  717. ///
  718. /// fn connect(url: &Url) -> io::Result<TcpStream> {
  719. /// TcpStream::connect(url.with_default_port(default_port)?)
  720. /// }
  721. ///
  722. /// fn default_port(url: &Url) -> Result<u16, ()> {
  723. /// match url.scheme() {
  724. /// "git" => Ok(9418),
  725. /// "git+ssh" => Ok(22),
  726. /// "git+https" => Ok(443),
  727. /// "git+http" => Ok(80),
  728. /// _ => Err(()),
  729. /// }
  730. /// }
  731. /// ```
  732. pub fn with_default_port<F>(&self, f: F) -> io::Result<HostAndPort<&str>>
  733. where F: FnOnce(&Url) -> Result<u16, ()> {
  734. Ok(HostAndPort {
  735. host: self.host()
  736. .ok_or(())
  737. .or_else(|()| io_error("URL has no host"))?,
  738. port: self.port_or_known_default()
  739. .ok_or(())
  740. .or_else(|()| f(self))
  741. .or_else(|()| io_error("URL has no port number"))?
  742. })
  743. }
  744. /// Return the path for this URL, as a percent-encoded ASCII string.
  745. /// For cannot-be-a-base URLs, this is an arbitrary string that doesn’t start with '/'.
  746. /// For other URLs, this starts with a '/' slash
  747. /// and continues with slash-separated path segments.
  748. pub fn path(&self) -> &str {
  749. match (self.query_start, self.fragment_start) {
  750. (None, None) => self.slice(self.path_start..),
  751. (Some(next_component_start), _) |
  752. (None, Some(next_component_start)) => {
  753. self.slice(self.path_start..next_component_start)
  754. }
  755. }
  756. }
  757. /// Unless this URL is cannot-be-a-base,
  758. /// return an iterator of '/' slash-separated path segments,
  759. /// each as a percent-encoded ASCII string.
  760. ///
  761. /// Return `None` for cannot-be-a-base URLs.
  762. ///
  763. /// When `Some` is returned, the iterator always contains at least one string
  764. /// (which may be empty).
  765. ///
  766. /// # Examples
  767. ///
  768. /// ```
  769. /// use url::Url;
  770. ///
  771. /// let url = Url::parse("https://example.com/foo/bar").unwrap();
  772. /// let mut path_segments = url.path_segments().unwrap();
  773. /// assert_eq!(path_segments.next(), Some("foo"));
  774. /// assert_eq!(path_segments.next(), Some("bar"));
  775. /// assert_eq!(path_segments.next(), None);
  776. ///
  777. /// let url = Url::parse("https://example.com").unwrap();
  778. /// let mut path_segments = url.path_segments().unwrap();
  779. /// assert_eq!(path_segments.next(), Some(""));
  780. /// assert_eq!(path_segments.next(), None);
  781. ///
  782. /// let url = Url::parse("data:text/plain,HelloWorld").unwrap();
  783. /// assert!(url.path_segments().is_none());
  784. /// ```
  785. pub fn path_segments(&self) -> Option<str::Split<char>> {
  786. let path = self.path();
  787. if path.starts_with('/') {
  788. Some(path[1..].split('/'))
  789. } else {
  790. None
  791. }
  792. }
  793. /// Return this URL’s query string, if any, as a percent-encoded ASCII string.
  794. pub fn query(&self) -> Option<&str> {
  795. match (self.query_start, self.fragment_start) {
  796. (None, _) => None,
  797. (Some(query_start), None) => {
  798. debug_assert!(self.byte_at(query_start) == b'?');
  799. Some(self.slice(query_start + 1..))
  800. }
  801. (Some(query_start), Some(fragment_start)) => {
  802. debug_assert!(self.byte_at(query_start) == b'?');
  803. Some(self.slice(query_start + 1..fragment_start))
  804. }
  805. }
  806. }
  807. /// Parse the URL’s query string, if any, as `application/x-www-form-urlencoded`
  808. /// and return an iterator of (key, value) pairs.
  809. #[inline]
  810. pub fn query_pairs(&self) -> form_urlencoded::Parse {
  811. form_urlencoded::parse(self.query().unwrap_or("").as_bytes())
  812. }
  813. /// Return this URL’s fragment identifier, if any.
  814. ///
  815. /// **Note:** the parser did *not* percent-encode this component,
  816. /// but the input may have been percent-encoded already.
  817. pub fn fragment(&self) -> Option<&str> {
  818. self.fragment_start.map(|start| {
  819. debug_assert!(self.byte_at(start) == b'#');
  820. self.slice(start + 1..)
  821. })
  822. }
  823. fn mutate<F: FnOnce(&mut Parser) -> R, R>(&mut self, f: F) -> R {
  824. let mut parser = Parser::for_setter(mem::replace(&mut self.serialization, String::new()));
  825. let result = f(&mut parser);
  826. self.serialization = parser.serialization;
  827. result
  828. }
  829. /// Change this URL’s fragment identifier.
  830. pub fn set_fragment(&mut self, fragment: Option<&str>) {
  831. // Remove any previous fragment
  832. if let Some(start) = self.fragment_start {
  833. debug_assert!(self.byte_at(start) == b'#');
  834. self.serialization.truncate(start as usize);
  835. }
  836. // Write the new one
  837. if let Some(input) = fragment {
  838. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  839. self.serialization.push('#');
  840. self.mutate(|parser| parser.parse_fragment(parser::Input::new(input)))
  841. } else {
  842. self.fragment_start = None
  843. }
  844. }
  845. fn take_fragment(&mut self) -> Option<String> {
  846. self.fragment_start.take().map(|start| {
  847. debug_assert!(self.byte_at(start) == b'#');
  848. let fragment = self.slice(start + 1..).to_owned();
  849. self.serialization.truncate(start as usize);
  850. fragment
  851. })
  852. }
  853. fn restore_already_parsed_fragment(&mut self, fragment: Option<String>) {
  854. if let Some(ref fragment) = fragment {
  855. assert!(self.fragment_start.is_none());
  856. self.fragment_start = Some(to_u32(self.serialization.len()).unwrap());
  857. self.serialization.push('#');
  858. self.serialization.push_str(fragment);
  859. }
  860. }
  861. /// Change this URL’s query string.
  862. pub fn set_query(&mut self, query: Option<&str>) {
  863. let fragment = self.take_fragment();
  864. // Remove any previous query
  865. if let Some(start) = self.query_start.take() {
  866. debug_assert!(self.byte_at(start) == b'?');
  867. self.serialization.truncate(start as usize);
  868. }
  869. // Write the new query, if any
  870. if let Some(input) = query {
  871. self.query_start = Some(to_u32(self.serialization.len()).unwrap());
  872. self.serialization.push('?');
  873. let scheme_end = self.scheme_end;
  874. self.mutate(|parser| parser.parse_query(scheme_end, parser::Input::new(input)));
  875. }
  876. self.restore_already_parsed_fragment(fragment);
  877. }
  878. /// Manipulate this URL’s query string, viewed as a sequence of name/value pairs
  879. /// in `application/x-www-form-urlencoded` syntax.
  880. ///
  881. /// The return value has a method-chaining API:
  882. ///
  883. /// ```rust
  884. /// # use url::Url;
  885. /// let mut url = Url::parse("https://example.net?lang=fr#nav").unwrap();
  886. /// assert_eq!(url.query(), Some("lang=fr"));
  887. ///
  888. /// url.query_pairs_mut().append_pair("foo", "bar");
  889. /// assert_eq!(url.query(), Some("lang=fr&foo=bar"));
  890. /// assert_eq!(url.as_str(), "https://example.net/?lang=fr&foo=bar#nav");
  891. ///
  892. /// url.query_pairs_mut()
  893. /// .clear()
  894. /// .append_pair("foo", "bar & baz")
  895. /// .append_pair("saisons", "\u{00C9}t\u{00E9}+hiver");
  896. /// assert_eq!(url.query(), Some("foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver"));
  897. /// assert_eq!(url.as_str(),
  898. /// "https://example.net/?foo=bar+%26+baz&saisons=%C3%89t%C3%A9%2Bhiver#nav");
  899. /// ```
  900. ///
  901. /// Note: `url.query_pairs_mut().clear();` is equivalent to `url.set_query(Some(""))`,
  902. /// not `url.set_query(None)`.
  903. ///
  904. /// The state of `Url` is unspecified if this return value is leaked without being dropped.
  905. pub fn query_pairs_mut(&mut self) -> form_urlencoded::Serializer<UrlQuery> {
  906. let fragment = self.take_fragment();
  907. let query_start;
  908. if let Some(start) = self.query_start {
  909. debug_assert!(self.byte_at(start) == b'?');
  910. query_start = start as usize;
  911. } else {
  912. query_start = self.serialization.len();
  913. self.query_start = Some(to_u32(query_start).unwrap());
  914. self.serialization.push('?');
  915. }
  916. let query = UrlQuery { url: self, fragment: fragment };
  917. form_urlencoded::Serializer::for_suffix(query, query_start + "?".len())
  918. }
  919. fn take_after_path(&mut self) -> String {
  920. match (self.query_start, self.fragment_start) {
  921. (Some(i), _) | (None, Some(i)) => {
  922. let after_path = self.slice(i..).to_owned();
  923. self.serialization.truncate(i as usize);
  924. after_path
  925. },
  926. (None, None) => String::new(),
  927. }
  928. }
  929. /// Change this URL’s path.
  930. pub fn set_path(&mut self, mut path: &str) {
  931. let after_path = self.take_after_path();
  932. let old_after_path_pos = to_u32(self.serialization.len()).unwrap();
  933. let cannot_be_a_base = self.cannot_be_a_base();
  934. let scheme_type = SchemeType::from(self.scheme());
  935. self.serialization.truncate(self.path_start as usize);
  936. self.mutate(|parser| {
  937. if cannot_be_a_base {
  938. if path.starts_with('/') {
  939. parser.serialization.push_str("%2F");
  940. path = &path[1..];
  941. }
  942. parser.parse_cannot_be_a_base_path(parser::Input::new(path));
  943. } else {
  944. let mut has_host = true; // FIXME
  945. parser.parse_path_start(scheme_type, &mut has_host, parser::Input::new(path));
  946. }
  947. });
  948. self.restore_after_path(old_after_path_pos, &after_path);
  949. }
  950. /// Return an object with methods to manipulate this URL’s path segments.
  951. ///
  952. /// Return `Err(())` if this URL is cannot-be-a-base.
  953. pub fn path_segments_mut(&mut self) -> Result<PathSegmentsMut, ()> {
  954. if self.cannot_be_a_base() {
  955. Err(())
  956. } else {
  957. Ok(path_segments::new(self))
  958. }
  959. }
  960. fn restore_after_path(&mut self, old_after_path_position: u32, after_path: &str) {
  961. let new_after_path_position = to_u32(self.serialization.len()).unwrap();
  962. let adjust = |index: &mut u32| {
  963. *index -= old_after_path_position;
  964. *index += new_after_path_position;
  965. };
  966. if let Some(ref mut index) = self.query_start { adjust(index) }
  967. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  968. self.serialization.push_str(after_path)
  969. }
  970. /// Change this URL’s port number.
  971. ///
  972. /// If this URL is cannot-be-a-base, does not have a host, or has the `file` scheme;
  973. /// do nothing and return `Err`.
  974. ///
  975. /// # Examples
  976. ///
  977. /// ```
  978. /// use url::Url;
  979. ///
  980. /// let mut url = Url::parse("ssh://example.net:2048/").unwrap();
  981. ///
  982. /// url.set_port(Some(4096)).unwrap();
  983. /// assert_eq!(url.as_str(), "ssh://example.net:4096/");
  984. ///
  985. /// url.set_port(None).unwrap();
  986. /// assert_eq!(url.as_str(), "ssh://example.net/");
  987. /// ```
  988. ///
  989. /// Cannot set port for cannot-be-a-base URLs:
  990. ///
  991. /// ```
  992. /// use url::Url;
  993. ///
  994. /// let mut url = Url::parse("mailto:rms@example.net").unwrap();
  995. ///
  996. /// let result = url.set_port(Some(80));
  997. /// assert!(result.is_err());
  998. ///
  999. /// let result = url.set_port(None);
  1000. /// assert!(result.is_err());
  1001. /// ```
  1002. pub fn set_port(&mut self, mut port: Option<u16>) -> Result<(), ()> {
  1003. if !self.has_host() || self.scheme() == "file" {
  1004. return Err(())
  1005. }
  1006. if port.is_some() && port == parser::default_port(self.scheme()) {
  1007. port = None
  1008. }
  1009. self.set_port_internal(port);
  1010. Ok(())
  1011. }
  1012. fn set_port_internal(&mut self, port: Option<u16>) {
  1013. match (self.port, port) {
  1014. (None, None) => {}
  1015. (Some(_), None) => {
  1016. self.serialization.drain(self.host_end as usize .. self.path_start as usize);
  1017. let offset = self.path_start - self.host_end;
  1018. self.path_start = self.host_end;
  1019. if let Some(ref mut index) = self.query_start { *index -= offset }
  1020. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  1021. }
  1022. (Some(old), Some(new)) if old == new => {}
  1023. (_, Some(new)) => {
  1024. let path_and_after = self.slice(self.path_start..).to_owned();
  1025. self.serialization.truncate(self.host_end as usize);
  1026. write!(&mut self.serialization, ":{}", new).unwrap();
  1027. let old_path_start = self.path_start;
  1028. let new_path_start = to_u32(self.serialization.len()).unwrap();
  1029. self.path_start = new_path_start;
  1030. let adjust = |index: &mut u32| {
  1031. *index -= old_path_start;
  1032. *index += new_path_start;
  1033. };
  1034. if let Some(ref mut index) = self.query_start { adjust(index) }
  1035. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1036. self.serialization.push_str(&path_and_after);
  1037. }
  1038. }
  1039. self.port = port;
  1040. }
  1041. /// Change this URL’s host.
  1042. ///
  1043. /// If this URL is cannot-be-a-base or there is an error parsing the given `host`,
  1044. /// do nothing and return `Err`.
  1045. ///
  1046. /// Removing the host (calling this with `None`)
  1047. /// will also remove any username, password, and port number.
  1048. ///
  1049. /// # Examples
  1050. ///
  1051. /// Change host:
  1052. ///
  1053. /// ```
  1054. /// use url::Url;
  1055. ///
  1056. /// let mut url = Url::parse("https://example.net").unwrap();
  1057. /// let result = url.set_host(Some("rust-lang.org"));
  1058. /// assert!(result.is_ok());
  1059. /// assert_eq!(url.as_str(), "https://rust-lang.org/");
  1060. /// ```
  1061. ///
  1062. /// Remove host:
  1063. ///
  1064. /// ```
  1065. /// use url::Url;
  1066. ///
  1067. /// let mut url = Url::parse("foo://example.net").unwrap();
  1068. /// let result = url.set_host(None);
  1069. /// assert!(result.is_ok());
  1070. /// assert_eq!(url.as_str(), "foo:/");
  1071. /// ```
  1072. ///
  1073. /// Cannot remove host for 'special' schemes (e.g. `http`):
  1074. ///
  1075. /// ```
  1076. /// use url::Url;
  1077. ///
  1078. /// let mut url = Url::parse("https://example.net").unwrap();
  1079. /// let result = url.set_host(None);
  1080. /// assert!(result.is_err());
  1081. /// assert_eq!(url.as_str(), "https://example.net/");
  1082. /// ```
  1083. ///
  1084. /// Cannot change or remove host for cannot-be-a-base URLs:
  1085. ///
  1086. /// ```
  1087. /// use url::Url;
  1088. ///
  1089. /// let mut url = Url::parse("mailto:rms@example.net").unwrap();
  1090. ///
  1091. /// let result = url.set_host(Some("rust-lang.org"));
  1092. /// assert!(result.is_err());
  1093. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1094. ///
  1095. /// let result = url.set_host(None);
  1096. /// assert!(result.is_err());
  1097. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1098. /// ```
  1099. pub fn set_host(&mut self, host: Option<&str>) -> Result<(), ParseError> {
  1100. if self.cannot_be_a_base() {
  1101. return Err(ParseError::SetHostOnCannotBeABaseUrl)
  1102. }
  1103. if let Some(host) = host {
  1104. if host == "" && SchemeType::from(self.scheme()).is_special() {
  1105. return Err(ParseError::EmptyHost);
  1106. }
  1107. self.set_host_internal(Host::parse(host)?, None)
  1108. } else if self.has_host() {
  1109. if SchemeType::from(self.scheme()).is_special() {
  1110. return Err(ParseError::EmptyHost)
  1111. }
  1112. debug_assert!(self.byte_at(self.scheme_end) == b':');
  1113. debug_assert!(self.byte_at(self.path_start) == b'/');
  1114. let new_path_start = self.scheme_end + 1;
  1115. self.serialization.drain(new_path_start as usize..self.path_start as usize);
  1116. let offset = self.path_start - new_path_start;
  1117. self.path_start = new_path_start;
  1118. self.username_end = new_path_start;
  1119. self.host_start = new_path_start;
  1120. self.host_end = new_path_start;
  1121. self.port = None;
  1122. if let Some(ref mut index) = self.query_start { *index -= offset }
  1123. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  1124. }
  1125. Ok(())
  1126. }
  1127. /// opt_new_port: None means leave unchanged, Some(None) means remove any port number.
  1128. fn set_host_internal(&mut self, host: Host<String>, opt_new_port: Option<Option<u16>>) {
  1129. let old_suffix_pos = if opt_new_port.is_some() { self.path_start } else { self.host_end };
  1130. let suffix = self.slice(old_suffix_pos..).to_owned();
  1131. self.serialization.truncate(self.host_start as usize);
  1132. if !self.has_authority() {
  1133. debug_assert!(self.slice(self.scheme_end..self.host_start) == ":");
  1134. debug_assert!(self.username_end == self.host_start);
  1135. self.serialization.push('/');
  1136. self.serialization.push('/');
  1137. self.username_end += 2;
  1138. self.host_start += 2;
  1139. }
  1140. write!(&mut self.serialization, "{}", host).unwrap();
  1141. self.host_end = to_u32(self.serialization.len()).unwrap();
  1142. self.host = host.into();
  1143. if let Some(new_port) = opt_new_port {
  1144. self.port = new_port;
  1145. if let Some(port) = new_port {
  1146. write!(&mut self.serialization, ":{}", port).unwrap();
  1147. }
  1148. }
  1149. let new_suffix_pos = to_u32(self.serialization.len()).unwrap();
  1150. self.serialization.push_str(&suffix);
  1151. let adjust = |index: &mut u32| {
  1152. *index -= old_suffix_pos;
  1153. *index += new_suffix_pos;
  1154. };
  1155. adjust(&mut self.path_start);
  1156. if let Some(ref mut index) = self.query_start { adjust(index) }
  1157. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1158. }
  1159. /// Change this URL’s host to the given IP address.
  1160. ///
  1161. /// If this URL is cannot-be-a-base, do nothing and return `Err`.
  1162. ///
  1163. /// Compared to `Url::set_host`, this skips the host parser.
  1164. pub fn set_ip_host(&mut self, address: IpAddr) -> Result<(), ()> {
  1165. if self.cannot_be_a_base() {
  1166. return Err(())
  1167. }
  1168. let address = match address {
  1169. IpAddr::V4(address) => Host::Ipv4(address),
  1170. IpAddr::V6(address) => Host::Ipv6(address),
  1171. };
  1172. self.set_host_internal(address, None);
  1173. Ok(())
  1174. }
  1175. /// Change this URL’s password.
  1176. ///
  1177. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1178. pub fn set_password(&mut self, password: Option<&str>) -> Result<(), ()> {
  1179. if !self.has_host() {
  1180. return Err(())
  1181. }
  1182. if let Some(password) = password {
  1183. let host_and_after = self.slice(self.host_start..).to_owned();
  1184. self.serialization.truncate(self.username_end as usize);
  1185. self.serialization.push(':');
  1186. self.serialization.extend(utf8_percent_encode(password, USERINFO_ENCODE_SET));
  1187. self.serialization.push('@');
  1188. let old_host_start = self.host_start;
  1189. let new_host_start = to_u32(self.serialization.len()).unwrap();
  1190. let adjust = |index: &mut u32| {
  1191. *index -= old_host_start;
  1192. *index += new_host_start;
  1193. };
  1194. self.host_start = new_host_start;
  1195. adjust(&mut self.host_end);
  1196. adjust(&mut self.path_start);
  1197. if let Some(ref mut index) = self.query_start { adjust(index) }
  1198. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1199. self.serialization.push_str(&host_and_after);
  1200. } else if self.byte_at(self.username_end) == b':' { // If there is a password to remove
  1201. let has_username_or_password = self.byte_at(self.host_start - 1) == b'@';
  1202. debug_assert!(has_username_or_password);
  1203. let username_start = self.scheme_end + 3;
  1204. let empty_username = username_start == self.username_end;
  1205. let start = self.username_end; // Remove the ':'
  1206. let end = if empty_username {
  1207. self.host_start // Remove the '@' as well
  1208. } else {
  1209. self.host_start - 1 // Keep the '@' to separate the username from the host
  1210. };
  1211. self.serialization.drain(start as usize .. end as usize);
  1212. let offset = end - start;
  1213. self.host_start -= offset;
  1214. self.host_end -= offset;
  1215. self.path_start -= offset;
  1216. if let Some(ref mut index) = self.query_start { *index -= offset }
  1217. if let Some(ref mut index) = self.fragment_start { *index -= offset }
  1218. }
  1219. Ok(())
  1220. }
  1221. /// Change this URL’s username.
  1222. ///
  1223. /// If this URL is cannot-be-a-base or does not have a host, do nothing and return `Err`.
  1224. pub fn set_username(&mut self, username: &str) -> Result<(), ()> {
  1225. if !self.has_host() {
  1226. return Err(())
  1227. }
  1228. let username_start = self.scheme_end + 3;
  1229. debug_assert!(self.slice(self.scheme_end..username_start) == "://");
  1230. if self.slice(username_start..self.username_end) == username {
  1231. return Ok(())
  1232. }
  1233. let after_username = self.slice(self.username_end..).to_owned();
  1234. self.serialization.truncate(username_start as usize);
  1235. self.serialization.extend(utf8_percent_encode(username, USERINFO_ENCODE_SET));
  1236. let mut removed_bytes = self.username_end;
  1237. self.username_end = to_u32(self.serialization.len()).unwrap();
  1238. let mut added_bytes = self.username_end;
  1239. let new_username_is_empty = self.username_end == username_start;
  1240. match (new_username_is_empty, after_username.chars().next()) {
  1241. (true, Some('@')) => {
  1242. removed_bytes += 1;
  1243. self.serialization.push_str(&after_username[1..]);
  1244. }
  1245. (false, Some('@')) | (_, Some(':')) | (true, _) => {
  1246. self.serialization.push_str(&after_username);
  1247. }
  1248. (false, _) => {
  1249. added_bytes += 1;
  1250. self.serialization.push('@');
  1251. self.serialization.push_str(&after_username);
  1252. }
  1253. }
  1254. let adjust = |index: &mut u32| {
  1255. *index -= removed_bytes;
  1256. *index += added_bytes;
  1257. };
  1258. adjust(&mut self.host_start);
  1259. adjust(&mut self.host_end);
  1260. adjust(&mut self.path_start);
  1261. if let Some(ref mut index) = self.query_start { adjust(index) }
  1262. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1263. Ok(())
  1264. }
  1265. /// Change this URL’s scheme.
  1266. ///
  1267. /// Do nothing and return `Err` if:
  1268. /// * The new scheme is not in `[a-zA-Z][a-zA-Z0-9+.-]+`
  1269. /// * This URL is cannot-be-a-base and the new scheme is one of
  1270. /// `http`, `https`, `ws`, `wss`, `ftp`, or `gopher`
  1271. ///
  1272. /// # Examples
  1273. ///
  1274. /// Change the URL’s scheme from `https` to `foo`:
  1275. ///
  1276. /// ```
  1277. /// use url::Url;
  1278. ///
  1279. /// let mut url = Url::parse("https://example.net").unwrap();
  1280. /// let result = url.set_scheme("foo");
  1281. /// assert_eq!(url.as_str(), "foo://example.net/");
  1282. /// assert!(result.is_ok());
  1283. /// ```
  1284. ///
  1285. ///
  1286. /// Cannot change URL’s scheme from `https` to `foõ`:
  1287. ///
  1288. /// ```
  1289. /// use url::Url;
  1290. ///
  1291. /// let mut url = Url::parse("https://example.net").unwrap();
  1292. /// let result = url.set_scheme("foõ");
  1293. /// assert_eq!(url.as_str(), "https://example.net/");
  1294. /// assert!(result.is_err());
  1295. /// ```
  1296. ///
  1297. /// Cannot change URL’s scheme from `mailto` (cannot-be-a-base) to `https`:
  1298. ///
  1299. /// ```
  1300. /// use url::Url;
  1301. ///
  1302. /// let mut url = Url::parse("mailto:rms@example.net").unwrap();
  1303. /// let result = url.set_scheme("https");
  1304. /// assert_eq!(url.as_str(), "mailto:rms@example.net");
  1305. /// assert!(result.is_err());
  1306. /// ```
  1307. pub fn set_scheme(&mut self, scheme: &str) -> Result<(), ()> {
  1308. let mut parser = Parser::for_setter(String::new());
  1309. let remaining = parser.parse_scheme(parser::Input::new(scheme))?;
  1310. if !remaining.is_empty() ||
  1311. (!self.has_host() && SchemeType::from(&parser.serialization).is_special()) {
  1312. return Err(())
  1313. }
  1314. let old_scheme_end = self.scheme_end;
  1315. let new_scheme_end = to_u32(parser.serialization.len()).unwrap();
  1316. let adjust = |index: &mut u32| {
  1317. *index -= old_scheme_end;
  1318. *index += new_scheme_end;
  1319. };
  1320. self.scheme_end = new_scheme_end;
  1321. adjust(&mut self.username_end);
  1322. adjust(&mut self.host_start);
  1323. adjust(&mut self.host_end);
  1324. adjust(&mut self.path_start);
  1325. if let Some(ref mut index) = self.query_start { adjust(index) }
  1326. if let Some(ref mut index) = self.fragment_start { adjust(index) }
  1327. parser.serialization.push_str(self.slice(old_scheme_end..));
  1328. self.serialization = parser.serialization;
  1329. Ok(())
  1330. }
  1331. /// Convert a file name as `std::path::Path` into an URL in the `file` scheme.
  1332. ///
  1333. /// This returns `Err` if the given path is not absolute or,
  1334. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`).
  1335. ///
  1336. /// # Examples
  1337. ///
  1338. /// On Unix-like platforms:
  1339. ///
  1340. /// ```
  1341. /// # if cfg!(unix) {
  1342. /// use url::Url;
  1343. ///
  1344. /// let url = Url::from_file_path("/tmp/foo.txt").unwrap();
  1345. /// assert_eq!(url.as_str(), "file:///tmp/foo.txt");
  1346. ///
  1347. /// let url = Url::from_file_path("../foo.txt");
  1348. /// assert!(url.is_err());
  1349. ///
  1350. /// let url = Url::from_file_path("https://google.com/");
  1351. /// assert!(url.is_err());
  1352. /// # }
  1353. /// ```
  1354. pub fn from_file_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  1355. let mut serialization = "file://".to_owned();
  1356. let path_start = serialization.len() as u32;
  1357. path_to_file_url_segments(path.as_ref(), &mut serialization)?;
  1358. Ok(Url {
  1359. serialization: serialization,
  1360. scheme_end: "file".len() as u32,
  1361. username_end: path_start,
  1362. host_start: path_start,
  1363. host_end: path_start,
  1364. host: HostInternal::None,
  1365. port: None,
  1366. path_start: path_start,
  1367. query_start: None,
  1368. fragment_start: None,
  1369. })
  1370. }
  1371. /// Convert a directory name as `std::path::Path` into an URL in the `file` scheme.
  1372. ///
  1373. /// This returns `Err` if the given path is not absolute or,
  1374. /// on Windows, if the prefix is not a disk prefix (e.g. `C:`).
  1375. ///
  1376. /// Compared to `from_file_path`, this ensure that URL’s the path has a trailing slash
  1377. /// so that the entire path is considered when using this URL as a base URL.
  1378. ///
  1379. /// For example:
  1380. ///
  1381. /// * `"index.html"` parsed with `Url::from_directory_path(Path::new("/var/www"))`
  1382. /// as the base URL is `file:///var/www/index.html`
  1383. /// * `"index.html"` parsed with `Url::from_file_path(Path::new("/var/www"))`
  1384. /// as the base URL is `file:///var/index.html`, which might not be what was intended.
  1385. ///
  1386. /// Note that `std::path` does not consider trailing slashes significant
  1387. /// and usually does not include them (e.g. in `Path::parent()`).
  1388. pub fn from_directory_path<P: AsRef<Path>>(path: P) -> Result<Url, ()> {
  1389. let mut url = Url::from_file_path(path)?;
  1390. if !url.serialization.ends_with('/') {
  1391. url.serialization.push('/')
  1392. }
  1393. Ok(url)
  1394. }
  1395. /// Serialize with Serde using the internal representation of the `Url` struct.
  1396. ///
  1397. /// The corresponding `deserialize_internal` method sacrifices some invariant-checking
  1398. /// for speed, compared to the `Deserialize` trait impl.
  1399. ///
  1400. /// This method is only available if the `serde` Cargo feature is enabled.
  1401. #[cfg(feature = "serde")]
  1402. #[deny(unused)]
  1403. pub fn serialize_internal<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
  1404. use serde::Serialize;
  1405. // Destructuring first lets us ensure that adding or removing fields forces this method
  1406. // to be updated
  1407. let Url { ref serialization, ref scheme_end,
  1408. ref username_end, ref host_start,
  1409. ref host_end, ref host, ref port,
  1410. ref path_start, ref query_start,
  1411. ref fragment_start} = *self;
  1412. (serialization, scheme_end, username_end,
  1413. host_start, host_end, host, port, path_start,
  1414. query_start, fragment_start).serialize(serializer)
  1415. }
  1416. /// Serialize with Serde using the internal representation of the `Url` struct.
  1417. ///
  1418. /// The corresponding `deserialize_internal` method sacrifices some invariant-checking
  1419. /// for speed, compared to the `Deserialize` trait impl.
  1420. ///
  1421. /// This method is only available if the `serde` Cargo feature is enabled.
  1422. #[cfg(feature = "serde")]
  1423. #[deny(unused)]
  1424. pub fn deserialize_internal<D>(deserializer: &mut D) -> Result<Self, D::Error> where D: serde::Deserializer {
  1425. use serde::{Deserialize, Error};
  1426. let (serialization, scheme_end, username_end,
  1427. host_start, host_end, host, port, path_start,
  1428. query_start, fragment_start) = Deserialize::deserialize(deserializer)?;
  1429. let url = Url {
  1430. serialization: serialization,
  1431. scheme_end: scheme_end,
  1432. username_end: username_end,
  1433. host_start: host_start,
  1434. host_end: host_end,
  1435. host: host,
  1436. port: port,
  1437. path_start: path_start,
  1438. query_start: query_start,
  1439. fragment_start: fragment_start
  1440. };
  1441. if cfg!(debug_assertions) {
  1442. url.check_invariants().map_err(|ref reason| Error::invalid_value(&reason))?
  1443. }
  1444. Ok(url)
  1445. }
  1446. /// Assuming the URL is in the `file` scheme or similar,
  1447. /// convert its path to an absolute `std::path::Path`.
  1448. ///
  1449. /// **Note:** This does not actually check the URL’s `scheme`,
  1450. /// and may give nonsensical results for other schemes.
  1451. /// It is the user’s responsibility to check the URL’s scheme before calling this.
  1452. ///
  1453. /// ```
  1454. /// # use url::Url;
  1455. /// # let url = Url::parse("file:///etc/passwd").unwrap();
  1456. /// let path = url.to_file_path();
  1457. /// ```
  1458. ///
  1459. /// Returns `Err` if the host is neither empty nor `"localhost"`,
  1460. /// or if `Path::new_opt()` returns `None`.
  1461. /// (That is, if the percent-decoded path contains a NUL byte or,
  1462. /// for a Windows path, is not UTF-8.)
  1463. #[inline]
  1464. pub fn to_file_path(&self) -> Result<PathBuf, ()> {
  1465. // FIXME: Figure out what to do w.r.t host.
  1466. if matches!(self.host(), None | Some(Host::Domain("localhost"))) {
  1467. if let Some(segments) = self.path_segments() {
  1468. return file_url_segments_to_pathbuf(segments)
  1469. }
  1470. }
  1471. Err(())
  1472. }
  1473. // Private helper methods:
  1474. #[inline]
  1475. fn slice<R>(&self, range: R) -> &str where R: RangeArg {
  1476. range.slice_of(&self.serialization)
  1477. }
  1478. #[inline]
  1479. fn byte_at(&self, i: u32) -> u8 {
  1480. self.serialization.as_bytes()[i as usize]
  1481. }
  1482. }
  1483. /// Return an error if `Url::host` or `Url::port_or_known_default` return `None`.
  1484. impl ToSocketAddrs for Url {
  1485. type Iter = SocketAddrs;
  1486. fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
  1487. self.with_default_port(|_| Err(()))?.to_socket_addrs()
  1488. }
  1489. }
  1490. /// Parse a string as an URL, without a base URL or encoding override.
  1491. impl str::FromStr for Url {
  1492. type Err = ParseError;
  1493. #[inline]
  1494. fn from_str(input: &str) -> Result<Url, ::ParseError> {
  1495. Url::parse(input)
  1496. }
  1497. }
  1498. /// Display the serialization of this URL.
  1499. impl fmt::Display for Url {
  1500. #[inline]
  1501. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  1502. fmt::Display::fmt(&self.serialization, formatter)
  1503. }
  1504. }
  1505. /// Debug the serialization of this URL.
  1506. impl fmt::Debug for Url {
  1507. #[inline]
  1508. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  1509. fmt::Debug::fmt(&self.serialization, formatter)
  1510. }
  1511. }
  1512. /// URLs compare like their serialization.
  1513. impl Eq for Url {}
  1514. /// URLs compare like their serialization.
  1515. impl PartialEq for Url {
  1516. #[inline]
  1517. fn eq(&self, other: &Self) -> bool {
  1518. self.serialization == other.serialization
  1519. }
  1520. }
  1521. /// URLs compare like their serialization.
  1522. impl Ord for Url {
  1523. #[inline]
  1524. fn cmp(&self, other: &Self) -> cmp::Ordering {
  1525. self.serialization.cmp(&other.serialization)
  1526. }
  1527. }
  1528. /// URLs compare like their serialization.
  1529. impl PartialOrd for Url {
  1530. #[inline]
  1531. fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
  1532. self.serialization.partial_cmp(&other.serialization)
  1533. }
  1534. }
  1535. /// URLs hash like their serialization.
  1536. impl hash::Hash for Url {
  1537. #[inline]
  1538. fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
  1539. hash::Hash::hash(&self.serialization, state)
  1540. }
  1541. }
  1542. /// Return the serialization of this URL.
  1543. impl AsRef<str> for Url {
  1544. #[inline]
  1545. fn as_ref(&self) -> &str {
  1546. &self.serialization
  1547. }
  1548. }
  1549. trait RangeArg {
  1550. fn slice_of<'a>(&self, s: &'a str) -> &'a str;
  1551. }
  1552. impl RangeArg for Range<u32> {
  1553. #[inline]
  1554. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  1555. &s[self.start as usize .. self.end as usize]
  1556. }
  1557. }
  1558. impl RangeArg for RangeFrom<u32> {
  1559. #[inline]
  1560. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  1561. &s[self.start as usize ..]
  1562. }
  1563. }
  1564. impl RangeArg for RangeTo<u32> {
  1565. #[inline]
  1566. fn slice_of<'a>(&self, s: &'a str) -> &'a str {
  1567. &s[.. self.end as usize]
  1568. }
  1569. }
  1570. #[cfg(feature="rustc-serialize")]
  1571. impl rustc_serialize::Encodable for Url {
  1572. fn encode<S: rustc_serialize::Encoder>(&self, encoder: &mut S) -> Result<(), S::Error> {
  1573. encoder.emit_str(self.as_str())
  1574. }
  1575. }
  1576. #[cfg(feature="rustc-serialize")]
  1577. impl rustc_serialize::Decodable for Url {
  1578. fn decode<D: rustc_serialize::Decoder>(decoder: &mut D) -> Result<Url, D::Error> {
  1579. Url::parse(&*decoder.read_str()?).map_err(|error| {
  1580. decoder.error(&format!("URL parsing error: {}", error))
  1581. })
  1582. }
  1583. }
  1584. /// Serializes this URL into a `serde` stream.
  1585. ///
  1586. /// This implementation is only available if the `serde` Cargo feature is enabled.
  1587. #[cfg(feature="serde")]
  1588. impl serde::Serialize for Url {
  1589. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: serde::Serializer {
  1590. serializer.serialize_str(self.as_str())
  1591. }
  1592. }
  1593. /// Deserializes this URL from a `serde` stream.
  1594. ///
  1595. /// This implementation is only available if the `serde` Cargo feature is enabled.
  1596. #[cfg(feature="serde")]
  1597. impl serde::Deserialize for Url {
  1598. fn deserialize<D>(deserializer: &mut D) -> Result<Url, D::Error> where D: serde::Deserializer {
  1599. let string_representation: String = serde::Deserialize::deserialize(deserializer)?;
  1600. Url::parse(&string_representation).map_err(|err| {
  1601. serde::Error::invalid_value(err.description())
  1602. })
  1603. }
  1604. }
  1605. #[cfg(any(unix, target_os = "redox"))]
  1606. fn path_to_file_url_segments(path: &Path, serialization: &mut String) -> Result<(), ()> {
  1607. use std::os::unix::prelude::OsStrExt;
  1608. if !path.is_absolute() {
  1609. return Err(())
  1610. }
  1611. let mut empty = true;
  1612. // skip the root component
  1613. for component in path.components().skip(1) {
  1614. empty = false;
  1615. serialization.push('/');
  1616. serialization.extend(percent_encode(
  1617. component.as_os_str().as_bytes(), PATH_SEGMENT_ENCODE_SET));
  1618. }
  1619. if empty {
  1620. // An URL’s path must not be empty.
  1621. serialization.push('/');
  1622. }
  1623. Ok(())
  1624. }
  1625. #[cfg(windows)]
  1626. fn path_to_file_url_segments(path: &Path, serialization: &mut String) -> Result<(), ()> {
  1627. path_to_file_url_segments_windows(path, serialization)
  1628. }
  1629. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  1630. #[cfg_attr(not(windows), allow(dead_code))]
  1631. fn path_to_file_url_segments_windows(path: &Path, serialization: &mut String) -> Result<(), ()> {
  1632. use std::path::{Prefix, Component};
  1633. if !path.is_absolute() {
  1634. return Err(())
  1635. }
  1636. let mut components = path.components();
  1637. let disk = match components.next() {
  1638. Some(Component::Prefix(ref p)) => match p.kind() {
  1639. Prefix::Disk(byte) => byte,
  1640. Prefix::VerbatimDisk(byte) => byte,
  1641. _ => return Err(()),
  1642. },
  1643. // FIXME: do something with UNC and other prefixes?
  1644. _ => return Err(())
  1645. };
  1646. // Start with the prefix, e.g. "C:"
  1647. serialization.push('/');
  1648. serialization.push(disk as char);
  1649. serialization.push(':');
  1650. for component in components {
  1651. if component == Component::RootDir { continue }
  1652. // FIXME: somehow work with non-unicode?
  1653. let component = component.as_os_str().to_str().ok_or(())?;
  1654. serialization.push('/');
  1655. serialization.extend(percent_encode(component.as_bytes(), PATH_SEGMENT_ENCODE_SET));
  1656. }
  1657. Ok(())
  1658. }
  1659. #[cfg(any(unix, target_os = "redox"))]
  1660. fn file_url_segments_to_pathbuf(segments: str::Split<char>) -> Result<PathBuf, ()> {
  1661. use std::ffi::OsStr;
  1662. use std::os::unix::prelude::OsStrExt;
  1663. use std::path::PathBuf;
  1664. let mut bytes = Vec::new();
  1665. for segment in segments {
  1666. bytes.push(b'/');
  1667. bytes.extend(percent_decode(segment.as_bytes()));
  1668. }
  1669. let os_str = OsStr::from_bytes(&bytes);
  1670. let path = PathBuf::from(os_str);
  1671. debug_assert!(path.is_absolute(),
  1672. "to_file_path() failed to produce an absolute Path");
  1673. Ok(path)
  1674. }
  1675. #[cfg(windows)]
  1676. fn file_url_segments_to_pathbuf(segments: str::Split<char>) -> Result<PathBuf, ()> {
  1677. file_url_segments_to_pathbuf_windows(segments)
  1678. }
  1679. // Build this unconditionally to alleviate https://github.com/servo/rust-url/issues/102
  1680. #[cfg_attr(not(windows), allow(dead_code))]
  1681. fn file_url_segments_to_pathbuf_windows(mut segments: str::Split<char>) -> Result<PathBuf, ()> {
  1682. let first = segments.next().ok_or(())?;
  1683. let mut string = match first.len() {
  1684. 2 => {
  1685. if !first.starts_with(parser::ascii_alpha) || first.as_bytes()[1] != b':' {
  1686. return Err(())
  1687. }
  1688. first.to_owned()
  1689. },
  1690. 4 => {
  1691. if !first.starts_with(parser::ascii_alpha) {
  1692. return Err(())
  1693. }
  1694. let bytes = first.as_bytes();
  1695. if bytes[1] != b'%' || bytes[2] != b'3' || (bytes[3] != b'a' && bytes[3] != b'A') {
  1696. return Err(())
  1697. }
  1698. first[0..1].to_owned() + ":"
  1699. },
  1700. _ => return Err(()),
  1701. };
  1702. for segment in segments {
  1703. string.push('\\');
  1704. // Currently non-unicode windows paths cannot be represented
  1705. match String::from_utf8(percent_decode(segment.as_bytes()).collect()) {
  1706. Ok(s) => string.push_str(&s),
  1707. Err(..) => return Err(()),
  1708. }
  1709. }
  1710. let path = PathBuf::from(string);
  1711. debug_assert!(path.is_absolute(),
  1712. "to_file_path() failed to produce an absolute Path");
  1713. Ok(path)
  1714. }
  1715. fn io_error<T>(reason: &str) -> io::Result<T> {
  1716. Err(io::Error::new(io::ErrorKind::InvalidData, reason))
  1717. }
  1718. /// Implementation detail of `Url::query_pairs_mut`. Typically not used directly.
  1719. pub struct UrlQuery<'a> {
  1720. url: &'a mut Url,
  1721. fragment: Option<String>,
  1722. }
  1723. impl<'a> Drop for UrlQuery<'a> {
  1724. fn drop(&mut self) {
  1725. self.url.restore_already_parsed_fragment(self.fragment.take())
  1726. }
  1727. }