1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Types/fns concerning URLs (see RFC 3986)
13 #![crate_name = "url"]
14 #![deprecated="This is being removed. Use rust-url instead. http://servo.github.io/rust-url/"]
16 #![crate_type = "rlib"]
17 #![crate_type = "dylib"]
18 #![license = "MIT/ASL2"]
19 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
20 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
21 html_root_url = "http://doc.rust-lang.org/master/",
22 html_playground_url = "http://play.rust-lang.org/")]
23 #![feature(default_type_params)]
25 use std::collections::HashMap;
26 use std::collections::hashmap::{Occupied, Vacant};
28 use std::from_str::FromStr;
31 use std::path::BytesContainer;
33 /// A Uniform Resource Locator (URL). A URL is a form of URI (Uniform Resource
34 /// Identifier) that includes network location information, such as hostname or
40 /// # #![allow(deprecated)]
43 /// let raw = "https://username@example.com:8080/foo/bar?baz=qux#quz";
44 /// match Url::parse(raw) {
45 /// Ok(u) => println!("Parsed '{}'", u),
46 /// Err(e) => println!("Couldn't parse '{}': {}", raw, e),
49 #[deriving(Clone, PartialEq, Eq)]
51 /// The scheme part of a URL, such as `https` in the above example.
53 /// A URL subcomponent for user authentication. `username` in the above example.
54 pub user: Option<UserInfo>,
55 /// A domain name or IP address. For example, `example.com`.
57 /// A TCP port number, for example `8080`.
58 pub port: Option<u16>,
59 /// The path component of a URL, for example `/foo/bar?baz=qux#quz`.
63 #[deriving(Clone, PartialEq, Eq)]
65 /// The path component of a URL, for example `/foo/bar`.
67 /// The query component of a URL.
68 /// `vec![("baz".to_string(), "qux".to_string())]` represents the fragment
69 /// `baz=qux` in the above example.
71 /// The fragment component, such as `quz`. Not including the leading `#` character.
72 pub fragment: Option<String>
75 /// An optional subcomponent of a URI authority component.
76 #[deriving(Clone, PartialEq, Eq)]
80 /// Password or other scheme-specific authentication information.
81 pub pass: Option<String>
84 /// Represents the query component of a URI.
85 pub type Query = Vec<(String, String)>;
88 pub fn new(scheme: String,
89 user: Option<UserInfo>,
94 fragment: Option<String>)
101 path: Path::new(path, query, fragment)
105 /// Parses a URL, converting it from a string to a `Url` representation.
108 /// * rawurl - a string representing the full URL, including scheme.
112 /// `Err(e)` if the string did not represent a valid URL, where `e` is a
113 /// `String` error message. Otherwise, `Ok(u)` where `u` is a `Url` struct
114 /// representing the URL.
115 pub fn parse(rawurl: &str) -> DecodeResult<Url> {
117 let (scheme, rest) = try!(get_scheme(rawurl));
120 let (userinfo, host, port, rest) = try!(get_authority(rest));
123 let has_authority = host.len() > 0;
124 let (path, rest) = try!(get_path(rest, has_authority));
126 // query and fragment
127 let (query, fragment) = try!(get_query_fragment(rest));
129 let url = Url::new(scheme.to_string(),
140 #[deprecated="use `Url::parse`"]
141 pub fn from_str(s: &str) -> Result<Url, String> {
146 pub fn new(path: String,
148 fragment: Option<String>)
157 /// Parses a URL path, converting it from a string to a `Path` representation.
160 /// * rawpath - a string representing the path component of a URL.
164 /// `Err(e)` if the string did not represent a valid URL path, where `e` is a
165 /// `String` error message. Otherwise, `Ok(p)` where `p` is a `Path` struct
166 /// representing the URL path.
167 pub fn parse(rawpath: &str) -> DecodeResult<Path> {
168 let (path, rest) = try!(get_path(rawpath, false));
170 // query and fragment
171 let (query, fragment) = try!(get_query_fragment(rest.as_slice()));
173 Ok(Path{ path: path, query: query, fragment: fragment })
177 #[deprecated="use `Path::parse`"]
178 pub fn path_from_str(s: &str) -> Result<Path, String> {
184 pub fn new(user: String, pass: Option<String>) -> UserInfo {
185 UserInfo { user: user, pass: pass }
189 fn encode_inner<T: BytesContainer>(c: T, full_url: bool) -> String {
190 c.container_as_bytes().iter().fold(String::new(), |mut out, &b| {
196 | '-' | '.' | '_' | '~' => out.push_char(b as char),
199 ':' | '/' | '?' | '#' | '[' | ']' | '@' |
201 '!' | '$' | '&' | '"' | '(' | ')' | '*' |
202 '+' | ',' | ';' | '='
203 if full_url => out.push_char(b as char),
205 ch => out.push_str(format!("%{:02X}", ch as uint).as_slice()),
212 /// Encodes a URI by replacing reserved characters with percent-encoded
213 /// character sequences.
215 /// This function is compliant with RFC 3986.
220 /// # #![allow(deprecated)]
223 /// let url = encode("https://example.com/Rust (programming language)");
224 /// println!("{}", url); // https://example.com/Rust%20(programming%20language)
226 pub fn encode<T: BytesContainer>(container: T) -> String {
227 encode_inner(container, true)
231 /// Encodes a URI component by replacing reserved characters with percent-
232 /// encoded character sequences.
234 /// This function is compliant with RFC 3986.
235 pub fn encode_component<T: BytesContainer>(container: T) -> String {
236 encode_inner(container, false)
239 pub type DecodeResult<T> = Result<T, String>;
241 /// Decodes a percent-encoded string representing a URI.
243 /// This will only decode escape sequences generated by `encode`.
248 /// # #![allow(deprecated)]
251 /// let url = decode("https://example.com/Rust%20(programming%20language)");
252 /// println!("{}", url); // https://example.com/Rust (programming language)
254 pub fn decode<T: BytesContainer>(container: T) -> DecodeResult<String> {
255 decode_inner(container, true)
258 /// Decode a string encoded with percent encoding.
259 pub fn decode_component<T: BytesContainer>(container: T) -> DecodeResult<String> {
260 decode_inner(container, false)
263 fn decode_inner<T: BytesContainer>(c: T, full_url: bool) -> DecodeResult<String> {
264 let mut out = String::new();
265 let mut iter = c.container_as_bytes().iter().map(|&b| b);
269 Some(b) => match b as char {
271 let bytes = match (iter.next(), iter.next()) {
272 (Some(one), Some(two)) => [one as u8, two as u8],
273 _ => return Err(format!("Malformed input: found '%' \
274 without two trailing bytes")),
277 // Only decode some characters if full_url:
278 match uint::parse_bytes(bytes, 16u).unwrap() as u8 as char {
280 ':' | '/' | '?' | '#' | '[' | ']' | '@' |
283 '!' | '$' | '&' | '"' | '(' | ')' | '*' |
284 '+' | ',' | ';' | '='
287 out.push_char(bytes[0u] as char);
288 out.push_char(bytes[1u] as char);
291 ch => out.push_char(ch)
294 ch => out.push_char(ch)
296 None => return Ok(out),
301 /// Encode a hashmap to the 'application/x-www-form-urlencoded' media type.
302 pub fn encode_form_urlencoded(m: &HashMap<String, Vec<String>>) -> String {
303 fn encode_plus<T: Str>(s: &T) -> String {
304 s.as_slice().bytes().fold(String::new(), |mut out, b| {
309 | '_' | '.' | '-' => out.push_char(b as char),
310 ' ' => out.push_char('+'),
311 ch => out.push_str(format!("%{:X}", ch as uint).as_slice())
318 let mut first = true;
319 m.iter().fold(String::new(), |mut out, (key, values)| {
320 let key = encode_plus(key);
322 for value in values.iter() {
329 out.push_str(key.as_slice());
331 out.push_str(encode_plus(value).as_slice());
338 /// Decode a string encoded with the 'application/x-www-form-urlencoded' media
339 /// type into a hashmap.
340 pub fn decode_form_urlencoded(s: &[u8])
341 -> DecodeResult<HashMap<String, Vec<String>>> {
342 fn maybe_push_value(map: &mut HashMap<String, Vec<String>>,
345 if key.len() > 0 && value.len() > 0 {
346 match map.entry(key) {
347 Vacant(entry) => { entry.set(vec![value]); },
348 Occupied(mut entry) => { entry.get_mut().push(value); },
353 let mut out = HashMap::new();
354 let mut iter = s.iter().map(|&x| x);
356 let mut key = String::new();
357 let mut value = String::new();
358 let mut parsing_key = true;
362 Some(b) => match b as char {
364 maybe_push_value(&mut out, key, value);
368 value = String::new();
370 '=' => parsing_key = false,
374 let bytes = match (iter.next(), iter.next()) {
375 (Some(one), Some(two)) => [one as u8, two as u8],
376 _ => return Err(format!("Malformed input: found \
377 '%' without two trailing bytes"))
380 uint::parse_bytes(bytes, 16u).unwrap() as u8 as char
394 maybe_push_value(&mut out, key, value);
401 fn split_char_first(s: &str, c: char) -> (&str, &str) {
402 let mut iter = s.splitn(1, c);
404 match (iter.next(), iter.next()) {
405 (Some(a), Some(b)) => (a, b),
406 (Some(a), None) => (a, ""),
407 (None, _) => unreachable!(),
411 impl fmt::Show for UserInfo {
412 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
414 Some(ref pass) => write!(f, "{}:{}@", self.user, *pass),
415 None => write!(f, "{}@", self.user),
420 fn query_from_str(rawquery: &str) -> DecodeResult<Query> {
421 let mut query: Query = vec!();
422 if !rawquery.is_empty() {
423 for p in rawquery.split('&') {
424 let (k, v) = split_char_first(p, '=');
425 query.push((try!(decode_component(k)),
426 try!(decode_component(v))));
433 /// Converts an instance of a URI `Query` type to a string.
438 /// # #![allow(deprecated)]
439 /// let query = vec![("title".to_string(), "The Village".to_string()),
440 /// ("north".to_string(), "52.91".to_string()),
441 /// ("west".to_string(), "4.10".to_string())];
442 /// println!("{}", url::query_to_str(&query)); // title=The%20Village&north=52.91&west=4.10
444 pub fn query_to_str(query: &Query) -> String {
445 query.iter().enumerate().fold(String::new(), |mut out, (i, &(ref k, ref v))| {
450 out.push_str(encode_component(k.as_slice()).as_slice());
452 out.push_str(encode_component(v.as_slice()).as_slice());
457 /// Returns a tuple of the URI scheme and the rest of the URI, or a parsing error.
459 /// Does not include the separating `:` character.
464 /// # #![allow(deprecated)]
465 /// use url::get_scheme;
467 /// let scheme = match get_scheme("https://example.com/") {
468 /// Ok((sch, _)) => sch,
469 /// Err(_) => "(None)",
471 /// println!("Scheme in use: {}.", scheme); // Scheme in use: https.
473 pub fn get_scheme(rawurl: &str) -> DecodeResult<(&str, &str)> {
474 for (i,c) in rawurl.chars().enumerate() {
475 let result = match c {
477 | 'a' ... 'z' => continue,
478 '0' ... '9' | '+' | '-' | '.' => {
479 if i != 0 { continue }
481 Err("url: Scheme must begin with a letter.".to_string())
485 Err("url: Scheme cannot be empty.".to_string())
487 Ok((rawurl.slice(0,i), rawurl.slice(i+1,rawurl.len())))
490 _ => Err("url: Invalid character in scheme.".to_string()),
496 Err("url: Scheme must be terminated with a colon.".to_string())
499 // returns userinfo, host, port, and unparsed part, or an error
500 fn get_authority(rawurl: &str) ->
501 DecodeResult<(Option<UserInfo>, &str, Option<u16>, &str)> {
503 Start, // starting state
504 PassHostPort, // could be in user or port
505 Ip6Port, // either in ipv6 host or port
506 Ip6Host, // are in an ipv6 host
507 InHost, // are in a host - may be ipv6, but don't know yet
508 InPort // are in port
511 #[deriving(Clone, PartialEq)]
514 Hex, // digits and letters a-f
515 Unreserved // all other legal characters
518 if !rawurl.starts_with("//") {
519 // there is no authority.
520 return Ok((None, "", None, rawurl));
523 let len = rawurl.len();
525 let mut input = Digit; // most restricted, start here.
527 let mut userinfo = None;
531 let mut colon_count = 0u;
536 for (i,c) in rawurl.chars().enumerate()
537 // ignore the leading '//' handled by early return
539 // deal with input class first
550 | '-' | '.' | '_' | '~' | '%'
551 | '&' |'\'' | '(' | ')' | '+'
552 | '!' | '*' | ',' | ';' | '=' => input = Unreserved,
553 ':' | '@' | '?' | '#' | '/' => {
554 // separators, don't change anything
556 _ => return Err("Illegal character in authority".to_string()),
559 // now process states
569 // multiple colons means ipv6 address.
570 if input == Unreserved {
572 "Illegal characters in IPv6 address.".to_string());
578 if input == Unreserved {
580 host = rawurl.slice(begin, i);
583 // can't be sure whether this is an ipv6 address or a port
588 if input == Unreserved {
589 return Err("Illegal characters in authority.".to_string());
595 host = rawurl.slice(begin, i);
600 _ => return Err("Invalid ':' in authority.".to_string()),
602 input = Digit; // reset input class
606 input = Digit; // reset input class
607 colon_count = 0; // reset count
610 let user = rawurl.slice(begin, i).to_string();
611 userinfo = Some(UserInfo::new(user, None));
615 let user = rawurl.slice(begin, pos).to_string();
616 let pass = rawurl.slice(pos+1, i).to_string();
617 userinfo = Some(UserInfo::new(user, Some(pass)));
620 _ => return Err("Invalid '@' in authority.".to_string()),
635 Start => host = rawurl.slice(begin, end),
639 return Err("Non-digit characters in port.".to_string());
641 host = rawurl.slice(begin, pos);
642 port = Some(rawurl.slice(pos+1, end));
645 | InHost => host = rawurl.slice(begin, end),
648 return Err("Non-digit characters in port.".to_string());
650 port = Some(rawurl.slice(pos+1, end));
654 let rest = rawurl.slice(end, len);
655 // If we have a port string, ensure it parses to u16.
656 let port = match port {
658 opt => match opt.and_then(|p| FromStr::from_str(p)) {
659 None => return Err(format!("Failed to parse port: {}", port)),
664 Ok((userinfo, host, port, rest))
668 // returns the path and unparsed part of url, or an error
669 fn get_path(rawurl: &str, is_authority: bool) -> DecodeResult<(String, &str)> {
670 let len = rawurl.len();
672 for (i,c) in rawurl.chars().enumerate() {
677 | '&' |'\'' | '(' | ')' | '.'
678 | '@' | ':' | '%' | '/' | '+'
679 | '!' | '*' | ',' | ';' | '='
680 | '_' | '-' | '~' => continue,
685 _ => return Err("Invalid character in path.".to_string())
689 if is_authority && end != 0 && !rawurl.starts_with("/") {
690 Err("Non-empty path must begin with \
691 '/' in presence of authority.".to_string())
693 Ok((try!(decode_component(rawurl.slice(0, end))),
694 rawurl.slice(end, len)))
698 // returns the parsed query and the fragment, if present
699 fn get_query_fragment(rawurl: &str) -> DecodeResult<(Query, Option<String>)> {
700 let (before_fragment, raw_fragment) = split_char_first(rawurl, '#');
702 // Parse the fragment if available
703 let fragment = match raw_fragment {
705 raw => Some(try!(decode_component(raw)))
708 match before_fragment.slice_shift_char() {
709 (Some('?'), rest) => Ok((try!(query_from_str(rest)), fragment)),
710 (None, "") => Ok((vec!(), fragment)),
711 _ => Err(format!("Query didn't start with '?': '{}..'", before_fragment)),
715 impl FromStr for Url {
716 fn from_str(s: &str) -> Option<Url> {
721 impl FromStr for Path {
722 fn from_str(s: &str) -> Option<Path> {
727 impl fmt::Show for Url {
728 /// Converts a URL from `Url` to string representation.
732 /// A string that contains the formatted URL. Note that this will usually
733 /// be an inverse of `from_str` but might strip out unneeded separators;
734 /// for example, "http://somehost.com?", when parsed and formatted, will
735 /// result in just "http://somehost.com".
736 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
737 try!(write!(f, "{}:", self.scheme));
739 if !self.host.is_empty() {
740 try!(write!(f, "//"));
742 Some(ref user) => try!(write!(f, "{}", *user)),
746 Some(ref port) => try!(write!(f, "{}:{}", self.host,
748 None => try!(write!(f, "{}", self.host)),
752 write!(f, "{}", self.path)
756 impl fmt::Show for Path {
757 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
758 try!(write!(f, "{}", self.path));
759 if !self.query.is_empty() {
760 try!(write!(f, "?{}", query_to_str(&self.query)))
763 match self.fragment {
764 Some(ref fragment) => {
765 write!(f, "#{}", encode_component(fragment.as_slice()))
772 impl<S: hash::Writer> hash::Hash<S> for Url {
773 fn hash(&self, state: &mut S) {
774 self.to_string().hash(state)
778 impl<S: hash::Writer> hash::Hash<S> for Path {
779 fn hash(&self, state: &mut S) {
780 self.to_string().hash(state)
784 // Put a few tests outside of the 'test' module so they can test the internal
785 // functions and those functions don't need 'pub'
788 fn test_split_char_first() {
789 let (u,v) = split_char_first("hello, sweet world", ',');
790 assert_eq!(u, "hello");
791 assert_eq!(v, " sweet world");
793 let (u,v) = split_char_first("hello sweet world", ',');
794 assert_eq!(u, "hello sweet world");
799 fn test_get_authority() {
800 let (u, h, p, r) = get_authority(
801 "//user:pass@rust-lang.org/something").unwrap();
802 assert_eq!(u, Some(UserInfo::new("user".to_string(), Some("pass".to_string()))));
803 assert_eq!(h, "rust-lang.org");
804 assert!(p.is_none());
805 assert_eq!(r, "/something");
807 let (u, h, p, r) = get_authority(
808 "//rust-lang.org:8000?something").unwrap();
809 assert!(u.is_none());
810 assert_eq!(h, "rust-lang.org");
811 assert_eq!(p, Some(8000));
812 assert_eq!(r, "?something");
814 let (u, h, p, r) = get_authority("//rust-lang.org#blah").unwrap();
815 assert!(u.is_none());
816 assert_eq!(h, "rust-lang.org");
817 assert!(p.is_none());
818 assert_eq!(r, "#blah");
821 let (_, h, _, _) = get_authority(
822 "//2001:0db8:85a3:0042:0000:8a2e:0370:7334#blah").unwrap();
823 assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334");
825 let (_, h, p, _) = get_authority(
826 "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah").unwrap();
827 assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334");
828 assert_eq!(p, Some(8000));
830 let (u, h, p, _) = get_authority(
831 "//us:p@2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah"
833 assert_eq!(u, Some(UserInfo::new("us".to_string(), Some("p".to_string()))));
834 assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334");
835 assert_eq!(p, Some(8000));
837 // invalid authorities;
838 assert!(get_authority("//user:pass@rust-lang:something").is_err());
839 assert!(get_authority("//user@rust-lang:something:/path").is_err());
840 assert!(get_authority(
841 "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:800a").is_err());
842 assert!(get_authority(
843 "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000:00").is_err());
845 assert!(get_authority("//user:pass@rust-lang:65536").is_err());
847 // these parse as empty, because they don't start with '//'
848 let (_, h, _, _) = get_authority("user:pass@rust-lang").unwrap();
850 let (_, h, _, _) = get_authority("rust-lang.org").unwrap();
856 let (p, r) = get_path("/something+%20orother", true).unwrap();
857 assert_eq!(p, "/something+ orother".to_string());
859 let (p, r) = get_path("test@email.com#fragment", false).unwrap();
860 assert_eq!(p, "test@email.com".to_string());
861 assert_eq!(r, "#fragment");
862 let (p, r) = get_path("/gen/:addr=?q=v", false).unwrap();
863 assert_eq!(p, "/gen/:addr=".to_string());
864 assert_eq!(r, "?q=v");
867 assert!(get_path("something?q", true).is_err());
872 use {encode_form_urlencoded, decode_form_urlencoded, decode, encode,
873 encode_component, decode_component, UserInfo, get_scheme, Url, Path};
875 use std::collections::HashMap;
876 use std::path::BytesContainer;
879 fn test_url_parse() {
880 let url = "http://user:pass@rust-lang.org:8080/doc/~u?s=v#something";
881 let u = from_str::<Url>(url).unwrap();
883 assert_eq!(u.scheme, "http".to_string());
884 assert_eq!(u.user, Some(UserInfo::new("user".to_string(), Some("pass".to_string()))));
885 assert_eq!(u.host, "rust-lang.org".to_string());
886 assert_eq!(u.port, Some(8080));
887 assert_eq!(u.path.path, "/doc/~u".to_string());
888 assert_eq!(u.path.query, vec!(("s".to_string(), "v".to_string())));
889 assert_eq!(u.path.fragment, Some("something".to_string()));
893 fn test_path_parse() {
894 let path = "/doc/~u?s=v#something";
895 let u = from_str::<Path>(path).unwrap();
897 assert_eq!(u.path, "/doc/~u".to_string());
898 assert_eq!(u.query, vec!(("s".to_string(), "v".to_string())));
899 assert_eq!(u.fragment, Some("something".to_string()));
903 fn test_url_parse_host_slash() {
904 let urlstr = "http://0.42.42.42/";
905 let url = from_str::<Url>(urlstr).unwrap();
906 assert_eq!(url.host, "0.42.42.42".to_string());
907 assert_eq!(url.path.path, "/".to_string());
911 fn test_path_parse_host_slash() {
913 let path = from_str::<Path>(pathstr).unwrap();
914 assert_eq!(path.path, "/".to_string());
918 fn test_url_host_with_port() {
919 let urlstr = "scheme://host:1234";
920 let url = from_str::<Url>(urlstr).unwrap();
921 assert_eq!(url.scheme, "scheme".to_string());
922 assert_eq!(url.host, "host".to_string());
923 assert_eq!(url.port, Some(1234));
924 // is empty path really correct? Other tests think so
925 assert_eq!(url.path.path, "".to_string());
927 let urlstr = "scheme://host:1234/";
928 let url = from_str::<Url>(urlstr).unwrap();
929 assert_eq!(url.scheme, "scheme".to_string());
930 assert_eq!(url.host, "host".to_string());
931 assert_eq!(url.port, Some(1234));
932 assert_eq!(url.path.path, "/".to_string());
936 fn test_url_with_underscores() {
937 let urlstr = "http://dotcom.com/file_name.html";
938 let url = from_str::<Url>(urlstr).unwrap();
939 assert_eq!(url.path.path, "/file_name.html".to_string());
943 fn test_path_with_underscores() {
944 let pathstr = "/file_name.html";
945 let path = from_str::<Path>(pathstr).unwrap();
946 assert_eq!(path.path, "/file_name.html".to_string());
950 fn test_url_with_dashes() {
951 let urlstr = "http://dotcom.com/file-name.html";
952 let url = from_str::<Url>(urlstr).unwrap();
953 assert_eq!(url.path.path, "/file-name.html".to_string());
957 fn test_path_with_dashes() {
958 let pathstr = "/file-name.html";
959 let path = from_str::<Path>(pathstr).unwrap();
960 assert_eq!(path.path, "/file-name.html".to_string());
964 fn test_no_scheme() {
965 assert!(get_scheme("noschemehere.html").is_err());
969 fn test_invalid_scheme_errors() {
970 assert!(Url::parse("99://something").is_err());
971 assert!(Url::parse("://something").is_err());
975 fn test_full_url_parse_and_format() {
976 let url = "http://user:pass@rust-lang.org/doc?s=v#something";
977 let u = from_str::<Url>(url).unwrap();
978 assert_eq!(format!("{}", u).as_slice(), url);
982 fn test_userless_url_parse_and_format() {
983 let url = "http://rust-lang.org/doc?s=v#something";
984 let u = from_str::<Url>(url).unwrap();
985 assert_eq!(format!("{}", u).as_slice(), url);
989 fn test_queryless_url_parse_and_format() {
990 let url = "http://user:pass@rust-lang.org/doc#something";
991 let u = from_str::<Url>(url).unwrap();
992 assert_eq!(format!("{}", u).as_slice(), url);
996 fn test_empty_query_url_parse_and_format() {
997 let url = "http://user:pass@rust-lang.org/doc?#something";
998 let should_be = "http://user:pass@rust-lang.org/doc#something";
999 let u = from_str::<Url>(url).unwrap();
1000 assert_eq!(format!("{}", u).as_slice(), should_be);
1004 fn test_fragmentless_url_parse_and_format() {
1005 let url = "http://user:pass@rust-lang.org/doc?q=v";
1006 let u = from_str::<Url>(url).unwrap();
1007 assert_eq!(format!("{}", u).as_slice(), url);
1011 fn test_minimal_url_parse_and_format() {
1012 let url = "http://rust-lang.org/doc";
1013 let u = from_str::<Url>(url).unwrap();
1014 assert_eq!(format!("{}", u).as_slice(), url);
1018 fn test_url_with_port_parse_and_format() {
1019 let url = "http://rust-lang.org:80/doc";
1020 let u = from_str::<Url>(url).unwrap();
1021 assert_eq!(format!("{}", u).as_slice(), url);
1025 fn test_scheme_host_only_url_parse_and_format() {
1026 let url = "http://rust-lang.org";
1027 let u = from_str::<Url>(url).unwrap();
1028 assert_eq!(format!("{}", u).as_slice(), url);
1032 fn test_pathless_url_parse_and_format() {
1033 let url = "http://user:pass@rust-lang.org?q=v#something";
1034 let u = from_str::<Url>(url).unwrap();
1035 assert_eq!(format!("{}", u).as_slice(), url);
1039 fn test_scheme_host_fragment_only_url_parse_and_format() {
1040 let url = "http://rust-lang.org#something";
1041 let u = from_str::<Url>(url).unwrap();
1042 assert_eq!(format!("{}", u).as_slice(), url);
1046 fn test_url_component_encoding() {
1047 let url = "http://rust-lang.org/doc%20uments?ba%25d%20=%23%26%2B";
1048 let u = from_str::<Url>(url).unwrap();
1049 assert!(u.path.path == "/doc uments".to_string());
1050 assert!(u.path.query == vec!(("ba%d ".to_string(), "#&+".to_string())));
1054 fn test_path_component_encoding() {
1055 let path = "/doc%20uments?ba%25d%20=%23%26%2B";
1056 let p = from_str::<Path>(path).unwrap();
1057 assert!(p.path == "/doc uments".to_string());
1058 assert!(p.query == vec!(("ba%d ".to_string(), "#&+".to_string())));
1062 fn test_url_without_authority() {
1063 let url = "mailto:test@email.com";
1064 let u = from_str::<Url>(url).unwrap();
1065 assert_eq!(format!("{}", u).as_slice(), url);
1070 fn t<T: BytesContainer>(input: T, expected: &str) {
1071 assert_eq!(encode(input), expected.to_string())
1075 t("http://example.com", "http://example.com");
1076 t("foo bar% baz", "foo%20bar%25%20baz");
1101 let a: &[_] = &[0u8, 10, 37];
1106 fn test_encode_component() {
1107 fn t<T: BytesContainer>(input: T, expected: &str) {
1108 assert_eq!(encode_component(input), expected.to_string())
1112 t("http://example.com", "http%3A%2F%2Fexample.com");
1113 t("foo bar% baz", "foo%20bar%25%20baz");
1137 let a: &[_] = &[0u8, 10, 37];
1143 fn t<T: BytesContainer>(input: T, expected: &str) {
1144 assert_eq!(decode(input), Ok(expected.to_string()))
1147 assert!(decode("sadsadsda%").is_err());
1148 assert!(decode("waeasd%4").is_err());
1150 t("abc/def 123", "abc/def 123");
1151 t("abc%2Fdef%20123", "abc%2Fdef 123");
1174 t("%00%0A%25".as_bytes(), "\0\n%");
1178 fn test_decode_component() {
1179 fn t<T: BytesContainer>(input: T, expected: &str) {
1180 assert_eq!(decode_component(input), Ok(expected.to_string()))
1183 assert!(decode_component("asacsa%").is_err());
1184 assert!(decode_component("acsas%4").is_err());
1186 t("abc/def 123", "abc/def 123");
1187 t("abc%2Fdef%20123", "abc/def 123");
1210 t("%00%0A%25".as_bytes(), "\0\n%");
1214 fn test_encode_form_urlencoded() {
1215 let mut m = HashMap::new();
1216 assert_eq!(encode_form_urlencoded(&m), "".to_string());
1218 m.insert("".to_string(), vec!());
1219 m.insert("foo".to_string(), vec!());
1220 assert_eq!(encode_form_urlencoded(&m), "".to_string());
1222 let mut m = HashMap::new();
1223 m.insert("foo".to_string(), vec!("bar".to_string(), "123".to_string()));
1224 assert_eq!(encode_form_urlencoded(&m), "foo=bar&foo=123".to_string());
1226 let mut m = HashMap::new();
1227 m.insert("foo bar".to_string(), vec!("abc".to_string(), "12 = 34".to_string()));
1228 assert_eq!(encode_form_urlencoded(&m),
1229 "foo+bar=abc&foo+bar=12+%3D+34".to_string());
1233 fn test_decode_form_urlencoded() {
1234 assert_eq!(decode_form_urlencoded([]).unwrap().len(), 0);
1236 let s = "a=1&foo+bar=abc&foo+bar=12+%3D+34".as_bytes();
1237 let form = decode_form_urlencoded(s).unwrap();
1238 assert_eq!(form.len(), 2);
1239 assert_eq!(form.get(&"a".to_string()), &vec!("1".to_string()));
1240 assert_eq!(form.get(&"foo bar".to_string()),
1241 &vec!("abc".to_string(), "12 = 34".to_string()));