Update for latest rust
Tracks rust nightly. 7 tests fail -- still finding source
This commit is contained in:
		| @@ -22,14 +22,14 @@ fn main() { | |||||||
|  |  | ||||||
|     let mut res = match client.get(url).send() { |     let mut res = match client.get(url).send() { | ||||||
|         Ok(res) => res, |         Ok(res) => res, | ||||||
|         Err(err) => panic!("Failed to connect: {}", err) |         Err(err) => panic!("Failed to connect: {:?}", err) | ||||||
|     }; |     }; | ||||||
|  |  | ||||||
|     println!("Response: {}", res.status); |     println!("Response: {}", res.status); | ||||||
|     println!("Headers:\n{}", res.headers); |     println!("Headers:\n{}", res.headers); | ||||||
|     match copy(&mut res, &mut stdout()) { |     match copy(&mut res, &mut stdout()) { | ||||||
|         Ok(..) => (), |         Ok(..) => (), | ||||||
|         Err(e) => panic!("Stream failure: {}", e) |         Err(e) => panic!("Stream failure: {:?}", e) | ||||||
|     }; |     }; | ||||||
|  |  | ||||||
| } | } | ||||||
|   | |||||||
| @@ -63,6 +63,7 @@ impl Client<HttpConnector> { | |||||||
|  |  | ||||||
| } | } | ||||||
|  |  | ||||||
|  | #[old_impl_check] | ||||||
| impl<C: NetworkConnector<S>, S: NetworkStream> Client<C> { | impl<C: NetworkConnector<S>, S: NetworkStream> Client<C> { | ||||||
|  |  | ||||||
|     /// Create a new client with a specific connector. |     /// Create a new client with a specific connector. | ||||||
| @@ -162,7 +163,7 @@ impl<'a, U: IntoUrl, C: NetworkConnector<S>, S: NetworkStream> RequestBuilder<'a | |||||||
|     pub fn send(self) -> HttpResult<Response> { |     pub fn send(self) -> HttpResult<Response> { | ||||||
|         let RequestBuilder { client, method, url, headers, body } = self; |         let RequestBuilder { client, method, url, headers, body } = self; | ||||||
|         let mut url = try!(url.into_url()); |         let mut url = try!(url.into_url()); | ||||||
|         debug!("client.request {} {}", method, url); |         debug!("client.request {:?} {:?}", method, url); | ||||||
|  |  | ||||||
|         let can_have_body = match &method { |         let can_have_body = match &method { | ||||||
|             &Method::Get | &Method::Head => false, |             &Method::Get | &Method::Head => false, | ||||||
| @@ -193,13 +194,13 @@ impl<'a, U: IntoUrl, C: NetworkConnector<S>, S: NetworkStream> RequestBuilder<'a | |||||||
|             if res.status.class() != Redirection { |             if res.status.class() != Redirection { | ||||||
|                 return Ok(res) |                 return Ok(res) | ||||||
|             } |             } | ||||||
|             debug!("redirect code {} for {}", res.status, url); |             debug!("redirect code {:?} for {:?}", res.status, url); | ||||||
|  |  | ||||||
|             let loc = { |             let loc = { | ||||||
|                 // punching borrowck here |                 // punching borrowck here | ||||||
|                 let loc = match res.headers.get::<Location>() { |                 let loc = match res.headers.get::<Location>() { | ||||||
|                     Some(&Location(ref loc)) => { |                     Some(&Location(ref loc)) => { | ||||||
|                         Some(UrlParser::new().base_url(&url).parse(loc[])) |                         Some(UrlParser::new().base_url(&url).parse(&loc[])) | ||||||
|                     } |                     } | ||||||
|                     None => { |                     None => { | ||||||
|                         debug!("no Location header"); |                         debug!("no Location header"); | ||||||
| @@ -217,7 +218,7 @@ impl<'a, U: IntoUrl, C: NetworkConnector<S>, S: NetworkStream> RequestBuilder<'a | |||||||
|                     inspect!("Location", u) |                     inspect!("Location", u) | ||||||
|                 }, |                 }, | ||||||
|                 Err(e) => { |                 Err(e) => { | ||||||
|                     debug!("Location header had invalid URI: {}", e); |                     debug!("Location header had invalid URI: {:?}", e); | ||||||
|                     return Ok(res); |                     return Ok(res); | ||||||
|                 } |                 } | ||||||
|             }; |             }; | ||||||
| @@ -242,13 +243,13 @@ pub enum Body<'a> { | |||||||
|     /// A Reader does not necessarily know it's size, so it is chunked. |     /// A Reader does not necessarily know it's size, so it is chunked. | ||||||
|     ChunkedBody(&'a mut (Reader + 'a)), |     ChunkedBody(&'a mut (Reader + 'a)), | ||||||
|     /// For Readers that can know their size, like a `File`. |     /// For Readers that can know their size, like a `File`. | ||||||
|     SizedBody(&'a mut (Reader + 'a), uint), |     SizedBody(&'a mut (Reader + 'a), usize), | ||||||
|     /// A String has a size, and uses Content-Length. |     /// A String has a size, and uses Content-Length. | ||||||
|     BufBody(&'a [u8] , uint), |     BufBody(&'a [u8] , usize), | ||||||
| } | } | ||||||
|  |  | ||||||
| impl<'a> Body<'a> { | impl<'a> Body<'a> { | ||||||
|     fn size(&self) -> Option<uint> { |     fn size(&self) -> Option<usize> { | ||||||
|         match *self { |         match *self { | ||||||
|             Body::SizedBody(_, len) | Body::BufBody(_, len) => Some(len), |             Body::SizedBody(_, len) | Body::BufBody(_, len) => Some(len), | ||||||
|             _ => None |             _ => None | ||||||
| @@ -258,7 +259,7 @@ impl<'a> Body<'a> { | |||||||
|  |  | ||||||
| impl<'a> Reader for Body<'a> { | impl<'a> Reader for Body<'a> { | ||||||
|     #[inline] |     #[inline] | ||||||
|     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { |     fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { | ||||||
|         match *self { |         match *self { | ||||||
|             Body::ChunkedBody(ref mut r) => r.read(buf), |             Body::ChunkedBody(ref mut r) => r.read(buf), | ||||||
|             Body::SizedBody(ref mut r, _) => r.read(buf), |             Body::SizedBody(ref mut r, _) => r.read(buf), | ||||||
| @@ -343,12 +344,12 @@ fn get_host_and_port(url: &Url) -> HttpResult<(String, Port)> { | |||||||
|         Some(host) => host, |         Some(host) => host, | ||||||
|         None => return Err(HttpUriError(UrlError::EmptyHost)) |         None => return Err(HttpUriError(UrlError::EmptyHost)) | ||||||
|     }; |     }; | ||||||
|     debug!("host={}", host); |     debug!("host={:?}", host); | ||||||
|     let port = match url.port_or_default() { |     let port = match url.port_or_default() { | ||||||
|         Some(port) => port, |         Some(port) => port, | ||||||
|         None => return Err(HttpUriError(UrlError::InvalidPort)) |         None => return Err(HttpUriError(UrlError::InvalidPort)) | ||||||
|     }; |     }; | ||||||
|     debug!("port={}", port); |     debug!("port={:?}", port); | ||||||
|     Ok((host, port)) |     Ok((host, port)) | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -47,10 +47,10 @@ impl Request<Fresh> { | |||||||
|  |  | ||||||
|     /// Create a new client request with a specific underlying NetworkStream. |     /// Create a new client request with a specific underlying NetworkStream. | ||||||
|     pub fn with_connector<C: NetworkConnector<S>, S: NetworkStream>(method: method::Method, url: Url, connector: &mut C) -> HttpResult<Request<Fresh>> { |     pub fn with_connector<C: NetworkConnector<S>, S: NetworkStream>(method: method::Method, url: Url, connector: &mut C) -> HttpResult<Request<Fresh>> { | ||||||
|         debug!("{} {}", method, url); |         debug!("{:?} {:?}", method, url); | ||||||
|         let (host, port) = try!(get_host_and_port(&url)); |         let (host, port) = try!(get_host_and_port(&url)); | ||||||
|  |  | ||||||
|         let stream: S = try!(connector.connect(host[], port, &*url.scheme)); |         let stream: S = try!(connector.connect(&host[], port, &*url.scheme)); | ||||||
|         let stream = ThroughWriter(BufferedWriter::new(box stream as Box<NetworkStream + Send>)); |         let stream = ThroughWriter(BufferedWriter::new(box stream as Box<NetworkStream + Send>)); | ||||||
|  |  | ||||||
|         let mut headers = Headers::new(); |         let mut headers = Headers::new(); | ||||||
| @@ -110,17 +110,17 @@ impl Request<Fresh> { | |||||||
|         //TODO: this needs a test |         //TODO: this needs a test | ||||||
|         if let Some(ref q) = self.url.query { |         if let Some(ref q) = self.url.query { | ||||||
|             uri.push('?'); |             uri.push('?'); | ||||||
|             uri.push_str(q[]); |             uri.push_str(&q[]); | ||||||
|         } |         } | ||||||
|  |  | ||||||
|         debug!("writing head: {} {} {}", self.method, uri, self.version); |         debug!("writing head: {:?} {:?} {:?}", self.method, uri, self.version); | ||||||
|         try!(write!(&mut self.body, "{} {} {}{}", |         try!(write!(&mut self.body, "{} {} {}{}", | ||||||
|                     self.method, uri, self.version, LINE_ENDING)); |                     self.method, uri, self.version, LINE_ENDING)); | ||||||
|  |  | ||||||
|  |  | ||||||
|         let stream = match self.method { |         let stream = match self.method { | ||||||
|             Get | Head => { |             Get | Head => { | ||||||
|                 debug!("headers [\n{}]", self.headers); |                 debug!("headers [\n{:?}]", self.headers); | ||||||
|                 try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING)); |                 try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING)); | ||||||
|                 EmptyWriter(self.body.unwrap()) |                 EmptyWriter(self.body.unwrap()) | ||||||
|             }, |             }, | ||||||
| @@ -139,7 +139,7 @@ impl Request<Fresh> { | |||||||
|                 // cant do in match above, thanks borrowck |                 // cant do in match above, thanks borrowck | ||||||
|                 if chunked { |                 if chunked { | ||||||
|                     let encodings = match self.headers.get_mut::<common::TransferEncoding>() { |                     let encodings = match self.headers.get_mut::<common::TransferEncoding>() { | ||||||
|                         Some(&common::TransferEncoding(ref mut encodings)) => { |                         Some(&mut common::TransferEncoding(ref mut encodings)) => { | ||||||
|                             //TODO: check if chunked is already in encodings. use HashSet? |                             //TODO: check if chunked is already in encodings. use HashSet? | ||||||
|                             encodings.push(common::transfer_encoding::Encoding::Chunked); |                             encodings.push(common::transfer_encoding::Encoding::Chunked); | ||||||
|                             false |                             false | ||||||
| @@ -153,7 +153,7 @@ impl Request<Fresh> { | |||||||
|                     } |                     } | ||||||
|                 } |                 } | ||||||
|  |  | ||||||
|                 debug!("headers [\n{}]", self.headers); |                 debug!("headers [\n{:?}]", self.headers); | ||||||
|                 try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING)); |                 try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING)); | ||||||
|  |  | ||||||
|                 if chunked { |                 if chunked { | ||||||
| @@ -218,7 +218,7 @@ mod tests { | |||||||
|         let stream = *req.body.end().unwrap() |         let stream = *req.body.end().unwrap() | ||||||
|             .into_inner().downcast::<MockStream>().ok().unwrap(); |             .into_inner().downcast::<MockStream>().ok().unwrap(); | ||||||
|         let bytes = stream.write.into_inner(); |         let bytes = stream.write.into_inner(); | ||||||
|         let s = from_utf8(bytes[]).unwrap(); |         let s = from_utf8(&bytes[]).unwrap(); | ||||||
|         assert!(!s.contains("Content-Length:")); |         assert!(!s.contains("Content-Length:")); | ||||||
|         assert!(!s.contains("Transfer-Encoding:")); |         assert!(!s.contains("Transfer-Encoding:")); | ||||||
|     } |     } | ||||||
| @@ -232,7 +232,7 @@ mod tests { | |||||||
|         let stream = *req.body.end().unwrap() |         let stream = *req.body.end().unwrap() | ||||||
|             .into_inner().downcast::<MockStream>().ok().unwrap(); |             .into_inner().downcast::<MockStream>().ok().unwrap(); | ||||||
|         let bytes = stream.write.into_inner(); |         let bytes = stream.write.into_inner(); | ||||||
|         let s = from_utf8(bytes[]).unwrap(); |         let s = from_utf8(&bytes[]).unwrap(); | ||||||
|         assert!(!s.contains("Content-Length:")); |         assert!(!s.contains("Content-Length:")); | ||||||
|         assert!(!s.contains("Transfer-Encoding:")); |         assert!(!s.contains("Transfer-Encoding:")); | ||||||
|     } |     } | ||||||
|   | |||||||
| @@ -35,16 +35,16 @@ impl Response { | |||||||
|             Some(status) => status, |             Some(status) => status, | ||||||
|             None => return Err(HttpStatusError) |             None => return Err(HttpStatusError) | ||||||
|         }; |         }; | ||||||
|         debug!("{} {}", version, status); |         debug!("{:?} {:?}", version, status); | ||||||
|  |  | ||||||
|         let headers = try!(header::Headers::from_raw(&mut stream)); |         let headers = try!(header::Headers::from_raw(&mut stream)); | ||||||
|         debug!("Headers: [\n{}]", headers); |         debug!("Headers: [\n{:?}]", headers); | ||||||
|  |  | ||||||
|         let body = if headers.has::<TransferEncoding>() { |         let body = if headers.has::<TransferEncoding>() { | ||||||
|             match headers.get::<TransferEncoding>() { |             match headers.get::<TransferEncoding>() { | ||||||
|                 Some(&TransferEncoding(ref codings)) => { |                 Some(&TransferEncoding(ref codings)) => { | ||||||
|                     if codings.len() > 1 { |                     if codings.len() > 1 { | ||||||
|                         debug!("TODO: #2 handle other codings: {}", codings); |                         debug!("TODO: #2 handle other codings: {:?}", codings); | ||||||
|                     }; |                     }; | ||||||
|  |  | ||||||
|                     if codings.contains(&Chunked) { |                     if codings.contains(&Chunked) { | ||||||
| @@ -88,7 +88,7 @@ impl Response { | |||||||
|  |  | ||||||
| impl Reader for Response { | impl Reader for Response { | ||||||
|     #[inline] |     #[inline] | ||||||
|     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { |     fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { | ||||||
|         self.body.read(buf) |         self.body.read(buf) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|   | |||||||
| @@ -28,7 +28,7 @@ use mime; | |||||||
| #[derive(Clone, PartialEq, Show)] | #[derive(Clone, PartialEq, Show)] | ||||||
| pub struct Accept(pub Vec<shared::QualityItem<mime::Mime>>); | pub struct Accept(pub Vec<shared::QualityItem<mime::Mime>>); | ||||||
|  |  | ||||||
| deref!(Accept -> Vec<shared::QualityItem<mime::Mime>>); | deref!(Accept => Vec<shared::QualityItem<mime::Mime>>); | ||||||
|  |  | ||||||
| impl header::Header for Accept { | impl header::Header for Accept { | ||||||
|     fn header_name(_: Option<Accept>) -> &'static str { |     fn header_name(_: Option<Accept>) -> &'static str { | ||||||
| @@ -43,7 +43,7 @@ impl header::Header for Accept { | |||||||
|  |  | ||||||
| impl header::HeaderFormat for Accept { | impl header::HeaderFormat for Accept { | ||||||
|     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         shared::fmt_comma_delimited(fmt, self[]) |         shared::fmt_comma_delimited(fmt, &self[]) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -10,7 +10,7 @@ use header::shared; | |||||||
| #[derive(Clone, PartialEq, Show)] | #[derive(Clone, PartialEq, Show)] | ||||||
| pub struct AcceptEncoding(pub Vec<shared::QualityItem<shared::Encoding>>); | pub struct AcceptEncoding(pub Vec<shared::QualityItem<shared::Encoding>>); | ||||||
|  |  | ||||||
| deref!(AcceptEncoding -> Vec<shared::QualityItem<shared::Encoding>>); | deref!(AcceptEncoding => Vec<shared::QualityItem<shared::Encoding>>); | ||||||
|  |  | ||||||
| impl header::Header for AcceptEncoding { | impl header::Header for AcceptEncoding { | ||||||
|     fn header_name(_: Option<AcceptEncoding>) -> &'static str { |     fn header_name(_: Option<AcceptEncoding>) -> &'static str { | ||||||
| @@ -24,7 +24,7 @@ impl header::Header for AcceptEncoding { | |||||||
|  |  | ||||||
| impl header::HeaderFormat for AcceptEncoding { | impl header::HeaderFormat for AcceptEncoding { | ||||||
|     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         shared::fmt_comma_delimited(fmt, self[]) |         shared::fmt_comma_delimited(fmt, &self[]) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -19,7 +19,7 @@ impl header::Header for AccessControlAllowOrigin { | |||||||
|  |  | ||||||
|     fn parse_header(raw: &[Vec<u8>]) -> Option<AccessControlAllowOrigin> { |     fn parse_header(raw: &[Vec<u8>]) -> Option<AccessControlAllowOrigin> { | ||||||
|         if raw.len() == 1 { |         if raw.len() == 1 { | ||||||
|             match str::from_utf8(unsafe { raw[].get_unchecked(0)[] }) { |             match str::from_utf8(unsafe { &raw[].get_unchecked(0)[] }) { | ||||||
|                 Ok(s) => { |                 Ok(s) => { | ||||||
|                     if s == "*" { |                     if s == "*" { | ||||||
|                         Some(AccessControlAllowOrigin::AllowStar) |                         Some(AccessControlAllowOrigin::AllowStar) | ||||||
|   | |||||||
| @@ -9,7 +9,7 @@ use header::shared::util::{from_comma_delimited, fmt_comma_delimited}; | |||||||
| #[derive(Clone, PartialEq, Show)] | #[derive(Clone, PartialEq, Show)] | ||||||
| pub struct Allow(pub Vec<Method>); | pub struct Allow(pub Vec<Method>); | ||||||
|  |  | ||||||
| deref!(Allow -> Vec<Method>); | deref!(Allow => Vec<Method>); | ||||||
|  |  | ||||||
| impl Header for Allow { | impl Header for Allow { | ||||||
|     fn header_name(_: Option<Allow>) -> &'static str { |     fn header_name(_: Option<Allow>) -> &'static str { | ||||||
| @@ -23,7 +23,7 @@ impl Header for Allow { | |||||||
|  |  | ||||||
| impl HeaderFormat for Allow { | impl HeaderFormat for Allow { | ||||||
|     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         fmt_comma_delimited(fmt, self[]) |         fmt_comma_delimited(fmt, &self[]) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -29,7 +29,7 @@ impl<S: Scheme> Header for Authorization<S> { | |||||||
|  |  | ||||||
|     fn parse_header(raw: &[Vec<u8>]) -> Option<Authorization<S>> { |     fn parse_header(raw: &[Vec<u8>]) -> Option<Authorization<S>> { | ||||||
|         if raw.len() == 1 { |         if raw.len() == 1 { | ||||||
|             match (from_utf8(unsafe { raw[].get_unchecked(0)[] }), Scheme::scheme(None::<S>)) { |             match (from_utf8(unsafe { &raw[].get_unchecked(0)[] }), Scheme::scheme(None::<S>)) { | ||||||
|                 (Ok(header), Some(scheme)) |                 (Ok(header), Some(scheme)) | ||||||
|                     if header.starts_with(scheme) && header.len() > scheme.len() + 1 => { |                     if header.starts_with(scheme) && header.len() > scheme.len() + 1 => { | ||||||
|                     header[scheme.len() + 1..].parse::<S>().map(|s| Authorization(s)) |                     header[scheme.len() + 1..].parse::<S>().map(|s| Authorization(s)) | ||||||
| @@ -96,7 +96,7 @@ impl Scheme for Basic { | |||||||
|         let mut text = self.username.clone(); |         let mut text = self.username.clone(); | ||||||
|         text.push(':'); |         text.push(':'); | ||||||
|         if let Some(ref pass) = self.password { |         if let Some(ref pass) = self.password { | ||||||
|             text.push_str(pass[]); |             text.push_str(&pass[]); | ||||||
|         } |         } | ||||||
|         text.as_bytes().to_base64(Config { |         text.as_bytes().to_base64(Config { | ||||||
|             char_set: Standard, |             char_set: Standard, | ||||||
| @@ -112,7 +112,7 @@ impl FromStr for Basic { | |||||||
|         match s.from_base64() { |         match s.from_base64() { | ||||||
|             Ok(decoded) => match String::from_utf8(decoded) { |             Ok(decoded) => match String::from_utf8(decoded) { | ||||||
|                 Ok(text) => { |                 Ok(text) => { | ||||||
|                     let mut parts = text[].split(':'); |                     let mut parts = &mut text[].split(':'); | ||||||
|                     let user = match parts.next() { |                     let user = match parts.next() { | ||||||
|                         Some(part) => part.to_string(), |                         Some(part) => part.to_string(), | ||||||
|                         None => return None |                         None => return None | ||||||
| @@ -127,12 +127,12 @@ impl FromStr for Basic { | |||||||
|                     }) |                     }) | ||||||
|                 }, |                 }, | ||||||
|                 Err(e) => { |                 Err(e) => { | ||||||
|                     debug!("Basic::from_utf8 error={}", e); |                     debug!("Basic::from_utf8 error={:?}", e); | ||||||
|                     None |                     None | ||||||
|                 } |                 } | ||||||
|             }, |             }, | ||||||
|             Err(e) => { |             Err(e) => { | ||||||
|                 debug!("Basic::from_base64 error={}", e); |                 debug!("Basic::from_base64 error={:?}", e); | ||||||
|                 None |                 None | ||||||
|             } |             } | ||||||
|         } |         } | ||||||
| @@ -159,7 +159,7 @@ mod tests { | |||||||
|     #[test] |     #[test] | ||||||
|     fn test_raw_auth_parse() { |     fn test_raw_auth_parse() { | ||||||
|         let headers = Headers::from_raw(&mut mem("Authorization: foo bar baz\r\n\r\n")).unwrap(); |         let headers = Headers::from_raw(&mut mem("Authorization: foo bar baz\r\n\r\n")).unwrap(); | ||||||
|         assert_eq!(headers.get::<Authorization<String>>().unwrap().0[], "foo bar baz"); |         assert_eq!(&headers.get::<Authorization<String>>().unwrap().0[], "foo bar baz"); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     #[test] |     #[test] | ||||||
| @@ -180,7 +180,7 @@ mod tests { | |||||||
|     fn test_basic_auth_parse() { |     fn test_basic_auth_parse() { | ||||||
|         let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n\r\n")).unwrap(); |         let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n\r\n")).unwrap(); | ||||||
|         let auth = headers.get::<Authorization<Basic>>().unwrap(); |         let auth = headers.get::<Authorization<Basic>>().unwrap(); | ||||||
|         assert_eq!(auth.0.username[], "Aladdin"); |         assert_eq!(&auth.0.username[], "Aladdin"); | ||||||
|         assert_eq!(auth.0.password, Some("open sesame".to_string())); |         assert_eq!(auth.0.password, Some("open sesame".to_string())); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -7,7 +7,7 @@ use header::shared::util::{from_one_comma_delimited, fmt_comma_delimited}; | |||||||
| #[derive(PartialEq, Clone, Show)] | #[derive(PartialEq, Clone, Show)] | ||||||
| pub struct CacheControl(pub Vec<CacheDirective>); | pub struct CacheControl(pub Vec<CacheDirective>); | ||||||
|  |  | ||||||
| deref!(CacheControl -> Vec<CacheDirective>); | deref!(CacheControl => Vec<CacheDirective>); | ||||||
|  |  | ||||||
| impl Header for CacheControl { | impl Header for CacheControl { | ||||||
|     fn header_name(_: Option<CacheControl>) -> &'static str { |     fn header_name(_: Option<CacheControl>) -> &'static str { | ||||||
| @@ -16,7 +16,7 @@ impl Header for CacheControl { | |||||||
|  |  | ||||||
|     fn parse_header(raw: &[Vec<u8>]) -> Option<CacheControl> { |     fn parse_header(raw: &[Vec<u8>]) -> Option<CacheControl> { | ||||||
|         let directives = raw.iter() |         let directives = raw.iter() | ||||||
|             .filter_map(|line| from_one_comma_delimited(line[])) |             .filter_map(|line| from_one_comma_delimited(&line[])) | ||||||
|             .collect::<Vec<Vec<CacheDirective>>>() |             .collect::<Vec<Vec<CacheDirective>>>() | ||||||
|             .concat(); |             .concat(); | ||||||
|         if directives.len() > 0 { |         if directives.len() > 0 { | ||||||
| @@ -29,7 +29,7 @@ impl Header for CacheControl { | |||||||
|  |  | ||||||
| impl HeaderFormat for CacheControl { | impl HeaderFormat for CacheControl { | ||||||
|     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         fmt_comma_delimited(fmt, self[]) |         fmt_comma_delimited(fmt, &self[]) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -47,11 +47,11 @@ pub enum CacheDirective { | |||||||
|  |  | ||||||
|     // request directives |     // request directives | ||||||
|     /// "max-age=delta" |     /// "max-age=delta" | ||||||
|     MaxAge(uint), |     MaxAge(usize), | ||||||
|     /// "max-stale=delta" |     /// "max-stale=delta" | ||||||
|     MaxStale(uint), |     MaxStale(usize), | ||||||
|     /// "min-fresh=delta" |     /// "min-fresh=delta" | ||||||
|     MinFresh(uint), |     MinFresh(usize), | ||||||
|  |  | ||||||
|     // response directives |     // response directives | ||||||
|     /// "must-revalidate" |     /// "must-revalidate" | ||||||
| @@ -63,13 +63,13 @@ pub enum CacheDirective { | |||||||
|     /// "proxy-revalidate" |     /// "proxy-revalidate" | ||||||
|     ProxyRevalidate, |     ProxyRevalidate, | ||||||
|     /// "s-maxage=delta" |     /// "s-maxage=delta" | ||||||
|     SMaxAge(uint), |     SMaxAge(usize), | ||||||
|  |  | ||||||
|     /// Extension directives. Optionally include an argument. |     /// Extension directives. Optionally include an argument. | ||||||
|     Extension(String, Option<String>) |     Extension(String, Option<String>) | ||||||
| } | } | ||||||
|  |  | ||||||
| impl fmt::Show for CacheDirective { | impl fmt::String for CacheDirective { | ||||||
|     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         use self::CacheDirective::*; |         use self::CacheDirective::*; | ||||||
|         match *self { |         match *self { | ||||||
| @@ -88,13 +88,18 @@ impl fmt::Show for CacheDirective { | |||||||
|             ProxyRevalidate => "proxy-revalidate", |             ProxyRevalidate => "proxy-revalidate", | ||||||
|             SMaxAge(secs) => return write!(f, "s-maxage={}", secs), |             SMaxAge(secs) => return write!(f, "s-maxage={}", secs), | ||||||
|  |  | ||||||
|             Extension(ref name, None) => name[], |             Extension(ref name, None) => &name[], | ||||||
|             Extension(ref name, Some(ref arg)) => return write!(f, "{}={}", name, arg), |             Extension(ref name, Some(ref arg)) => return write!(f, "{}={}", name, arg), | ||||||
|  |  | ||||||
|         }.fmt(f) |         }.fmt(f) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|  | impl fmt::Show for CacheDirective { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  | 		self.to_string().fmt(fmt) | ||||||
|  | 	} | ||||||
|  | } | ||||||
| impl FromStr for CacheDirective { | impl FromStr for CacheDirective { | ||||||
|     fn from_str(s: &str) -> Option<CacheDirective> { |     fn from_str(s: &str) -> Option<CacheDirective> { | ||||||
|         use self::CacheDirective::*; |         use self::CacheDirective::*; | ||||||
| @@ -109,7 +114,7 @@ impl FromStr for CacheDirective { | |||||||
|             "proxy-revalidate" => Some(ProxyRevalidate), |             "proxy-revalidate" => Some(ProxyRevalidate), | ||||||
|             "" => None, |             "" => None, | ||||||
|             _ => match s.find('=') { |             _ => match s.find('=') { | ||||||
|                 Some(idx) if idx+1 < s.len() => match (s[..idx], s[idx+1..].trim_matches('"')) { |                 Some(idx) if idx+1 < s.len() => match (&s[..idx], &s[idx+1..].trim_matches('"')) { | ||||||
|                     ("max-age" , secs) => secs.parse().map(MaxAge), |                     ("max-age" , secs) => secs.parse().map(MaxAge), | ||||||
|                     ("max-stale", secs) => secs.parse().map(MaxStale), |                     ("max-stale", secs) => secs.parse().map(MaxStale), | ||||||
|                     ("min-fresh", secs) => secs.parse().map(MinFresh), |                     ("min-fresh", secs) => secs.parse().map(MinFresh), | ||||||
|   | |||||||
| @@ -9,7 +9,7 @@ pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader}; | |||||||
| #[derive(Clone, PartialEq, Show)] | #[derive(Clone, PartialEq, Show)] | ||||||
| pub struct Connection(pub Vec<ConnectionOption>); | pub struct Connection(pub Vec<ConnectionOption>); | ||||||
|  |  | ||||||
| deref!(Connection -> Vec<ConnectionOption>); | deref!(Connection => Vec<ConnectionOption>); | ||||||
|  |  | ||||||
| /// Values that can be in the `Connection` header. | /// Values that can be in the `Connection` header. | ||||||
| #[derive(Clone, PartialEq)] | #[derive(Clone, PartialEq)] | ||||||
| @@ -39,13 +39,19 @@ impl FromStr for ConnectionOption { | |||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| impl fmt::Show for ConnectionOption { | impl fmt::String for ConnectionOption { | ||||||
|     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         match *self { |         write!(fmt, "{}", match *self { | ||||||
|             KeepAlive => "keep-alive", |             KeepAlive => "keep-alive", | ||||||
|             Close => "close", |             Close => "close", | ||||||
|             ConnectionHeader(ref s) => s.as_slice() |             ConnectionHeader(ref s) => s.as_slice() | ||||||
|         }.fmt(fmt) |         }) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
|  | impl fmt::Show for ConnectionOption { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  | 		self.to_string().fmt(fmt) | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -62,7 +68,7 @@ impl Header for Connection { | |||||||
| impl HeaderFormat for Connection { | impl HeaderFormat for Connection { | ||||||
|     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         let Connection(ref parts) = *self; |         let Connection(ref parts) = *self; | ||||||
|         fmt_comma_delimited(fmt, parts[]) |         fmt_comma_delimited(fmt, &parts[]) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -5,11 +5,11 @@ use header::shared::util::from_one_raw_str; | |||||||
|  |  | ||||||
| /// The `Content-Length` header. | /// The `Content-Length` header. | ||||||
| /// | /// | ||||||
| /// Simply a wrapper around a `uint`. | /// Simply a wrapper around a `usize`. | ||||||
| #[derive(Copy, Clone, PartialEq, Show)] | #[derive(Copy, Clone, PartialEq, Show)] | ||||||
| pub struct ContentLength(pub uint); | pub struct ContentLength(pub usize); | ||||||
|  |  | ||||||
| deref!(ContentLength -> uint); | deref!(ContentLength => usize); | ||||||
|  |  | ||||||
| impl Header for ContentLength { | impl Header for ContentLength { | ||||||
|     fn header_name(_: Option<ContentLength>) -> &'static str { |     fn header_name(_: Option<ContentLength>) -> &'static str { | ||||||
| @@ -32,7 +32,7 @@ impl ContentLength { | |||||||
|     /// Returns the wrapped length. |     /// Returns the wrapped length. | ||||||
|     #[deprecated = "use Deref instead"] |     #[deprecated = "use Deref instead"] | ||||||
|     #[inline] |     #[inline] | ||||||
|     pub fn len(&self) -> uint { |     pub fn len(&self) -> usize { | ||||||
|         **self |         **self | ||||||
|     } |     } | ||||||
| } | } | ||||||
|   | |||||||
| @@ -10,7 +10,7 @@ use mime::Mime; | |||||||
| #[derive(Clone, PartialEq, Show)] | #[derive(Clone, PartialEq, Show)] | ||||||
| pub struct ContentType(pub Mime); | pub struct ContentType(pub Mime); | ||||||
|  |  | ||||||
| deref!(ContentType -> Mime); | deref!(ContentType => Mime); | ||||||
|  |  | ||||||
| impl Header for ContentType { | impl Header for ContentType { | ||||||
|     fn header_name(_: Option<ContentType>) -> &'static str { |     fn header_name(_: Option<ContentType>) -> &'static str { | ||||||
|   | |||||||
| @@ -20,7 +20,7 @@ pub struct Cookies(pub Vec<Cookie>); | |||||||
| unsafe impl Send for Cookies {} | unsafe impl Send for Cookies {} | ||||||
| unsafe impl Sync for Cookies {} | unsafe impl Sync for Cookies {} | ||||||
|  |  | ||||||
| deref!(Cookies -> Vec<Cookie>); | deref!(Cookies => Vec<Cookie>); | ||||||
|  |  | ||||||
| impl Header for Cookies { | impl Header for Cookies { | ||||||
|     fn header_name(_: Option<Cookies>) -> &'static str { |     fn header_name(_: Option<Cookies>) -> &'static str { | ||||||
| @@ -30,7 +30,7 @@ impl Header for Cookies { | |||||||
|     fn parse_header(raw: &[Vec<u8>]) -> Option<Cookies> { |     fn parse_header(raw: &[Vec<u8>]) -> Option<Cookies> { | ||||||
|         let mut cookies = Vec::with_capacity(raw.len()); |         let mut cookies = Vec::with_capacity(raw.len()); | ||||||
|         for cookies_raw in raw.iter() { |         for cookies_raw in raw.iter() { | ||||||
|             match from_utf8(cookies_raw[]) { |             match from_utf8(&cookies_raw[]) { | ||||||
|                 Ok(cookies_str) => { |                 Ok(cookies_str) => { | ||||||
|                     for cookie_str in cookies_str.split(';') { |                     for cookie_str in cookies_str.split(';') { | ||||||
|                         match cookie_str.trim().parse() { |                         match cookie_str.trim().parse() { | ||||||
| @@ -56,7 +56,7 @@ impl HeaderFormat for Cookies { | |||||||
|         let cookies = &self.0; |         let cookies = &self.0; | ||||||
|         let last = cookies.len() - 1; |         let last = cookies.len() - 1; | ||||||
|         for (i, cookie) in cookies.iter().enumerate() { |         for (i, cookie) in cookies.iter().enumerate() { | ||||||
|             try!(cookie.pair().fmt(fmt)); |             try!(write!(fmt, "{}", cookie.pair())); | ||||||
| 			if i < last { | 			if i < last { | ||||||
|                 try!("; ".fmt(fmt)); |                 try!("; ".fmt(fmt)); | ||||||
|             } |             } | ||||||
| @@ -86,7 +86,7 @@ impl Cookies { | |||||||
|  |  | ||||||
| #[test] | #[test] | ||||||
| fn test_parse() { | fn test_parse() { | ||||||
|     let h = Header::parse_header([b"foo=bar; baz=quux".to_vec()][]); |     let h = Header::parse_header(&[b"foo=bar; baz=quux".to_vec()][]); | ||||||
|     let c1 = Cookie::new("foo".to_string(), "bar".to_string()); |     let c1 = Cookie::new("foo".to_string(), "bar".to_string()); | ||||||
|     let c2 = Cookie::new("baz".to_string(), "quux".to_string()); |     let c2 = Cookie::new("baz".to_string(), "quux".to_string()); | ||||||
|     assert_eq!(h, Some(Cookies(vec![c1, c2]))); |     assert_eq!(h, Some(Cookies(vec![c1, c2]))); | ||||||
| @@ -103,7 +103,7 @@ fn test_fmt() { | |||||||
|     let mut headers = Headers::new(); |     let mut headers = Headers::new(); | ||||||
|     headers.set(cookies); |     headers.set(cookies); | ||||||
|  |  | ||||||
|     assert_eq!(headers.to_string()[], "Cookie: foo=bar; baz=quux\r\n"); |     assert_eq!(&headers.to_string()[], "Cookie: foo=bar; baz=quux\r\n"); | ||||||
| } | } | ||||||
|  |  | ||||||
| #[test] | #[test] | ||||||
|   | |||||||
| @@ -10,7 +10,7 @@ use header::shared::time::tm_from_str; | |||||||
| #[derive(Copy, PartialEq, Clone)] | #[derive(Copy, PartialEq, Clone)] | ||||||
| pub struct Date(pub Tm); | pub struct Date(pub Tm); | ||||||
|  |  | ||||||
| deref!(Date -> Tm); | deref!(Date => Tm); | ||||||
|  |  | ||||||
| impl Header for Date { | impl Header for Date { | ||||||
|     fn header_name(_: Option<Date>) -> &'static str { |     fn header_name(_: Option<Date>) -> &'static str { | ||||||
|   | |||||||
| @@ -38,8 +38,8 @@ impl Header for Etag { | |||||||
|  |  | ||||||
|  |  | ||||||
|         from_one_raw_str(raw).and_then(|s: String| { |         from_one_raw_str(raw).and_then(|s: String| { | ||||||
|             let length: uint = s.len(); |             let length: usize = s.len(); | ||||||
|             let slice = s[]; |             let slice = &s[]; | ||||||
|  |  | ||||||
|             // Early exits: |             // Early exits: | ||||||
|             // 1. The string is empty, or, |             // 1. The string is empty, or, | ||||||
|   | |||||||
| @@ -9,7 +9,7 @@ use header::shared::time::tm_from_str; | |||||||
| #[derive(Copy, PartialEq, Clone)] | #[derive(Copy, PartialEq, Clone)] | ||||||
| pub struct Expires(pub Tm); | pub struct Expires(pub Tm); | ||||||
|  |  | ||||||
| deref!(Expires -> Tm); | deref!(Expires => Tm); | ||||||
|  |  | ||||||
| impl Header for Expires { | impl Header for Expires { | ||||||
|     fn header_name(_: Option<Expires>) -> &'static str { |     fn header_name(_: Option<Expires>) -> &'static str { | ||||||
|   | |||||||
| @@ -28,7 +28,7 @@ impl Header for Host { | |||||||
|             // FIXME: use rust-url to parse this |             // FIXME: use rust-url to parse this | ||||||
|             // https://github.com/servo/rust-url/issues/42 |             // https://github.com/servo/rust-url/issues/42 | ||||||
|             let idx = { |             let idx = { | ||||||
|                 let slice = s[]; |                 let slice = &s[]; | ||||||
|                 if slice.char_at(1) == '[' { |                 if slice.char_at(1) == '[' { | ||||||
|                     match slice.rfind(']') { |                     match slice.rfind(']') { | ||||||
|                         Some(idx) => { |                         Some(idx) => { | ||||||
|   | |||||||
| @@ -9,7 +9,7 @@ use header::shared::time::tm_from_str; | |||||||
| #[derive(Copy, PartialEq, Clone)] | #[derive(Copy, PartialEq, Clone)] | ||||||
| pub struct IfModifiedSince(pub Tm); | pub struct IfModifiedSince(pub Tm); | ||||||
|  |  | ||||||
| deref!(IfModifiedSince -> Tm); | deref!(IfModifiedSince => Tm); | ||||||
|  |  | ||||||
| impl Header for IfModifiedSince { | impl Header for IfModifiedSince { | ||||||
|     fn header_name(_: Option<IfModifiedSince>) -> &'static str { |     fn header_name(_: Option<IfModifiedSince>) -> &'static str { | ||||||
|   | |||||||
| @@ -9,7 +9,7 @@ use header::shared::time::tm_from_str; | |||||||
| #[derive(Copy, PartialEq, Clone)] | #[derive(Copy, PartialEq, Clone)] | ||||||
| pub struct LastModified(pub Tm); | pub struct LastModified(pub Tm); | ||||||
|  |  | ||||||
| deref!(LastModified -> Tm); | deref!(LastModified => Tm); | ||||||
|  |  | ||||||
| impl Header for LastModified { | impl Header for LastModified { | ||||||
|     fn header_name(_: Option<LastModified>) -> &'static str { |     fn header_name(_: Option<LastModified>) -> &'static str { | ||||||
|   | |||||||
| @@ -16,7 +16,7 @@ use header::shared::util::from_one_raw_str; | |||||||
| #[derive(Clone, PartialEq, Show)] | #[derive(Clone, PartialEq, Show)] | ||||||
| pub struct Location(pub String); | pub struct Location(pub String); | ||||||
|  |  | ||||||
| deref!(Location -> String); | deref!(Location => String); | ||||||
|  |  | ||||||
| impl Header for Location { | impl Header for Location { | ||||||
|     fn header_name(_: Option<Location>) -> &'static str { |     fn header_name(_: Option<Location>) -> &'static str { | ||||||
|   | |||||||
| @@ -42,13 +42,13 @@ macro_rules! bench_header( | |||||||
|             fn bench_parse(b: &mut Bencher) { |             fn bench_parse(b: &mut Bencher) { | ||||||
|                 let val = $value; |                 let val = $value; | ||||||
|                 b.iter(|| { |                 b.iter(|| { | ||||||
|                     let _: $ty = Header::parse_header(val[]).unwrap(); |                     let _: $ty = Header::parse_header(&val[]).unwrap(); | ||||||
|                 }); |                 }); | ||||||
|             } |             } | ||||||
|  |  | ||||||
|             #[bench] |             #[bench] | ||||||
|             fn bench_format(b: &mut Bencher) { |             fn bench_format(b: &mut Bencher) { | ||||||
|                 let val: $ty = Header::parse_header($value[]).unwrap(); |                 let val: $ty = Header::parse_header(&$value[]).unwrap(); | ||||||
|                 let fmt = HeaderFormatter(&val); |                 let fmt = HeaderFormatter(&val); | ||||||
|                 b.iter(|| { |                 b.iter(|| { | ||||||
|                     format!("{}", fmt); |                     format!("{}", fmt); | ||||||
| @@ -59,7 +59,7 @@ macro_rules! bench_header( | |||||||
| ); | ); | ||||||
|  |  | ||||||
| macro_rules! deref( | macro_rules! deref( | ||||||
|     ($from:ty -> $to:ty) => { |     ($from:ty => $to:ty) => { | ||||||
|         impl ::std::ops::Deref for $from { |         impl ::std::ops::Deref for $from { | ||||||
|             type Target = $to; |             type Target = $to; | ||||||
|  |  | ||||||
|   | |||||||
| @@ -8,7 +8,7 @@ use header::shared::util::from_one_raw_str; | |||||||
| #[derive(Clone, PartialEq, Show)] | #[derive(Clone, PartialEq, Show)] | ||||||
| pub struct Server(pub String); | pub struct Server(pub String); | ||||||
|  |  | ||||||
| deref!(Server -> String); | deref!(Server => String); | ||||||
|  |  | ||||||
| impl Header for Server { | impl Header for Server { | ||||||
|     fn header_name(_: Option<Server>) -> &'static str { |     fn header_name(_: Option<Server>) -> &'static str { | ||||||
|   | |||||||
| @@ -17,7 +17,7 @@ pub struct SetCookie(pub Vec<Cookie>); | |||||||
| unsafe impl Send for SetCookie {} | unsafe impl Send for SetCookie {} | ||||||
| unsafe impl Sync for SetCookie {} | unsafe impl Sync for SetCookie {} | ||||||
|  |  | ||||||
| deref!(SetCookie -> Vec<Cookie>); | deref!(SetCookie => Vec<Cookie>); | ||||||
|  |  | ||||||
| impl Header for SetCookie { | impl Header for SetCookie { | ||||||
|     fn header_name(_: Option<SetCookie>) -> &'static str { |     fn header_name(_: Option<SetCookie>) -> &'static str { | ||||||
| @@ -27,7 +27,7 @@ impl Header for SetCookie { | |||||||
|     fn parse_header(raw: &[Vec<u8>]) -> Option<SetCookie> { |     fn parse_header(raw: &[Vec<u8>]) -> Option<SetCookie> { | ||||||
|         let mut set_cookies = Vec::with_capacity(raw.len()); |         let mut set_cookies = Vec::with_capacity(raw.len()); | ||||||
|         for set_cookies_raw in raw.iter() { |         for set_cookies_raw in raw.iter() { | ||||||
|             match from_utf8(set_cookies_raw[]) { |             match from_utf8(&set_cookies_raw[]) { | ||||||
|                 Ok(s) if !s.is_empty() => { |                 Ok(s) if !s.is_empty() => { | ||||||
|                     match s.parse() { |                     match s.parse() { | ||||||
|                         Some(cookie) => set_cookies.push(cookie), |                         Some(cookie) => set_cookies.push(cookie), | ||||||
| @@ -80,7 +80,7 @@ impl SetCookie { | |||||||
|  |  | ||||||
| #[test] | #[test] | ||||||
| fn test_parse() { | fn test_parse() { | ||||||
|     let h = Header::parse_header([b"foo=bar; HttpOnly".to_vec()][]); |     let h = Header::parse_header(&[b"foo=bar; HttpOnly".to_vec()][]); | ||||||
|     let mut c1 = Cookie::new("foo".to_string(), "bar".to_string()); |     let mut c1 = Cookie::new("foo".to_string(), "bar".to_string()); | ||||||
|     c1.httponly = true; |     c1.httponly = true; | ||||||
|  |  | ||||||
| @@ -98,7 +98,7 @@ fn test_fmt() { | |||||||
|     let mut headers = Headers::new(); |     let mut headers = Headers::new(); | ||||||
|     headers.set(cookies); |     headers.set(cookies); | ||||||
|  |  | ||||||
|     assert_eq!(headers.to_string()[], "Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n"); |     assert_eq!(&headers.to_string()[], "Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n"); | ||||||
| } | } | ||||||
|  |  | ||||||
| #[test] | #[test] | ||||||
|   | |||||||
| @@ -21,7 +21,7 @@ use self::Encoding::{Chunked, Gzip, Deflate, Compress, EncodingExt}; | |||||||
| #[derive(Clone, PartialEq, Show)] | #[derive(Clone, PartialEq, Show)] | ||||||
| pub struct TransferEncoding(pub Vec<Encoding>); | pub struct TransferEncoding(pub Vec<Encoding>); | ||||||
|  |  | ||||||
| deref!(TransferEncoding -> Vec<Encoding>); | deref!(TransferEncoding => Vec<Encoding>); | ||||||
|  |  | ||||||
| /// A value to be used with the `Transfer-Encoding` header. | /// A value to be used with the `Transfer-Encoding` header. | ||||||
| /// | /// | ||||||
| @@ -47,15 +47,21 @@ pub enum Encoding { | |||||||
|     EncodingExt(String) |     EncodingExt(String) | ||||||
| } | } | ||||||
|  |  | ||||||
| impl fmt::Show for Encoding { | impl fmt::String for Encoding { | ||||||
|     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         match *self { |         write!(fmt, "{}", match *self { | ||||||
|             Chunked => "chunked", |             Chunked => "chunked", | ||||||
|             Gzip => "gzip", |             Gzip => "gzip", | ||||||
|             Deflate => "deflate", |             Deflate => "deflate", | ||||||
|             Compress => "compress", |             Compress => "compress", | ||||||
|             EncodingExt(ref s) => s.as_slice() |             EncodingExt(ref s) => s.as_slice() | ||||||
|         }.fmt(fmt) |         }) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
|  | impl fmt::Show for Encoding { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  | 		self.to_string().fmt(fmt) | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -83,7 +89,7 @@ impl Header for TransferEncoding { | |||||||
|  |  | ||||||
| impl HeaderFormat for TransferEncoding { | impl HeaderFormat for TransferEncoding { | ||||||
|     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         fmt_comma_delimited(fmt, self[]) |         fmt_comma_delimited(fmt, &self[]) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -9,7 +9,7 @@ use self::Protocol::{WebSocket, ProtocolExt}; | |||||||
| #[derive(Clone, PartialEq, Show)] | #[derive(Clone, PartialEq, Show)] | ||||||
| pub struct Upgrade(pub Vec<Protocol>); | pub struct Upgrade(pub Vec<Protocol>); | ||||||
|  |  | ||||||
| deref!(Upgrade -> Vec<Protocol>); | deref!(Upgrade => Vec<Protocol>); | ||||||
|  |  | ||||||
| /// Protocol values that can appear in the Upgrade header. | /// Protocol values that can appear in the Upgrade header. | ||||||
| #[derive(Clone, PartialEq)] | #[derive(Clone, PartialEq)] | ||||||
| @@ -29,12 +29,18 @@ impl FromStr for Protocol { | |||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| impl fmt::Show for Protocol { | impl fmt::String for Protocol { | ||||||
|     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         match *self { |         write!(fmt, "{}", match *self { | ||||||
|             WebSocket => "websocket", |             WebSocket => "websocket", | ||||||
|             ProtocolExt(ref s) => s.as_slice() |             ProtocolExt(ref s) => s.as_slice() | ||||||
|         }.fmt(fmt) |         }) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
|  | impl fmt::Show for Protocol { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  |         self.to_string().fmt(fmt) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -51,7 +57,7 @@ impl Header for Upgrade { | |||||||
| impl HeaderFormat for Upgrade { | impl HeaderFormat for Upgrade { | ||||||
|     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         let Upgrade(ref parts) = *self; |         let Upgrade(ref parts) = *self; | ||||||
|         fmt_comma_delimited(fmt, parts[]) |         fmt_comma_delimited(fmt, &parts[]) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -8,7 +8,7 @@ use header::shared::util::from_one_raw_str; | |||||||
| #[derive(Clone, PartialEq, Show)] | #[derive(Clone, PartialEq, Show)] | ||||||
| pub struct UserAgent(pub String); | pub struct UserAgent(pub String); | ||||||
|  |  | ||||||
| deref!(UserAgent -> String); | deref!(UserAgent => String); | ||||||
|  |  | ||||||
| impl Header for UserAgent { | impl Header for UserAgent { | ||||||
|     fn header_name(_: Option<UserAgent>) -> &'static str { |     fn header_name(_: Option<UserAgent>) -> &'static str { | ||||||
|   | |||||||
| @@ -20,7 +20,7 @@ impl Header for Vary { | |||||||
|  |  | ||||||
|     fn parse_header(raw: &[Vec<u8>]) -> Option<Vary> { |     fn parse_header(raw: &[Vec<u8>]) -> Option<Vary> { | ||||||
|         from_one_raw_str(raw).and_then(|s: String| { |         from_one_raw_str(raw).and_then(|s: String| { | ||||||
|             let slice = s[]; |             let slice = &s[]; | ||||||
|             match slice { |             match slice { | ||||||
|                 "" => None, |                 "" => None, | ||||||
|                 "*" => Some(Vary::Any), |                 "*" => Some(Vary::Any), | ||||||
| @@ -34,7 +34,7 @@ impl HeaderFormat for Vary { | |||||||
|     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         match *self { |         match *self { | ||||||
|             Vary::Any => { write!(fmt, "*") } |             Vary::Any => { write!(fmt, "*") } | ||||||
|             Vary::Headers(ref fields) => { fmt_comma_delimited(fmt, fields[]) } |             Vary::Headers(ref fields) => { fmt_comma_delimited(fmt, &fields[]) } | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
| } | } | ||||||
|   | |||||||
| @@ -134,15 +134,15 @@ impl Headers { | |||||||
|         loop { |         loop { | ||||||
|             match try!(http::read_header(rdr)) { |             match try!(http::read_header(rdr)) { | ||||||
|                 Some((name, value)) => { |                 Some((name, value)) => { | ||||||
|                     debug!("raw header: {}={}", name, value[]); |                     debug!("raw header: {:?}={:?}", name, &value[]); | ||||||
|                     let name = CaseInsensitive(Owned(name)); |                     let name = CaseInsensitive(Owned(name)); | ||||||
|                     let mut item = match headers.data.entry(&name) { |                     let mut item = match headers.data.entry(name) { | ||||||
|                         Entry::Vacant(entry) => entry.insert(MuCell::new(Item::raw(vec![]))), |                         Entry::Vacant(entry) => entry.insert(MuCell::new(Item::raw(vec![]))), | ||||||
|                         Entry::Occupied(entry) => entry.into_mut() |                         Entry::Occupied(entry) => entry.into_mut() | ||||||
|                     }; |                     }; | ||||||
|  |  | ||||||
|                     match &mut item.borrow_mut().raw { |                     match &mut item.borrow_mut().raw { | ||||||
|                         &Some(ref mut raw) => raw.push(value), |                         &mut Some(ref mut raw) => raw.push(value), | ||||||
|                         // Unreachable |                         // Unreachable | ||||||
|                         _ => {} |                         _ => {} | ||||||
|                     }; |                     }; | ||||||
| @@ -178,7 +178,7 @@ impl Headers { | |||||||
|             .get(&CaseInsensitive(Borrowed(unsafe { mem::transmute::<&str, &str>(name) }))) |             .get(&CaseInsensitive(Borrowed(unsafe { mem::transmute::<&str, &str>(name) }))) | ||||||
|             .and_then(|item| { |             .and_then(|item| { | ||||||
|                 if let Some(ref raw) = item.borrow().raw { |                 if let Some(ref raw) = item.borrow().raw { | ||||||
|                     return unsafe { mem::transmute(Some(raw[])) }; |                     return unsafe { mem::transmute(Some(&raw[])) }; | ||||||
|                 } |                 } | ||||||
|  |  | ||||||
|                 let worked = item.try_mutate(|item| { |                 let worked = item.try_mutate(|item| { | ||||||
| @@ -189,7 +189,7 @@ impl Headers { | |||||||
|  |  | ||||||
|                 let item = item.borrow(); |                 let item = item.borrow(); | ||||||
|                 let raw = item.raw.as_ref().unwrap(); |                 let raw = item.raw.as_ref().unwrap(); | ||||||
|                 unsafe { mem::transmute(Some(raw[])) } |                 unsafe { mem::transmute(Some(&raw[])) } | ||||||
|             }) |             }) | ||||||
|     } |     } | ||||||
|  |  | ||||||
| @@ -258,7 +258,7 @@ impl Headers { | |||||||
|     } |     } | ||||||
|  |  | ||||||
|     /// Returns the number of headers in the map. |     /// Returns the number of headers in the map. | ||||||
|     pub fn len(&self) -> uint { |     pub fn len(&self) -> usize { | ||||||
|         self.data.len() |         self.data.len() | ||||||
|     } |     } | ||||||
|  |  | ||||||
| @@ -268,7 +268,7 @@ impl Headers { | |||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| impl fmt::Show for Headers { | impl fmt::String for Headers { | ||||||
|     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         for header in self.iter() { |         for header in self.iter() { | ||||||
|             try!(write!(fmt, "{}{}", header, LineEnding)); |             try!(write!(fmt, "{}{}", header, LineEnding)); | ||||||
| @@ -277,6 +277,12 @@ impl fmt::Show for Headers { | |||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|  | impl fmt::Show for Headers { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  |         self.to_string().fmt(fmt) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
| /// An `Iterator` over the fields in a `Headers` map. | /// An `Iterator` over the fields in a `Headers` map. | ||||||
| pub struct HeadersItems<'a> { | pub struct HeadersItems<'a> { | ||||||
|     inner: Iter<'a, CaseInsensitive, MuCell<Item>> |     inner: Iter<'a, CaseInsensitive, MuCell<Item>> | ||||||
| @@ -326,12 +332,18 @@ impl<'a> HeaderView<'a> { | |||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| impl<'a> fmt::Show for HeaderView<'a> { | impl<'a> fmt::String for HeaderView<'a> { | ||||||
|     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         write!(f, "{}: {}", self.0, *self.1.borrow()) |         write!(f, "{}: {}", self.0, *self.1.borrow()) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|  | impl<'a> fmt::Show for HeaderView<'a> { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  |         self.to_string().fmt(fmt) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
| impl<'a> Extend<HeaderView<'a>> for Headers { | impl<'a> Extend<HeaderView<'a>> for Headers { | ||||||
|     fn extend<I: Iterator<Item=HeaderView<'a>>>(&mut self, mut iter: I) { |     fn extend<I: Iterator<Item=HeaderView<'a>>>(&mut self, mut iter: I) { | ||||||
|         for header in iter { |         for header in iter { | ||||||
| @@ -375,7 +387,7 @@ fn get_or_parse<H: Header + HeaderFormat>(item: &MuCell<Item>) -> Option<&MuCell | |||||||
|     match item.borrow().typed { |     match item.borrow().typed { | ||||||
|         Some(ref typed) if typed.is::<H>() => return Some(item), |         Some(ref typed) if typed.is::<H>() => return Some(item), | ||||||
|         Some(ref typed) => { |         Some(ref typed) => { | ||||||
|             warn!("attempted to access {} as wrong type", typed); |             warn!("attempted to access {:?} as wrong type", typed); | ||||||
|             return None; |             return None; | ||||||
|         } |         } | ||||||
|         _ => () |         _ => () | ||||||
| @@ -394,7 +406,7 @@ fn get_or_parse_mut<H: Header + HeaderFormat>(item: &mut MuCell<Item>) -> Option | |||||||
|     let is_correct_type = match item.borrow().typed { |     let is_correct_type = match item.borrow().typed { | ||||||
|         Some(ref typed) if typed.is::<H>() => Some(true), |         Some(ref typed) if typed.is::<H>() => Some(true), | ||||||
|         Some(ref typed) => { |         Some(ref typed) => { | ||||||
|             warn!("attempted to access {} as wrong type", typed); |             warn!("attempted to access {:?} as wrong type", typed); | ||||||
|             Some(false) |             Some(false) | ||||||
|         } |         } | ||||||
|         _ => None |         _ => None | ||||||
| @@ -416,7 +428,7 @@ fn get_or_parse_mut<H: Header + HeaderFormat>(item: &mut MuCell<Item>) -> Option | |||||||
|  |  | ||||||
| fn parse<H: Header + HeaderFormat>(item: &mut Item) { | fn parse<H: Header + HeaderFormat>(item: &mut Item) { | ||||||
|     item.typed = match item.raw { |     item.typed = match item.raw { | ||||||
|         Some(ref raw) => match Header::parse_header(raw[]) { |         Some(ref raw) => match Header::parse_header(&raw[]) { | ||||||
|             Some::<H>(h) => Some(box h as Box<HeaderFormat + Send + Sync>), |             Some::<H>(h) => Some(box h as Box<HeaderFormat + Send + Sync>), | ||||||
|             None => None |             None => None | ||||||
|         }, |         }, | ||||||
| @@ -432,17 +444,17 @@ unsafe fn downcast_mut<H: Header + HeaderFormat>(item: &mut Item) -> &mut H { | |||||||
|     item.typed.as_mut().expect("item.typed must be set").downcast_mut_unchecked() |     item.typed.as_mut().expect("item.typed must be set").downcast_mut_unchecked() | ||||||
| } | } | ||||||
|  |  | ||||||
| impl fmt::Show for Item { | impl fmt::String for Item { | ||||||
|     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         match self.typed { |         match self.typed { | ||||||
|             Some(ref h) => h.fmt_header(fmt), |             Some(ref h) => h.fmt_header(fmt), | ||||||
|             None => match self.raw { |             None => match self.raw { | ||||||
|                 Some(ref raw) => { |                 Some(ref raw) => { | ||||||
|                     for part in raw.iter() { |                     for part in raw.iter() { | ||||||
|                         match from_utf8(part[]) { |                         match from_utf8(&part[]) { | ||||||
|                             Ok(s) => try!(fmt.write_str(s)), |                             Ok(s) => try!(fmt.write_str(s)), | ||||||
|                             Err(e) => { |                             Err(e) => { | ||||||
|                                 error!("raw header value is not utf8. header={}, error={}", part[], e); |                                 error!("raw header value is not utf8. header={:?}, error={:?}", &part[], e); | ||||||
|                                 return Err(fmt::Error); |                                 return Err(fmt::Error); | ||||||
|                             } |                             } | ||||||
|                         } |                         } | ||||||
| @@ -455,12 +467,24 @@ impl fmt::Show for Item { | |||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| impl fmt::Show for Box<HeaderFormat + Send + Sync> { | impl<'a> fmt::Show for Item { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  |         self.to_string().fmt(fmt) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
|  | impl fmt::String for Box<HeaderFormat + Send + Sync> { | ||||||
|     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         (**self).fmt_header(fmt) |         (**self).fmt_header(fmt) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|  | impl fmt::Show for Box<HeaderFormat + Send + Sync> { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  |         self.to_string().fmt(fmt) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
| /// Case-insensitive string. | /// Case-insensitive string. | ||||||
| pub struct CaseInsensitive(CowString<'static>); | pub struct CaseInsensitive(CowString<'static>); | ||||||
|  |  | ||||||
| @@ -484,9 +508,15 @@ impl Str for CaseInsensitive { | |||||||
|  |  | ||||||
| } | } | ||||||
|  |  | ||||||
|  | impl fmt::String for CaseInsensitive { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  |         write!(fmt, "{}", self.as_slice()) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
| impl fmt::Show for CaseInsensitive { | impl fmt::Show for CaseInsensitive { | ||||||
|     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         self.as_slice().fmt(fmt) |         self.to_string().fmt(fmt) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -498,7 +528,7 @@ impl PartialEq for CaseInsensitive { | |||||||
|  |  | ||||||
| impl Eq for CaseInsensitive {} | impl Eq for CaseInsensitive {} | ||||||
|  |  | ||||||
| impl<H: hash::Writer> hash::Hash<H> for CaseInsensitive { | impl<H: hash::Writer + hash::Hasher> hash::Hash<H> for CaseInsensitive { | ||||||
|     #[inline] |     #[inline] | ||||||
|     fn hash(&self, hasher: &mut H) { |     fn hash(&self, hasher: &mut H) { | ||||||
|         for b in self.as_slice().bytes() { |         for b in self.as_slice().bytes() { | ||||||
| @@ -514,6 +544,12 @@ impl<H: hash::Writer> hash::Hash<H> for CaseInsensitive { | |||||||
| /// outgoing TcpStream. | /// outgoing TcpStream. | ||||||
| pub struct HeaderFormatter<'a, H: HeaderFormat>(pub &'a H); | pub struct HeaderFormatter<'a, H: HeaderFormat>(pub &'a H); | ||||||
|  |  | ||||||
|  | impl<'a, H: HeaderFormat> fmt::String for HeaderFormatter<'a, H> { | ||||||
|  |     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  |         self.0.fmt_header(f) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
| impl<'a, H: HeaderFormat> Show for HeaderFormatter<'a, H> { | impl<'a, H: HeaderFormat> Show for HeaderFormatter<'a, H> { | ||||||
|     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         self.0.fmt_header(f) |         self.0.fmt_header(f) | ||||||
| @@ -525,7 +561,7 @@ mod tests { | |||||||
|     use std::io::MemReader; |     use std::io::MemReader; | ||||||
|     use std::fmt; |     use std::fmt; | ||||||
|     use std::borrow::Cow::Borrowed; |     use std::borrow::Cow::Borrowed; | ||||||
|     use std::hash::sip::hash; |     use std::hash::{SipHasher, hash}; | ||||||
|     use mime::Mime; |     use mime::Mime; | ||||||
|     use mime::TopLevel::Text; |     use mime::TopLevel::Text; | ||||||
|     use mime::SubLevel::Plain; |     use mime::SubLevel::Plain; | ||||||
| @@ -546,7 +582,7 @@ mod tests { | |||||||
|         let b = CaseInsensitive(Borrowed("FOOBAR")); |         let b = CaseInsensitive(Borrowed("FOOBAR")); | ||||||
|  |  | ||||||
|         assert_eq!(a, b); |         assert_eq!(a, b); | ||||||
|         assert_eq!(hash(&a), hash(&b)); |         assert_eq!(hash::<_, SipHasher>(&a), hash::<_, SipHasher>(&b)); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     #[test] |     #[test] | ||||||
| @@ -574,7 +610,7 @@ mod tests { | |||||||
|     } |     } | ||||||
|  |  | ||||||
|     #[derive(Clone, Show)] |     #[derive(Clone, Show)] | ||||||
|     struct CrazyLength(Option<bool>, uint); |     struct CrazyLength(Option<bool>, usize); | ||||||
|  |  | ||||||
|     impl Header for CrazyLength { |     impl Header for CrazyLength { | ||||||
|         fn header_name(_: Option<CrazyLength>) -> &'static str { |         fn header_name(_: Option<CrazyLength>) -> &'static str { | ||||||
| @@ -588,7 +624,7 @@ mod tests { | |||||||
|                 return None; |                 return None; | ||||||
|             } |             } | ||||||
|             // we JUST checked that raw.len() == 1, so raw[0] WILL exist. |             // we JUST checked that raw.len() == 1, so raw[0] WILL exist. | ||||||
|             match from_utf8(unsafe { raw[].get_unchecked(0)[] }) { |             match from_utf8(unsafe { &raw[].get_unchecked(0)[] }) { | ||||||
|                 Ok(s) => FromStr::from_str(s), |                 Ok(s) => FromStr::from_str(s), | ||||||
|                 Err(_) => None |                 Err(_) => None | ||||||
|             }.map(|u| CrazyLength(Some(false), u)) |             }.map(|u| CrazyLength(Some(false), u)) | ||||||
| @@ -598,7 +634,7 @@ mod tests { | |||||||
|     impl HeaderFormat for CrazyLength { |     impl HeaderFormat for CrazyLength { | ||||||
|         fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |         fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|             let CrazyLength(ref opt, ref value) = *self; |             let CrazyLength(ref opt, ref value) = *self; | ||||||
|             write!(fmt, "{}, {}", opt, value) |             write!(fmt, "{:?}, {:?}", opt, value) | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
| @@ -649,7 +685,7 @@ mod tests { | |||||||
|         let mut pieces = s[].split_str("\r\n").collect::<Vec<&str>>(); |         let mut pieces = s[].split_str("\r\n").collect::<Vec<&str>>(); | ||||||
|         pieces.sort(); |         pieces.sort(); | ||||||
|         let s = pieces.into_iter().rev().collect::<Vec<&str>>().connect("\r\n"); |         let s = pieces.into_iter().rev().collect::<Vec<&str>>().connect("\r\n"); | ||||||
|         assert_eq!(s[], "Host: foo.bar\r\nContent-Length: 15\r\n"); |         assert_eq!(&s[], "Host: foo.bar\r\nContent-Length: 15\r\n"); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     #[test] |     #[test] | ||||||
| @@ -664,7 +700,7 @@ mod tests { | |||||||
|         let mut headers = Headers::new(); |         let mut headers = Headers::new(); | ||||||
|         headers.set(ContentLength(10)); |         headers.set(ContentLength(10)); | ||||||
|         headers.set_raw("content-LENGTH", vec![b"20".to_vec()]); |         headers.set_raw("content-LENGTH", vec![b"20".to_vec()]); | ||||||
|         assert_eq!(headers.get_raw("Content-length").unwrap(), [b"20".to_vec()][]); |         assert_eq!(headers.get_raw("Content-length").unwrap(), &[b"20".to_vec()][]); | ||||||
|         assert_eq!(headers.get(), Some(&ContentLength(20))); |         assert_eq!(headers.get(), Some(&ContentLength(20))); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -23,16 +23,22 @@ pub enum Encoding { | |||||||
|     EncodingExt(String) |     EncodingExt(String) | ||||||
| } | } | ||||||
|  |  | ||||||
| impl fmt::Show for Encoding { | impl fmt::String for Encoding { | ||||||
|     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         match *self { |         write!(fmt, "{}", match *self { | ||||||
|             Chunked => "chunked", |             Chunked => "chunked", | ||||||
|             Gzip => "gzip", |             Gzip => "gzip", | ||||||
|             Deflate => "deflate", |             Deflate => "deflate", | ||||||
|             Compress => "compress", |             Compress => "compress", | ||||||
|             Identity => "identity", |             Identity => "identity", | ||||||
|             EncodingExt(ref s) => s.as_slice() |             EncodingExt(ref s) => s.as_slice() | ||||||
|             }.fmt(fmt) |         }) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | impl fmt::Show for Encoding { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  | 		self.to_string().fmt(fmt) | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -26,7 +26,13 @@ impl<T> QualityItem<T> { | |||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| impl<T: fmt::Show> fmt::Show for QualityItem<T> { | impl<T: fmt::String> fmt::String for QualityItem<T> { | ||||||
|  |     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  |         write!(f, "{}; q={}", self.item, format!("{:.3}", self.quality).trim_right_matches(['0', '.'].as_slice())) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
|  | impl<T: fmt::String> fmt::Show for QualityItem<T> { | ||||||
|     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         write!(f, "{}; q={}", self.item, format!("{:.3}", self.quality).trim_right_matches(['0', '.'].as_slice())) |         write!(f, "{}; q={}", self.item, format!("{:.3}", self.quality).trim_right_matches(['0', '.'].as_slice())) | ||||||
|     } |     } | ||||||
|   | |||||||
| @@ -9,7 +9,7 @@ pub fn from_one_raw_str<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<T> { | |||||||
|         return None; |         return None; | ||||||
|     } |     } | ||||||
|     // we JUST checked that raw.len() == 1, so raw[0] WILL exist. |     // we JUST checked that raw.len() == 1, so raw[0] WILL exist. | ||||||
|     match str::from_utf8(raw[0][]) { |     match str::from_utf8(&raw[0][]) { | ||||||
|         Ok(s) => str::FromStr::from_str(s), |         Ok(s) => str::FromStr::from_str(s), | ||||||
|         Err(_) => None |         Err(_) => None | ||||||
|     } |     } | ||||||
| @@ -22,7 +22,7 @@ pub fn from_comma_delimited<T: str::FromStr>(raw: &[Vec<u8>]) -> Option<Vec<T>> | |||||||
|         return None; |         return None; | ||||||
|     } |     } | ||||||
|     // we JUST checked that raw.len() == 1, so raw[0] WILL exist. |     // we JUST checked that raw.len() == 1, so raw[0] WILL exist. | ||||||
|     from_one_comma_delimited(raw[0][]) |     from_one_comma_delimited(&raw[0][]) | ||||||
| } | } | ||||||
|  |  | ||||||
| /// Reads a comma-delimited raw string into a Vec. | /// Reads a comma-delimited raw string into a Vec. | ||||||
| @@ -40,7 +40,7 @@ pub fn from_one_comma_delimited<T: str::FromStr>(raw: &[u8]) -> Option<Vec<T>> { | |||||||
| } | } | ||||||
|  |  | ||||||
| /// Format an array into a comma-delimited string. | /// Format an array into a comma-delimited string. | ||||||
| pub fn fmt_comma_delimited<T: fmt::Show>(fmt: &mut fmt::Formatter, parts: &[T]) -> fmt::Result { | pub fn fmt_comma_delimited<T: fmt::String>(fmt: &mut fmt::Formatter, parts: &[T]) -> fmt::Result { | ||||||
|     let last = parts.len() - 1; |     let last = parts.len() - 1; | ||||||
|     for (i, part) in parts.iter().enumerate() { |     for (i, part) in parts.iter().enumerate() { | ||||||
|         try!(write!(fmt, "{}", part)); |         try!(write!(fmt, "{}", part)); | ||||||
|   | |||||||
							
								
								
									
										60
									
								
								src/http.rs
									
									
									
									
									
								
							
							
						
						
									
										60
									
								
								src/http.rs
									
									
									
									
									
								
							| @@ -30,9 +30,9 @@ use self::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; | |||||||
| /// include a Content-Length header. | /// include a Content-Length header. | ||||||
| pub enum HttpReader<R> { | pub enum HttpReader<R> { | ||||||
|     /// A Reader used when a Content-Length header is passed with a positive integer. |     /// A Reader used when a Content-Length header is passed with a positive integer. | ||||||
|     SizedReader(R, uint), |     SizedReader(R, usize), | ||||||
|     /// A Reader used when Transfer-Encoding is `chunked`. |     /// A Reader used when Transfer-Encoding is `chunked`. | ||||||
|     ChunkedReader(R, Option<uint>), |     ChunkedReader(R, Option<usize>), | ||||||
|     /// A Reader used for responses that don't indicate a length or chunked. |     /// A Reader used for responses that don't indicate a length or chunked. | ||||||
|     /// |     /// | ||||||
|     /// Note: This should only used for `Response`s. It is illegal for a |     /// Note: This should only used for `Response`s. It is illegal for a | ||||||
| @@ -68,10 +68,10 @@ impl<R: Reader> HttpReader<R> { | |||||||
| } | } | ||||||
|  |  | ||||||
| impl<R: Reader> Reader for HttpReader<R> { | impl<R: Reader> Reader for HttpReader<R> { | ||||||
|     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { |     fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { | ||||||
|         match *self { |         match *self { | ||||||
|             SizedReader(ref mut body, ref mut remaining) => { |             SizedReader(ref mut body, ref mut remaining) => { | ||||||
|                 debug!("Sized read, remaining={}", remaining); |                 debug!("Sized read, remaining={:?}", remaining); | ||||||
|                 if *remaining == 0 { |                 if *remaining == 0 { | ||||||
|                     Err(io::standard_error(io::EndOfFile)) |                     Err(io::standard_error(io::EndOfFile)) | ||||||
|                 } else { |                 } else { | ||||||
| @@ -90,7 +90,7 @@ impl<R: Reader> Reader for HttpReader<R> { | |||||||
|                     // None means we don't know the size of the next chunk |                     // None means we don't know the size of the next chunk | ||||||
|                     None => try!(read_chunk_size(body)) |                     None => try!(read_chunk_size(body)) | ||||||
|                 }; |                 }; | ||||||
|                 debug!("Chunked read, remaining={}", rem); |                 debug!("Chunked read, remaining={:?}", rem); | ||||||
|  |  | ||||||
|                 if rem == 0 { |                 if rem == 0 { | ||||||
|                     *opt_remaining = Some(0); |                     *opt_remaining = Some(0); | ||||||
| @@ -133,8 +133,8 @@ fn eat<R: Reader>(rdr: &mut R, bytes: &[u8]) -> IoResult<()> { | |||||||
| } | } | ||||||
|  |  | ||||||
| /// Chunked chunks start with 1*HEXDIGIT, indicating the size of the chunk. | /// Chunked chunks start with 1*HEXDIGIT, indicating the size of the chunk. | ||||||
| fn read_chunk_size<R: Reader>(rdr: &mut R) -> IoResult<uint> { | fn read_chunk_size<R: Reader>(rdr: &mut R) -> IoResult<usize> { | ||||||
|     let mut size = 0u; |     let mut size = 0us; | ||||||
|     let radix = 16; |     let radix = 16; | ||||||
|     let mut in_ext = false; |     let mut in_ext = false; | ||||||
|     let mut in_chunk_size = true; |     let mut in_chunk_size = true; | ||||||
| @@ -142,15 +142,15 @@ fn read_chunk_size<R: Reader>(rdr: &mut R) -> IoResult<uint> { | |||||||
|         match try!(rdr.read_byte()) { |         match try!(rdr.read_byte()) { | ||||||
|             b@b'0'...b'9' if in_chunk_size => { |             b@b'0'...b'9' if in_chunk_size => { | ||||||
|                 size *= radix; |                 size *= radix; | ||||||
|                 size += (b - b'0') as uint; |                 size += (b - b'0') as usize; | ||||||
|             }, |             }, | ||||||
|             b@b'a'...b'f' if in_chunk_size => { |             b@b'a'...b'f' if in_chunk_size => { | ||||||
|                 size *= radix; |                 size *= radix; | ||||||
|                 size += (b + 10 - b'a') as uint; |                 size += (b + 10 - b'a') as usize; | ||||||
|             }, |             }, | ||||||
|             b@b'A'...b'F' if in_chunk_size => { |             b@b'A'...b'F' if in_chunk_size => { | ||||||
|                 size *= radix; |                 size *= radix; | ||||||
|                 size += (b + 10 - b'A') as uint; |                 size += (b + 10 - b'A') as usize; | ||||||
|             }, |             }, | ||||||
|             CR => { |             CR => { | ||||||
|                 match try!(rdr.read_byte()) { |                 match try!(rdr.read_byte()) { | ||||||
| @@ -183,7 +183,7 @@ fn read_chunk_size<R: Reader>(rdr: &mut R) -> IoResult<uint> { | |||||||
|             } |             } | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
|     debug!("chunk size={}", size); |     debug!("chunk size={:?}", size); | ||||||
|     Ok(size) |     Ok(size) | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -196,7 +196,7 @@ pub enum HttpWriter<W: Writer> { | |||||||
|     /// A Writer for when Content-Length is set. |     /// A Writer for when Content-Length is set. | ||||||
|     /// |     /// | ||||||
|     /// Enforces that the body is not longer than the Content-Length header. |     /// Enforces that the body is not longer than the Content-Length header. | ||||||
|     SizedWriter(W, uint), |     SizedWriter(W, usize), | ||||||
|     /// A writer that should not write any body. |     /// A writer that should not write any body. | ||||||
|     EmptyWriter(W), |     EmptyWriter(W), | ||||||
| } | } | ||||||
| @@ -257,7 +257,7 @@ impl<W: Writer> Writer for HttpWriter<W> { | |||||||
|             ThroughWriter(ref mut w) => w.write(msg), |             ThroughWriter(ref mut w) => w.write(msg), | ||||||
|             ChunkedWriter(ref mut w) => { |             ChunkedWriter(ref mut w) => { | ||||||
|                 let chunk_size = msg.len(); |                 let chunk_size = msg.len(); | ||||||
|                 debug!("chunked write, size = {}", chunk_size); |                 debug!("chunked write, size = {:?}", chunk_size); | ||||||
|                 try!(write!(w, "{:X}{}", chunk_size, LINE_ENDING)); |                 try!(write!(w, "{:X}{}", chunk_size, LINE_ENDING)); | ||||||
|                 try!(w.write(msg)); |                 try!(w.write(msg)); | ||||||
|                 w.write_str(LINE_ENDING) |                 w.write_str(LINE_ENDING) | ||||||
| @@ -311,12 +311,18 @@ pub struct LineEnding; | |||||||
|  |  | ||||||
| impl Copy for LineEnding {} | impl Copy for LineEnding {} | ||||||
|  |  | ||||||
| impl fmt::Show for LineEnding { | impl fmt::String for LineEnding { | ||||||
|     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         fmt.write_str(LINE_ENDING) |         fmt.write_str(LINE_ENDING) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|  | impl fmt::Show for LineEnding { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  |         self.to_string().fmt(fmt) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
| /// Determines if byte is a token char. | /// Determines if byte is a token char. | ||||||
| /// | /// | ||||||
| /// > ```notrust | /// > ```notrust | ||||||
| @@ -392,7 +398,7 @@ pub fn read_method<R: Reader>(stream: &mut R) -> HttpResult<method::Method> { | |||||||
|         return Err(HttpMethodError); |         return Err(HttpMethodError); | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     let maybe_method = match buf[0..7] { |     let maybe_method = match &buf[0..7] { | ||||||
|         b"GET    " => Some(method::Method::Get), |         b"GET    " => Some(method::Method::Get), | ||||||
|         b"PUT    " => Some(method::Method::Put), |         b"PUT    " => Some(method::Method::Put), | ||||||
|         b"POST   " => Some(method::Method::Post), |         b"POST   " => Some(method::Method::Post), | ||||||
| @@ -405,9 +411,9 @@ pub fn read_method<R: Reader>(stream: &mut R) -> HttpResult<method::Method> { | |||||||
|         _ => None, |         _ => None, | ||||||
|     }; |     }; | ||||||
|  |  | ||||||
|     debug!("maybe_method = {}", maybe_method); |     debug!("maybe_method = {:?}", maybe_method); | ||||||
|  |  | ||||||
|     match (maybe_method, buf[]) { |     match (maybe_method, &buf[]) { | ||||||
|         (Some(method), _) => Ok(method), |         (Some(method), _) => Ok(method), | ||||||
|         (None, ext) => { |         (None, ext) => { | ||||||
|             // We already checked that the buffer is ASCII |             // We already checked that the buffer is ASCII | ||||||
| @@ -442,7 +448,7 @@ pub fn read_uri<R: Reader>(stream: &mut R) -> HttpResult<uri::RequestUri> { | |||||||
|         } |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     debug!("uri buf = {}", s); |     debug!("uri buf = {:?}", s); | ||||||
|  |  | ||||||
|     if s.as_slice().starts_with("/") { |     if s.as_slice().starts_with("/") { | ||||||
|         Ok(AbsolutePath(s)) |         Ok(AbsolutePath(s)) | ||||||
| @@ -491,8 +497,8 @@ pub fn read_http_version<R: Reader>(stream: &mut R) -> HttpResult<HttpVersion> { | |||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| const MAX_HEADER_NAME_LENGTH: uint = 100; | const MAX_HEADER_NAME_LENGTH: usize = 100; | ||||||
| const MAX_HEADER_FIELD_LENGTH: uint = 1000; | const MAX_HEADER_FIELD_LENGTH: usize = 1000; | ||||||
|  |  | ||||||
| /// The raw bytes when parsing a header line. | /// The raw bytes when parsing a header line. | ||||||
| /// | /// | ||||||
| @@ -541,7 +547,7 @@ pub fn read_header<R: Reader>(stream: &mut R) -> HttpResult<Option<RawHeaderLine | |||||||
|         }; |         }; | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     debug!("header name = {}", name); |     debug!("header name = {:?}", name); | ||||||
|  |  | ||||||
|     let mut ows = true; //optional whitespace |     let mut ows = true; //optional whitespace | ||||||
|  |  | ||||||
| @@ -576,11 +582,11 @@ pub type RequestLine = (method::Method, uri::RequestUri, HttpVersion); | |||||||
| pub fn read_request_line<R: Reader>(stream: &mut R) -> HttpResult<RequestLine> { | pub fn read_request_line<R: Reader>(stream: &mut R) -> HttpResult<RequestLine> { | ||||||
|     debug!("read request line"); |     debug!("read request line"); | ||||||
|     let method = try!(read_method(stream)); |     let method = try!(read_method(stream)); | ||||||
|     debug!("method = {}", method); |     debug!("method = {:?}", method); | ||||||
|     let uri = try!(read_uri(stream)); |     let uri = try!(read_uri(stream)); | ||||||
|     debug!("uri = {}", uri); |     debug!("uri = {:?}", uri); | ||||||
|     let version = try!(read_http_version(stream)); |     let version = try!(read_http_version(stream)); | ||||||
|     debug!("version = {}", version); |     debug!("version = {:?}", version); | ||||||
|  |  | ||||||
|     if try!(stream.read_byte()) != CR { |     if try!(stream.read_byte()) != CR { | ||||||
|         return Err(HttpVersionError); |         return Err(HttpVersionError); | ||||||
| @@ -660,7 +666,7 @@ pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> { | |||||||
|                 b => match bufwrt.write_u8(b) { |                 b => match bufwrt.write_u8(b) { | ||||||
|                     Ok(_) => (), |                     Ok(_) => (), | ||||||
|                     Err(_) => { |                     Err(_) => { | ||||||
|                         for _ in range(0u, 128) { |                         for _ in range(0us, 128) { | ||||||
|                             match try!(stream.read_byte()) { |                             match try!(stream.read_byte()) { | ||||||
|                                 CR => match try!(stream.read_byte()) { |                                 CR => match try!(stream.read_byte()) { | ||||||
|                                     LF => break 'read, |                                     LF => break 'read, | ||||||
| @@ -676,7 +682,7 @@ pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> { | |||||||
|         } |         } | ||||||
|     } |     } | ||||||
|  |  | ||||||
|     let reason = match str::from_utf8(buf[]) { |     let reason = match str::from_utf8(&buf[]) { | ||||||
|         Ok(s) => s.trim(), |         Ok(s) => s.trim(), | ||||||
|         Err(_) => return Err(HttpStatusError) |         Err(_) => return Err(HttpStatusError) | ||||||
|     }; |     }; | ||||||
| @@ -833,7 +839,7 @@ mod tests { | |||||||
|  |  | ||||||
|     #[test] |     #[test] | ||||||
|     fn test_read_chunk_size() { |     fn test_read_chunk_size() { | ||||||
|         fn read(s: &str, result: IoResult<uint>) { |         fn read(s: &str, result: IoResult<usize>) { | ||||||
|             assert_eq!(read_chunk_size(&mut mem(s)), result); |             assert_eq!(read_chunk_size(&mut mem(s)), result); | ||||||
|         } |         } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -1,4 +1,5 @@ | |||||||
| #![feature(slicing_syntax, old_orphan_check)] | #![feature(slicing_syntax, box_syntax, old_orphan_check, old_impl_check)] | ||||||
|  | #![allow(unstable)] | ||||||
| #![deny(missing_docs)] | #![deny(missing_docs)] | ||||||
| #![deny(warnings)] | #![deny(warnings)] | ||||||
| #![experimental] | #![experimental] | ||||||
| @@ -151,14 +152,14 @@ use self::HttpError::{HttpMethodError, HttpUriError, HttpVersionError, | |||||||
|  |  | ||||||
| macro_rules! todo( | macro_rules! todo( | ||||||
|     ($($arg:tt)*) => (if cfg!(not(ndebug)) { |     ($($arg:tt)*) => (if cfg!(not(ndebug)) { | ||||||
|         log!(5, "TODO: {}", format_args!($($arg)*)) |         log!(5, "TODO: {:?}", format_args!($($arg)*)) | ||||||
|     }) |     }) | ||||||
| ); | ); | ||||||
|  |  | ||||||
| macro_rules! inspect( | macro_rules! inspect( | ||||||
|     ($name:expr, $value:expr) => ({ |     ($name:expr, $value:expr) => ({ | ||||||
|         let v = $value; |         let v = $value; | ||||||
|         debug!("inspect: {} = {}", $name, v); |         debug!("inspect: {:?} = {:?}", $name, v); | ||||||
|         v |         v | ||||||
|     }) |     }) | ||||||
| ); | ); | ||||||
|   | |||||||
| @@ -88,7 +88,7 @@ impl FromStr for Method { | |||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| impl fmt::Show for Method { | impl fmt::String for Method { | ||||||
|     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         match *self { |         match *self { | ||||||
|             Options => "OPTIONS", |             Options => "OPTIONS", | ||||||
| @@ -105,6 +105,12 @@ impl fmt::Show for Method { | |||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|  | impl fmt::Show for Method { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  |         self.to_string().fmt(fmt) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
| #[cfg(test)] | #[cfg(test)] | ||||||
| mod tests { | mod tests { | ||||||
|     use std::collections::HashMap; |     use std::collections::HashMap; | ||||||
| @@ -141,7 +147,7 @@ mod tests { | |||||||
|  |  | ||||||
|     #[test] |     #[test] | ||||||
|     fn test_hashable() { |     fn test_hashable() { | ||||||
|         let mut counter: HashMap<Method,uint> = HashMap::new(); |         let mut counter: HashMap<Method,usize> = HashMap::new(); | ||||||
|         counter.insert(Get, 1); |         counter.insert(Get, 1); | ||||||
|         assert_eq!(Some(&1), counter.get(&Get)); |         assert_eq!(Some(&1), counter.get(&Get)); | ||||||
|     } |     } | ||||||
|   | |||||||
| @@ -27,7 +27,7 @@ impl PartialEq for MockStream { | |||||||
|  |  | ||||||
| impl fmt::Show for MockStream { | impl fmt::Show for MockStream { | ||||||
|     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         write!(f, "MockStream {{ read: {}, write: {} }}", |         write!(f, "MockStream {{ read: {:?}, write: {:?} }}", | ||||||
|                self.read.get_ref(), self.write.get_ref()) |                self.read.get_ref(), self.write.get_ref()) | ||||||
|     } |     } | ||||||
|  |  | ||||||
| @@ -49,7 +49,7 @@ impl MockStream { | |||||||
|     } |     } | ||||||
| } | } | ||||||
| impl Reader for MockStream { | impl Reader for MockStream { | ||||||
|     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { |     fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { | ||||||
|         self.read.read(buf) |         self.read.read(buf) | ||||||
|     } |     } | ||||||
| } | } | ||||||
| @@ -85,7 +85,7 @@ macro_rules! mock_connector ( | |||||||
|         impl ::net::NetworkConnector<::mock::MockStream> for $name { |         impl ::net::NetworkConnector<::mock::MockStream> for $name { | ||||||
|             fn connect(&mut self, host: &str, port: u16, scheme: &str) -> ::std::io::IoResult<::mock::MockStream> { |             fn connect(&mut self, host: &str, port: u16, scheme: &str) -> ::std::io::IoResult<::mock::MockStream> { | ||||||
|                 use std::collections::HashMap; |                 use std::collections::HashMap; | ||||||
|                 debug!("MockStream::connect({}, {}, {})", host, port, scheme); |                 debug!("MockStream::connect({:?}, {:?}, {:?})", host, port, scheme); | ||||||
|                 let mut map = HashMap::new(); |                 let mut map = HashMap::new(); | ||||||
|                 $(map.insert($url, $res);)* |                 $(map.insert($url, $res);)* | ||||||
|  |  | ||||||
| @@ -97,7 +97,7 @@ macro_rules! mock_connector ( | |||||||
|                         write: ::std::io::MemWriter::new(), |                         write: ::std::io::MemWriter::new(), | ||||||
|                         read: ::std::io::MemReader::new(res.to_string().into_bytes()) |                         read: ::std::io::MemReader::new(res.to_string().into_bytes()) | ||||||
|                     }), |                     }), | ||||||
|                     None => panic!("{} doesn't know url {}", stringify!($name), key) |                     None => panic!("{:?} doesn't know url {}", stringify!($name), key) | ||||||
|                 } |                 } | ||||||
|             } |             } | ||||||
|  |  | ||||||
|   | |||||||
							
								
								
									
										10
									
								
								src/net.rs
									
									
									
									
									
								
							
							
						
						
									
										10
									
								
								src/net.rs
									
									
									
									
									
								
							| @@ -80,7 +80,7 @@ impl Clone for Box<NetworkStream + Send> { | |||||||
|  |  | ||||||
| impl Reader for Box<NetworkStream + Send> { | impl Reader for Box<NetworkStream + Send> { | ||||||
|     #[inline] |     #[inline] | ||||||
|     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (**self).read(buf) } |     fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { (**self).read(buf) } | ||||||
| } | } | ||||||
|  |  | ||||||
| impl Writer for Box<NetworkStream + Send> { | impl Writer for Box<NetworkStream + Send> { | ||||||
| @@ -93,7 +93,7 @@ impl Writer for Box<NetworkStream + Send> { | |||||||
|  |  | ||||||
| impl<'a> Reader for &'a mut NetworkStream { | impl<'a> Reader for &'a mut NetworkStream { | ||||||
|     #[inline] |     #[inline] | ||||||
|     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (**self).read(buf) } |     fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { (**self).read(buf) } | ||||||
| } | } | ||||||
|  |  | ||||||
| impl<'a> Writer for &'a mut NetworkStream { | impl<'a> Writer for &'a mut NetworkStream { | ||||||
| @@ -219,7 +219,7 @@ pub enum HttpStream { | |||||||
|  |  | ||||||
| impl Reader for HttpStream { | impl Reader for HttpStream { | ||||||
|     #[inline] |     #[inline] | ||||||
|     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { |     fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { | ||||||
|         match *self { |         match *self { | ||||||
|             Http(ref mut inner) => inner.read(buf), |             Http(ref mut inner) => inner.read(buf), | ||||||
|             Https(ref mut inner) => inner.read(buf) |             Https(ref mut inner) => inner.read(buf) | ||||||
| @@ -287,7 +287,7 @@ impl NetworkConnector<HttpStream> for HttpConnector { | |||||||
| } | } | ||||||
|  |  | ||||||
| fn lift_ssl_error(ssl: SslError) -> IoError { | fn lift_ssl_error(ssl: SslError) -> IoError { | ||||||
|     debug!("lift_ssl_error: {}", ssl); |     debug!("lift_ssl_error: {:?}", ssl); | ||||||
|     match ssl { |     match ssl { | ||||||
|         StreamError(err) => err, |         StreamError(err) => err, | ||||||
|         SslSessionClosed => IoError { |         SslSessionClosed => IoError { | ||||||
| @@ -300,7 +300,7 @@ fn lift_ssl_error(ssl: SslError) -> IoError { | |||||||
|         OpenSslErrors(errs) => IoError { |         OpenSslErrors(errs) => IoError { | ||||||
|             kind: OtherIoError, |             kind: OtherIoError, | ||||||
|             desc: "Error in OpenSSL", |             desc: "Error in OpenSSL", | ||||||
|             detail: Some(format!("{}", errs)) |             detail: Some(format!("{:?}", errs)) | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
| } | } | ||||||
|   | |||||||
| @@ -50,17 +50,17 @@ impl Server<HttpListener> { | |||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L> { | impl<X> Server<X> { | ||||||
| 	/// Binds to a socket, and starts handling connections using a task pool. | 	/// Binds to a socket, and starts handling connections using a task pool. | ||||||
|     /// |     /// | ||||||
|     /// This method has unbound type parameters, so can be used when you want to use |     /// This method has unbound type parameters, so can be used when you want to use | ||||||
|     /// something other than the provided HttpStream, HttpAcceptor, and HttpListener. |     /// something other than the provided HttpStream, HttpAcceptor, and HttpListener. | ||||||
|     pub fn listen_network<H, S, A, L>(self, handler: H, threads: uint) -> HttpResult<Listening<A>> |     pub fn listen_network<H, S, A, L>(self, handler: H, threads: usize) -> HttpResult<Listening<A>> | ||||||
|     where H: Handler, |     where H: Handler, | ||||||
|           S: NetworkStream + Clone, |           S: NetworkStream + Clone, | ||||||
|           A: NetworkAcceptor<S>, |           A: NetworkAcceptor<S>, | ||||||
|           L: NetworkListener<S, A>, { |           L: NetworkListener<S, A>, { | ||||||
|         debug!("binding to {}:{}", self.ip, self.port); |         debug!("binding to {:?}:{:?}", self.ip, self.port); | ||||||
|         let mut listener: L = try!(NetworkListener::<S, A>::bind((self.ip, self.port))); |         let mut listener: L = try!(NetworkListener::<S, A>::bind((self.ip, self.port))); | ||||||
|  |  | ||||||
|         let socket = try!(listener.socket_name()); |         let socket = try!(listener.socket_name()); | ||||||
| @@ -68,9 +68,9 @@ impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L | |||||||
|         let acceptor = try!(listener.listen()); |         let acceptor = try!(listener.listen()); | ||||||
|  |  | ||||||
|         let mut captured = acceptor.clone(); |         let mut captured = acceptor.clone(); | ||||||
|         let guard = Builder::new().name("hyper acceptor".to_string()).spawn(move || { |         let guard = Builder::new().name("hyper acceptor".to_string()).scoped(move || { | ||||||
|             let handler = Arc::new(handler); |             let handler = Arc::new(handler); | ||||||
|             debug!("threads = {}", threads); |             debug!("threads = {:?}", threads); | ||||||
|             let pool = TaskPool::new(threads); |             let pool = TaskPool::new(threads); | ||||||
|             for conn in captured.incoming() { |             for conn in captured.incoming() { | ||||||
|                 match conn { |                 match conn { | ||||||
| @@ -81,7 +81,7 @@ impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L | |||||||
|                             let addr = match stream.peer_name() { |                             let addr = match stream.peer_name() { | ||||||
|                                 Ok(addr) => addr, |                                 Ok(addr) => addr, | ||||||
|                                 Err(e) => { |                                 Err(e) => { | ||||||
|                                     error!("Peer Name error: {}", e); |                                     error!("Peer Name error: {:?}", e); | ||||||
|                                     return; |                                     return; | ||||||
|                                 } |                                 } | ||||||
|                             }; |                             }; | ||||||
| @@ -94,12 +94,12 @@ impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L | |||||||
|                                 let req = match Request::new(&mut rdr, addr) { |                                 let req = match Request::new(&mut rdr, addr) { | ||||||
|                                     Ok(req) => req, |                                     Ok(req) => req, | ||||||
|                                     Err(e@HttpIoError(_)) => { |                                     Err(e@HttpIoError(_)) => { | ||||||
|                                         debug!("ioerror in keepalive loop = {}", e); |                                         debug!("ioerror in keepalive loop = {:?}", e); | ||||||
|                                         return; |                                         return; | ||||||
|                                     } |                                     } | ||||||
|                                     Err(e) => { |                                     Err(e) => { | ||||||
|                                         //TODO: send a 400 response |                                         //TODO: send a 400 response | ||||||
|                                         error!("request error = {}", e); |                                         error!("request error = {:?}", e); | ||||||
|                                         return; |                                         return; | ||||||
|                                     } |                                     } | ||||||
|                                 }; |                                 }; | ||||||
| @@ -111,7 +111,7 @@ impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L | |||||||
|                                 }; |                                 }; | ||||||
|                                 res.version = req.version; |                                 res.version = req.version; | ||||||
|                                 handler.handle(req, res); |                                 handler.handle(req, res); | ||||||
|                                 debug!("keep_alive = {}", keep_alive); |                                 debug!("keep_alive = {:?}", keep_alive); | ||||||
|                             } |                             } | ||||||
|  |  | ||||||
|                         }); |                         }); | ||||||
| @@ -134,9 +134,12 @@ impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L | |||||||
|             socket: socket, |             socket: socket, | ||||||
|         }) |         }) | ||||||
|     } |     } | ||||||
|  | } | ||||||
|  |  | ||||||
|  | #[old_impl_check] | ||||||
|  | impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L> { | ||||||
|     /// Binds to a socket and starts handling connections with the specified number of tasks. |     /// Binds to a socket and starts handling connections with the specified number of tasks. | ||||||
|     pub fn listen_threads<H: Handler>(self, handler: H, threads: uint) -> HttpResult<Listening<HttpAcceptor>> { |     pub fn listen_threads<H: Handler>(self, handler: H, threads: usize) -> HttpResult<Listening<HttpAcceptor>> { | ||||||
|         self.listen_network::<H, HttpStream, HttpAcceptor, HttpListener>(handler, threads) |         self.listen_network::<H, HttpStream, HttpAcceptor, HttpListener>(handler, threads) | ||||||
|     } |     } | ||||||
|  |  | ||||||
| @@ -150,11 +153,12 @@ impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L | |||||||
| /// A listening server, which can later be closed. | /// A listening server, which can later be closed. | ||||||
| pub struct Listening<A = HttpAcceptor> { | pub struct Listening<A = HttpAcceptor> { | ||||||
|     acceptor: A, |     acceptor: A, | ||||||
|     guard: Option<JoinGuard<()>>, |     guard: Option<JoinGuard<'static, ()>>, | ||||||
|     /// The socket addresses that the server is bound to. |     /// The socket addresses that the server is bound to. | ||||||
|     pub socket: SocketAddr, |     pub socket: SocketAddr, | ||||||
| } | } | ||||||
|  |  | ||||||
|  | #[old_impl_check] | ||||||
| impl<A: NetworkAcceptor<S>, S: NetworkStream> Listening<A> { | impl<A: NetworkAcceptor<S>, S: NetworkStream> Listening<A> { | ||||||
|     /// Causes the current thread to wait for this listening to complete. |     /// Causes the current thread to wait for this listening to complete. | ||||||
|     pub fn await(&mut self) { |     pub fn await(&mut self) { | ||||||
|   | |||||||
| @@ -37,9 +37,9 @@ impl<'a> Request<'a> { | |||||||
|     /// immediately useful. |     /// immediately useful. | ||||||
|     pub fn new(mut stream: &'a mut (Reader + 'a), addr: SocketAddr) -> HttpResult<Request<'a>> { |     pub fn new(mut stream: &'a mut (Reader + 'a), addr: SocketAddr) -> HttpResult<Request<'a>> { | ||||||
|         let (method, uri, version) = try!(read_request_line(&mut stream)); |         let (method, uri, version) = try!(read_request_line(&mut stream)); | ||||||
|         debug!("Request Line: {} {} {}", method, uri, version); |         debug!("Request Line: {:?} {:?} {:?}", method, uri, version); | ||||||
|         let headers = try!(Headers::from_raw(&mut stream)); |         let headers = try!(Headers::from_raw(&mut stream)); | ||||||
|         debug!("Headers: [\n{}]", headers); |         debug!("Headers: [\n{:?}]", headers); | ||||||
|  |  | ||||||
|  |  | ||||||
|         let body = if method == Get || method == Head { |         let body = if method == Get || method == Head { | ||||||
| @@ -68,7 +68,7 @@ impl<'a> Request<'a> { | |||||||
| } | } | ||||||
|  |  | ||||||
| impl<'a> Reader for Request<'a> { | impl<'a> Reader for Request<'a> { | ||||||
|     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { |     fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> { | ||||||
|         self.body.read(buf) |         self.body.read(buf) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|   | |||||||
| @@ -67,7 +67,7 @@ impl<'a> Response<'a, Fresh> { | |||||||
|  |  | ||||||
|     /// Consume this Response<Fresh>, writing the Headers and Status and creating a Response<Streaming> |     /// Consume this Response<Fresh>, writing the Headers and Status and creating a Response<Streaming> | ||||||
|     pub fn start(mut self) -> IoResult<Response<'a, Streaming>> { |     pub fn start(mut self) -> IoResult<Response<'a, Streaming>> { | ||||||
|         debug!("writing head: {} {}", self.version, self.status); |         debug!("writing head: {:?} {:?}", self.version, self.status); | ||||||
|         try!(write!(&mut self.body, "{} {}{}{}", self.version, self.status, CR as char, LF as char)); |         try!(write!(&mut self.body, "{} {}{}{}", self.version, self.status, CR as char, LF as char)); | ||||||
|  |  | ||||||
|         if !self.headers.has::<common::Date>() { |         if !self.headers.has::<common::Date>() { | ||||||
| @@ -89,7 +89,7 @@ impl<'a> Response<'a, Fresh> { | |||||||
|         // cant do in match above, thanks borrowck |         // cant do in match above, thanks borrowck | ||||||
|         if chunked { |         if chunked { | ||||||
|             let encodings = match self.headers.get_mut::<common::TransferEncoding>() { |             let encodings = match self.headers.get_mut::<common::TransferEncoding>() { | ||||||
|                 Some(&common::TransferEncoding(ref mut encodings)) => { |                 Some(&mut common::TransferEncoding(ref mut encodings)) => { | ||||||
|                     //TODO: check if chunked is already in encodings. use HashSet? |                     //TODO: check if chunked is already in encodings. use HashSet? | ||||||
|                     encodings.push(common::transfer_encoding::Encoding::Chunked); |                     encodings.push(common::transfer_encoding::Encoding::Chunked); | ||||||
|                     false |                     false | ||||||
| @@ -104,7 +104,7 @@ impl<'a> Response<'a, Fresh> { | |||||||
|         } |         } | ||||||
|  |  | ||||||
|  |  | ||||||
|         debug!("headers [\n{}]", self.headers); |         debug!("headers [\n{:?}]", self.headers); | ||||||
|         try!(write!(&mut self.body, "{}", self.headers)); |         try!(write!(&mut self.body, "{}", self.headers)); | ||||||
|  |  | ||||||
|         try!(self.body.write_str(LINE_ENDING)); |         try!(self.body.write_str(LINE_ENDING)); | ||||||
| @@ -143,7 +143,7 @@ impl<'a> Response<'a, Streaming> { | |||||||
|  |  | ||||||
| impl<'a> Writer for Response<'a, Streaming> { | impl<'a> Writer for Response<'a, Streaming> { | ||||||
|     fn write(&mut self, msg: &[u8]) -> IoResult<()> { |     fn write(&mut self, msg: &[u8]) -> IoResult<()> { | ||||||
|         debug!("write {} bytes", msg.len()); |         debug!("write {:?} bytes", msg.len()); | ||||||
|         self.body.write(msg) |         self.body.write(msg) | ||||||
|     } |     } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -1585,13 +1585,19 @@ impl Copy for StatusCode {} | |||||||
| /// ``` | /// ``` | ||||||
| /// | /// | ||||||
| /// If you wish to just include the number, cast to a u16 instead. | /// If you wish to just include the number, cast to a u16 instead. | ||||||
| impl fmt::Show for StatusCode { | impl fmt::String for StatusCode { | ||||||
|     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         write!(f, "{} {}", *self as u16, |         write!(f, "{} {}", *self as u16, | ||||||
|                self.canonical_reason().unwrap_or("<unknown status code>")) |                self.canonical_reason().unwrap_or("<unknown status code>")) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|  | impl fmt::Show for StatusCode { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  |         self.to_string().fmt(fmt) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
| // Specified manually because the codegen for derived is slow (at the time of writing on the machine | // Specified manually because the codegen for derived is slow (at the time of writing on the machine | ||||||
| // of writing, 1.2 seconds) and verbose (though the optimiser cuts it down to size). | // of writing, 1.2 seconds) and verbose (though the optimiser cuts it down to size). | ||||||
| impl PartialEq for StatusCode { | impl PartialEq for StatusCode { | ||||||
|   | |||||||
| @@ -19,7 +19,7 @@ pub enum HttpVersion { | |||||||
|     Http20 |     Http20 | ||||||
| } | } | ||||||
|  |  | ||||||
| impl fmt::Show for HttpVersion { | impl fmt::String for HttpVersion { | ||||||
|     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|         match *self { |         match *self { | ||||||
|             Http09 => "HTTP/0.9", |             Http09 => "HTTP/0.9", | ||||||
| @@ -29,3 +29,10 @@ impl fmt::Show for HttpVersion { | |||||||
|         }.fmt(fmt) |         }.fmt(fmt) | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
|  | impl fmt::Show for HttpVersion { | ||||||
|  |     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { | ||||||
|  |         self.to_string().fmt(fmt) | ||||||
|  |     } | ||||||
|  | } | ||||||
|  |  | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user