1 // Copyright 2012 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 #[allow(missing_doc)];
17 use std::io::{Reader, ReaderUtil};
19 use std::hashmap::HashMap;
23 #[deriving(Clone, Eq)]
26 user: Option<UserInfo>,
31 fragment: Option<~str>
34 #[deriving(Clone, Eq)]
40 pub type Query = ~[(~str, ~str)];
43 pub fn new(scheme: ~str,
44 user: Option<UserInfo>,
49 fragment: Option<~str>)
64 pub fn new(user: ~str, pass: Option<~str>) -> UserInfo {
65 UserInfo { user: user, pass: pass }
69 fn encode_inner(s: &str, full_url: bool) -> ~str {
70 do io::with_str_reader(s) |rdr| {
74 let ch = rdr.read_byte() as char;
80 '-' | '.' | '_' | '~' => {
87 ':' | '/' | '?' | '#' | '[' | ']' | '@' |
90 '!' | '$' | '&' | '"' | '(' | ')' | '*' |
91 '+' | ',' | ';' | '=' => {
95 _ => out.push_str(fmt!("%%%X", ch as uint))
98 out.push_str(fmt!("%%%X", ch as uint));
109 * Encodes a URI by replacing reserved characters with percent encoded
110 * character sequences.
112 * This function is compliant with RFC 3986.
114 pub fn encode(s: &str) -> ~str {
115 encode_inner(s, true)
119 * Encodes a URI component by replacing reserved characters with percent
120 * encoded character sequences.
122 * This function is compliant with RFC 3986.
125 pub fn encode_component(s: &str) -> ~str {
126 encode_inner(s, false)
129 fn decode_inner(s: &str, full_url: bool) -> ~str {
130 do io::with_str_reader(s) |rdr| {
134 match rdr.read_char() {
136 let bytes = rdr.read_bytes(2u);
137 let ch = uint::parse_bytes(bytes, 16u).get() as char;
140 // Only decode some characters:
143 ':' | '/' | '?' | '#' | '[' | ']' | '@' |
146 '!' | '$' | '&' | '"' | '(' | ')' | '*' |
147 '+' | ',' | ';' | '=' => {
149 out.push_char(bytes[0u] as char);
150 out.push_char(bytes[1u] as char);
153 ch => out.push_char(ch)
159 ch => out.push_char(ch)
168 * Decode a string encoded with percent encoding.
170 * This will only decode escape sequences generated by encode.
172 pub fn decode(s: &str) -> ~str {
173 decode_inner(s, true)
177 * Decode a string encoded with percent encoding.
179 pub fn decode_component(s: &str) -> ~str {
180 decode_inner(s, false)
183 fn encode_plus(s: &str) -> ~str {
184 do io::with_str_reader(s) |rdr| {
188 let ch = rdr.read_byte() as char;
190 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '_' | '.' | '-' => {
193 ' ' => out.push_char('+'),
194 _ => out.push_str(fmt!("%%%X", ch as uint))
203 * Encode a hashmap to the 'application/x-www-form-urlencoded' media type.
205 pub fn encode_form_urlencoded(m: &HashMap<~str, ~[~str]>) -> ~str {
207 let mut first = true;
209 for m.iter().advance |(key, values)| {
210 let key = encode_plus(*key);
212 for values.iter().advance |value| {
220 out.push_str(fmt!("%s=%s", key, encode_plus(*value)));
228 * Decode a string encoded with the 'application/x-www-form-urlencoded' media
229 * type into a hashmap.
231 pub fn decode_form_urlencoded(s: &[u8]) -> HashMap<~str, ~[~str]> {
232 do io::with_bytes_reader(s) |rdr| {
233 let mut m = HashMap::new();
236 let mut parsing_key = true;
239 match rdr.read_char() {
241 if key != ~"" && value != ~"" {
242 let mut values = match m.pop(&key) {
243 Some(values) => values,
248 m.insert(key, values);
255 '=' => parsing_key = false,
259 let bytes = rdr.read_bytes(2u);
260 uint::parse_bytes(bytes, 16u).get() as char
275 if key != ~"" && value != ~"" {
276 let mut values = match m.pop(&key) {
277 Some(values) => values,
282 m.insert(key, values);
290 fn split_char_first(s: &str, c: char) -> (~str, ~str) {
294 do io::with_str_reader(s) |rdr| {
297 ch = rdr.read_byte() as char;
299 // found a match, adjust markers
300 index = rdr.tell()-1;
306 if index+mat == len {
307 return (s.slice(0, index).to_owned(), ~"");
309 return (s.slice(0, index).to_owned(),
310 s.slice(index + mat, s.len()).to_owned());
314 fn userinfo_from_str(uinfo: &str) -> UserInfo {
315 let (user, p) = split_char_first(uinfo, ':');
316 let pass = if p.is_empty() {
321 return UserInfo::new(user, pass);
324 fn userinfo_to_str(userinfo: &UserInfo) -> ~str {
325 match userinfo.pass {
326 Some(ref pass) => fmt!("%s:%s@", userinfo.user, *pass),
327 None => fmt!("%s@", userinfo.user),
331 fn query_from_str(rawquery: &str) -> Query {
332 let mut query: Query = ~[];
333 if !rawquery.is_empty() {
334 for rawquery.split_iter('&').advance |p| {
335 let (k, v) = split_char_first(p, '=');
336 query.push((decode_component(k), decode_component(v)));
342 pub fn query_to_str(query: &Query) -> ~str {
343 let mut strvec = ~[];
344 for query.iter().advance |kv| {
347 strvec.push(fmt!("%s=%s",
348 encode_component(*k),
349 encode_component(*v))
354 return strvec.connect("&");
357 // returns the scheme and the rest of the url, or a parsing error
358 pub fn get_scheme(rawurl: &str) -> Result<(~str, ~str), ~str> {
359 for rawurl.iter().enumerate().advance |(i,c)| {
361 'A' .. 'Z' | 'a' .. 'z' => loop,
362 '0' .. '9' | '+' | '-' | '.' => {
364 return Err(~"url: Scheme must begin with a letter.");
370 return Err(~"url: Scheme cannot be empty.");
372 return Ok((rawurl.slice(0,i).to_owned(),
373 rawurl.slice(i+1,rawurl.len()).to_owned()));
377 return Err(~"url: Invalid character in scheme.");
381 return Err(~"url: Scheme must be terminated with a colon.");
384 #[deriving(Clone, Eq)]
387 Hex, // digits and letters a-f
388 Unreserved // all other legal characters
391 // returns userinfo, host, port, and unparsed part, or an error
392 fn get_authority(rawurl: &str) ->
393 Result<(Option<UserInfo>, ~str, Option<~str>, ~str), ~str> {
394 if !rawurl.starts_with("//") {
395 // there is no authority.
396 return Ok((None, ~"", None, rawurl.to_str()));
400 Start, // starting state
401 PassHostPort, // could be in user or port
402 Ip6Port, // either in ipv6 host or port
403 Ip6Host, // are in an ipv6 host
404 InHost, // are in a host - may be ipv6, but don't know yet
405 InPort // are in port
408 let len = rawurl.len();
410 let mut in = Digit; // most restricted, start here.
412 let mut userinfo = None;
416 let mut colon_count = 0;
421 for rawurl.iter().enumerate().advance |(i,c)| {
422 if i < 2 { loop; } // ignore the leading //
424 // deal with input class first
427 'A' .. 'F' | 'a' .. 'f' => {
432 'G' .. 'Z' | 'g' .. 'z' | '-' | '.' | '_' | '~' | '%' |
433 '&' |'\'' | '(' | ')' | '+' | '!' | '*' | ',' | ';' | '=' => {
436 ':' | '@' | '?' | '#' | '/' => {
437 // separators, don't change anything
440 return Err(~"Illegal character in authority");
444 // now process states
454 // multiple colons means ipv6 address.
455 if in == Unreserved {
457 ~"Illegal characters in IPv6 address.");
463 // can't be sure whether this is an ipv6 address or a port
464 if in == Unreserved {
465 return Err(~"Illegal characters in authority.");
470 if in == Unreserved {
471 return Err(~"Illegal characters in authority.");
477 host = rawurl.slice(begin, i).to_owned();
483 return Err(~"Invalid ':' in authority.");
486 in = Digit; // reset input class
490 in = Digit; // reset input class
491 colon_count = 0; // reset count
494 let user = rawurl.slice(begin, i).to_owned();
495 userinfo = Some(UserInfo::new(user, None));
499 let user = rawurl.slice(begin, pos).to_owned();
500 let pass = rawurl.slice(pos+1, i).to_owned();
501 userinfo = Some(UserInfo::new(user, Some(pass)));
505 return Err(~"Invalid '@' in authority.");
520 let end = end; // make end immutable so it can be captured
522 let host_is_end_plus_one: &fn() -> bool = || {
523 let xs = ['?', '#', '/'];
525 && !xs.iter().any(|x| *x == (rawurl[end] as char))
531 if host_is_end_plus_one() {
532 host = rawurl.slice(begin, end+1).to_owned();
534 host = rawurl.slice(begin, end).to_owned();
537 PassHostPort | Ip6Port => {
539 return Err(~"Non-digit characters in port.");
541 host = rawurl.slice(begin, pos).to_owned();
542 port = Some(rawurl.slice(pos+1, end).to_owned());
544 Ip6Host | InHost => {
545 host = rawurl.slice(begin, end).to_owned();
549 return Err(~"Non-digit characters in port.");
551 port = Some(rawurl.slice(pos+1, end).to_owned());
555 let rest = if host_is_end_plus_one() { ~"" }
556 else { rawurl.slice(end, len).to_owned() };
557 return Ok((userinfo, host, port, rest));
561 // returns the path and unparsed part of url, or an error
562 fn get_path(rawurl: &str, authority: bool) ->
563 Result<(~str, ~str), ~str> {
564 let len = rawurl.len();
566 for rawurl.iter().enumerate().advance |(i,c)| {
568 'A' .. 'Z' | 'a' .. 'z' | '0' .. '9' | '&' |'\'' | '(' | ')' | '.'
569 | '@' | ':' | '%' | '/' | '+' | '!' | '*' | ',' | ';' | '='
577 _ => return Err(~"Invalid character in path.")
582 if end != 0 && !rawurl.starts_with("/") {
583 return Err(~"Non-empty path must begin with\
584 '/' in presence of authority.");
588 return Ok((decode_component(rawurl.slice(0, end)),
589 rawurl.slice(end, len).to_owned()));
592 // returns the parsed query and the fragment, if present
593 fn get_query_fragment(rawurl: &str) ->
594 Result<(Query, Option<~str>), ~str> {
595 if !rawurl.starts_with("?") {
596 if rawurl.starts_with("#") {
597 let f = decode_component(rawurl.slice(
600 return Ok((~[], Some(f)));
602 return Ok((~[], None));
605 let (q, r) = split_char_first(rawurl.slice(1, rawurl.len()), '#');
606 let f = if r.len() != 0 {
607 Some(decode_component(r)) } else { None };
608 return Ok((query_from_str(q), f));
612 * Parse a `str` to a `url`
616 * `rawurl` - a string representing a full url, including scheme.
620 * a `url` that contains the parsed representation of the url.
624 pub fn from_str(rawurl: &str) -> Result<Url, ~str> {
626 let (scheme, rest) = match get_scheme(rawurl) {
628 Err(e) => return Err(e),
632 let (userinfo, host, port, rest) = match get_authority(rest) {
634 Err(e) => return Err(e),
638 let has_authority = if host == ~"" { false } else { true };
639 let (path, rest) = match get_path(rest, has_authority) {
641 Err(e) => return Err(e),
644 // query and fragment
645 let (query, fragment) = match get_query_fragment(rest) {
647 Err(e) => return Err(e),
650 Ok(Url::new(scheme, userinfo, host, port, path, query, fragment))
653 impl FromStr for Url {
654 fn from_str(s: &str) -> Option<Url> {
656 Ok(url) => Some(url),
663 * Format a `url` as a string
671 * a `str` that contains the formatted url. Note that this will usually
672 * be an inverse of `from_str` but might strip out unneeded separators.
673 * for example, "http://somehost.com?", when parsed and formatted, will
674 * result in just "http://somehost.com".
677 pub fn to_str(url: &Url) -> ~str {
678 let user = match url.user {
679 Some(ref user) => userinfo_to_str(user),
683 let authority = if url.host.is_empty() {
686 fmt!("//%s%s", user, url.host)
689 let query = if url.query.is_empty() {
692 fmt!("?%s", query_to_str(&url.query))
695 let fragment = match url.fragment {
696 Some(ref fragment) => fmt!("#%s", encode_component(*fragment)),
700 fmt!("%s:%s%s%s%s", url.scheme, authority, url.path, query, fragment)
704 pub fn to_str(&self) -> ~str {
709 impl IterBytes for Url {
710 fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
711 self.to_str().iter_bytes(lsb0, f)
715 // Put a few tests outside of the 'test' module so they can test the internal
716 // functions and those functions don't need 'pub'
719 fn test_split_char_first() {
720 let (u,v) = split_char_first("hello, sweet world", ',');
721 assert_eq!(u, ~"hello");
722 assert_eq!(v, ~" sweet world");
724 let (u,v) = split_char_first("hello sweet world", ',');
725 assert_eq!(u, ~"hello sweet world");
730 fn test_get_authority() {
731 let (u, h, p, r) = get_authority(
732 "//user:pass@rust-lang.org/something").unwrap();
733 assert_eq!(u, Some(UserInfo::new(~"user", Some(~"pass"))));
734 assert_eq!(h, ~"rust-lang.org");
735 assert!(p.is_none());
736 assert_eq!(r, ~"/something");
738 let (u, h, p, r) = get_authority(
739 "//rust-lang.org:8000?something").unwrap();
740 assert!(u.is_none());
741 assert_eq!(h, ~"rust-lang.org");
742 assert_eq!(p, Some(~"8000"));
743 assert_eq!(r, ~"?something");
745 let (u, h, p, r) = get_authority(
746 "//rust-lang.org#blah").unwrap();
747 assert!(u.is_none());
748 assert_eq!(h, ~"rust-lang.org");
749 assert!(p.is_none());
750 assert_eq!(r, ~"#blah");
753 let (_, h, _, _) = get_authority(
754 "//2001:0db8:85a3:0042:0000:8a2e:0370:7334#blah").unwrap();
755 assert_eq!(h, ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334");
757 let (_, h, p, _) = get_authority(
758 "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah").unwrap();
759 assert_eq!(h, ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334");
760 assert_eq!(p, Some(~"8000"));
762 let (u, h, p, _) = get_authority(
763 "//us:p@2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah"
765 assert_eq!(u, Some(UserInfo::new(~"us", Some(~"p"))));
766 assert_eq!(h, ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334");
767 assert_eq!(p, Some(~"8000"));
769 // invalid authorities;
770 assert!(get_authority("//user:pass@rust-lang:something").is_err());
771 assert!(get_authority("//user@rust-lang:something:/path").is_err());
772 assert!(get_authority(
773 "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:800a").is_err());
774 assert!(get_authority(
775 "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000:00").is_err());
777 // these parse as empty, because they don't start with '//'
778 let (_, h, _, _) = get_authority("user:pass@rust-lang").unwrap();
780 let (_, h, _, _) = get_authority("rust-lang.org").unwrap();
786 let (p, r) = get_path("/something+%20orother", true).unwrap();
787 assert_eq!(p, ~"/something+ orother");
789 let (p, r) = get_path("test@email.com#fragment", false).unwrap();
790 assert_eq!(p, ~"test@email.com");
791 assert_eq!(r, ~"#fragment");
792 let (p, r) = get_path("/gen/:addr=?q=v", false).unwrap();
793 assert_eq!(p, ~"/gen/:addr=");
794 assert_eq!(r, ~"?q=v");
797 assert!(get_path("something?q", true).is_err());
805 use std::hashmap::HashMap;
808 fn test_url_parse() {
809 let url = ~"http://user:pass@rust-lang.org/doc?s=v#something";
811 let up = from_str(url);
813 assert!(u.scheme == ~"http");
814 let userinfo = u.user.get_ref();
815 assert!(userinfo.user == ~"user");
816 assert!(userinfo.pass.get_ref() == &~"pass");
817 assert!(u.host == ~"rust-lang.org");
818 assert!(u.path == ~"/doc");
819 assert!(u.query == ~[(~"s", ~"v")]);
820 assert!(u.fragment.get_ref() == &~"something");
824 fn test_url_parse_host_slash() {
825 let urlstr = ~"http://0.42.42.42/";
826 let url = from_str(urlstr).unwrap();
827 assert!(url.host == ~"0.42.42.42");
828 assert!(url.path == ~"/");
832 fn test_url_with_underscores() {
833 let urlstr = ~"http://dotcom.com/file_name.html";
834 let url = from_str(urlstr).unwrap();
835 assert!(url.path == ~"/file_name.html");
839 fn test_url_with_dashes() {
840 let urlstr = ~"http://dotcom.com/file-name.html";
841 let url = from_str(urlstr).unwrap();
842 assert!(url.path == ~"/file-name.html");
846 fn test_no_scheme() {
847 assert!(get_scheme("noschemehere.html").is_err());
851 fn test_invalid_scheme_errors() {
852 assert!(from_str("99://something").is_err());
853 assert!(from_str("://something").is_err());
857 fn test_full_url_parse_and_format() {
858 let url = ~"http://user:pass@rust-lang.org/doc?s=v#something";
859 assert_eq!(from_str(url).unwrap().to_str(), url);
863 fn test_userless_url_parse_and_format() {
864 let url = ~"http://rust-lang.org/doc?s=v#something";
865 assert_eq!(from_str(url).unwrap().to_str(), url);
869 fn test_queryless_url_parse_and_format() {
870 let url = ~"http://user:pass@rust-lang.org/doc#something";
871 assert_eq!(from_str(url).unwrap().to_str(), url);
875 fn test_empty_query_url_parse_and_format() {
876 let url = ~"http://user:pass@rust-lang.org/doc?#something";
877 let should_be = ~"http://user:pass@rust-lang.org/doc#something";
878 assert_eq!(from_str(url).unwrap().to_str(), should_be);
882 fn test_fragmentless_url_parse_and_format() {
883 let url = ~"http://user:pass@rust-lang.org/doc?q=v";
884 assert_eq!(from_str(url).unwrap().to_str(), url);
888 fn test_minimal_url_parse_and_format() {
889 let url = ~"http://rust-lang.org/doc";
890 assert_eq!(from_str(url).unwrap().to_str(), url);
894 fn test_scheme_host_only_url_parse_and_format() {
895 let url = ~"http://rust-lang.org";
896 assert_eq!(from_str(url).unwrap().to_str(), url);
900 fn test_pathless_url_parse_and_format() {
901 let url = ~"http://user:pass@rust-lang.org?q=v#something";
902 assert_eq!(from_str(url).unwrap().to_str(), url);
906 fn test_scheme_host_fragment_only_url_parse_and_format() {
907 let url = ~"http://rust-lang.org#something";
908 assert_eq!(from_str(url).unwrap().to_str(), url);
912 fn test_url_component_encoding() {
913 let url = ~"http://rust-lang.org/doc%20uments?ba%25d%20=%23%26%2B";
914 let u = from_str(url).unwrap();
915 assert!(u.path == ~"/doc uments");
916 assert!(u.query == ~[(~"ba%d ", ~"#&+")]);
920 fn test_url_without_authority() {
921 let url = ~"mailto:test@email.com";
922 assert_eq!(from_str(url).unwrap().to_str(), url);
927 assert_eq!(encode(""), ~"");
928 assert_eq!(encode("http://example.com"), ~"http://example.com");
929 assert_eq!(encode("foo bar% baz"), ~"foo%20bar%25%20baz");
930 assert_eq!(encode(" "), ~"%20");
931 assert_eq!(encode("!"), ~"!");
932 assert_eq!(encode("\""), ~"\"");
933 assert_eq!(encode("#"), ~"#");
934 assert_eq!(encode("$"), ~"$");
935 assert_eq!(encode("%"), ~"%25");
936 assert_eq!(encode("&"), ~"&");
937 assert_eq!(encode("'"), ~"%27");
938 assert_eq!(encode("("), ~"(");
939 assert_eq!(encode(")"), ~")");
940 assert_eq!(encode("*"), ~"*");
941 assert_eq!(encode("+"), ~"+");
942 assert_eq!(encode(","), ~",");
943 assert_eq!(encode("/"), ~"/");
944 assert_eq!(encode(":"), ~":");
945 assert_eq!(encode(";"), ~";");
946 assert_eq!(encode("="), ~"=");
947 assert_eq!(encode("?"), ~"?");
948 assert_eq!(encode("@"), ~"@");
949 assert_eq!(encode("["), ~"[");
950 assert_eq!(encode("]"), ~"]");
954 fn test_encode_component() {
955 assert_eq!(encode_component(""), ~"");
956 assert!(encode_component("http://example.com") ==
957 ~"http%3A%2F%2Fexample.com");
958 assert!(encode_component("foo bar% baz") ==
959 ~"foo%20bar%25%20baz");
960 assert_eq!(encode_component(" "), ~"%20");
961 assert_eq!(encode_component("!"), ~"%21");
962 assert_eq!(encode_component("#"), ~"%23");
963 assert_eq!(encode_component("$"), ~"%24");
964 assert_eq!(encode_component("%"), ~"%25");
965 assert_eq!(encode_component("&"), ~"%26");
966 assert_eq!(encode_component("'"), ~"%27");
967 assert_eq!(encode_component("("), ~"%28");
968 assert_eq!(encode_component(")"), ~"%29");
969 assert_eq!(encode_component("*"), ~"%2A");
970 assert_eq!(encode_component("+"), ~"%2B");
971 assert_eq!(encode_component(","), ~"%2C");
972 assert_eq!(encode_component("/"), ~"%2F");
973 assert_eq!(encode_component(":"), ~"%3A");
974 assert_eq!(encode_component(";"), ~"%3B");
975 assert_eq!(encode_component("="), ~"%3D");
976 assert_eq!(encode_component("?"), ~"%3F");
977 assert_eq!(encode_component("@"), ~"%40");
978 assert_eq!(encode_component("["), ~"%5B");
979 assert_eq!(encode_component("]"), ~"%5D");
984 assert_eq!(decode(""), ~"");
985 assert_eq!(decode("abc/def 123"), ~"abc/def 123");
986 assert_eq!(decode("abc%2Fdef%20123"), ~"abc%2Fdef 123");
987 assert_eq!(decode("%20"), ~" ");
988 assert_eq!(decode("%21"), ~"%21");
989 assert_eq!(decode("%22"), ~"%22");
990 assert_eq!(decode("%23"), ~"%23");
991 assert_eq!(decode("%24"), ~"%24");
992 assert_eq!(decode("%25"), ~"%");
993 assert_eq!(decode("%26"), ~"%26");
994 assert_eq!(decode("%27"), ~"'");
995 assert_eq!(decode("%28"), ~"%28");
996 assert_eq!(decode("%29"), ~"%29");
997 assert_eq!(decode("%2A"), ~"%2A");
998 assert_eq!(decode("%2B"), ~"%2B");
999 assert_eq!(decode("%2C"), ~"%2C");
1000 assert_eq!(decode("%2F"), ~"%2F");
1001 assert_eq!(decode("%3A"), ~"%3A");
1002 assert_eq!(decode("%3B"), ~"%3B");
1003 assert_eq!(decode("%3D"), ~"%3D");
1004 assert_eq!(decode("%3F"), ~"%3F");
1005 assert_eq!(decode("%40"), ~"%40");
1006 assert_eq!(decode("%5B"), ~"%5B");
1007 assert_eq!(decode("%5D"), ~"%5D");
1011 fn test_decode_component() {
1012 assert_eq!(decode_component(""), ~"");
1013 assert_eq!(decode_component("abc/def 123"), ~"abc/def 123");
1014 assert_eq!(decode_component("abc%2Fdef%20123"), ~"abc/def 123");
1015 assert_eq!(decode_component("%20"), ~" ");
1016 assert_eq!(decode_component("%21"), ~"!");
1017 assert_eq!(decode_component("%22"), ~"\"");
1018 assert_eq!(decode_component("%23"), ~"#");
1019 assert_eq!(decode_component("%24"), ~"$");
1020 assert_eq!(decode_component("%25"), ~"%");
1021 assert_eq!(decode_component("%26"), ~"&");
1022 assert_eq!(decode_component("%27"), ~"'");
1023 assert_eq!(decode_component("%28"), ~"(");
1024 assert_eq!(decode_component("%29"), ~")");
1025 assert_eq!(decode_component("%2A"), ~"*");
1026 assert_eq!(decode_component("%2B"), ~"+");
1027 assert_eq!(decode_component("%2C"), ~",");
1028 assert_eq!(decode_component("%2F"), ~"/");
1029 assert_eq!(decode_component("%3A"), ~":");
1030 assert_eq!(decode_component("%3B"), ~";");
1031 assert_eq!(decode_component("%3D"), ~"=");
1032 assert_eq!(decode_component("%3F"), ~"?");
1033 assert_eq!(decode_component("%40"), ~"@");
1034 assert_eq!(decode_component("%5B"), ~"[");
1035 assert_eq!(decode_component("%5D"), ~"]");
1039 fn test_encode_form_urlencoded() {
1040 let mut m = HashMap::new();
1041 assert_eq!(encode_form_urlencoded(&m), ~"");
1044 m.insert(~"foo", ~[]);
1045 assert_eq!(encode_form_urlencoded(&m), ~"");
1047 let mut m = HashMap::new();
1048 m.insert(~"foo", ~[~"bar", ~"123"]);
1049 assert_eq!(encode_form_urlencoded(&m), ~"foo=bar&foo=123");
1051 let mut m = HashMap::new();
1052 m.insert(~"foo bar", ~[~"abc", ~"12 = 34"]);
1053 assert!(encode_form_urlencoded(&m) ==
1054 ~"foo+bar=abc&foo+bar=12+%3D+34");
1058 fn test_decode_form_urlencoded() {
1059 // FIXME #4449: Commented out because this causes an ICE, but only
1062 assert_eq!(decode_form_urlencoded([]).len(), 0);
1064 let s = "a=1&foo+bar=abc&foo+bar=12+%3D+34".as_bytes();
1065 let form = decode_form_urlencoded(s);
1066 assert_eq!(form.len(), 2);
1067 assert_eq!(form.get_ref(&~"a"), &~[~"1"]);
1068 assert_eq!(form.get_ref(&~"foo bar"), &~[~"abc", ~"12 = 34"]);