diff --git a/examples/client.rs b/examples/client.rs index 02961ea4..abcbb9e9 100644 --- a/examples/client.rs +++ b/examples/client.rs @@ -22,14 +22,14 @@ fn main() { let mut res = match client.get(url).send() { Ok(res) => res, - Err(err) => panic!("Failed to connect: {}", err) + Err(err) => panic!("Failed to connect: {:?}", err) }; println!("Response: {}", res.status); println!("Headers:\n{}", res.headers); match copy(&mut res, &mut stdout()) { Ok(..) => (), - Err(e) => panic!("Stream failure: {}", e) + Err(e) => panic!("Stream failure: {:?}", e) }; } diff --git a/src/client/mod.rs b/src/client/mod.rs index 3eddc4b3..71d3d096 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -63,6 +63,7 @@ impl Client { } +#[old_impl_check] impl, S: NetworkStream> Client { /// Create a new client with a specific connector. @@ -162,7 +163,7 @@ impl<'a, U: IntoUrl, C: NetworkConnector, S: NetworkStream> RequestBuilder<'a pub fn send(self) -> HttpResult { let RequestBuilder { client, method, url, headers, body } = self; let mut url = try!(url.into_url()); - debug!("client.request {} {}", method, url); + debug!("client.request {:?} {:?}", method, url); let can_have_body = match &method { &Method::Get | &Method::Head => false, @@ -193,13 +194,13 @@ impl<'a, U: IntoUrl, C: NetworkConnector, S: NetworkStream> RequestBuilder<'a if res.status.class() != Redirection { return Ok(res) } - debug!("redirect code {} for {}", res.status, url); + debug!("redirect code {:?} for {:?}", res.status, url); let loc = { // punching borrowck here let loc = match res.headers.get::() { Some(&Location(ref loc)) => { - Some(UrlParser::new().base_url(&url).parse(loc[])) + Some(UrlParser::new().base_url(&url).parse(&loc[])) } None => { debug!("no Location header"); @@ -217,7 +218,7 @@ impl<'a, U: IntoUrl, C: NetworkConnector, S: NetworkStream> RequestBuilder<'a inspect!("Location", u) }, Err(e) => { - debug!("Location header had invalid URI: {}", e); + debug!("Location header had invalid URI: {:?}", e); return Ok(res); } }; @@ -242,13 +243,13 @@ pub enum Body<'a> { /// A Reader does not necessarily know it's size, so it is chunked. ChunkedBody(&'a mut (Reader + 'a)), /// 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. - BufBody(&'a [u8] , uint), + BufBody(&'a [u8] , usize), } impl<'a> Body<'a> { - fn size(&self) -> Option { + fn size(&self) -> Option { match *self { Body::SizedBody(_, len) | Body::BufBody(_, len) => Some(len), _ => None @@ -258,7 +259,7 @@ impl<'a> Body<'a> { impl<'a> Reader for Body<'a> { #[inline] - fn read(&mut self, buf: &mut [u8]) -> IoResult { + fn read(&mut self, buf: &mut [u8]) -> IoResult { match *self { Body::ChunkedBody(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, None => return Err(HttpUriError(UrlError::EmptyHost)) }; - debug!("host={}", host); + debug!("host={:?}", host); let port = match url.port_or_default() { Some(port) => port, None => return Err(HttpUriError(UrlError::InvalidPort)) }; - debug!("port={}", port); + debug!("port={:?}", port); Ok((host, port)) } diff --git a/src/client/request.rs b/src/client/request.rs index 8b97034b..5cf8eecd 100644 --- a/src/client/request.rs +++ b/src/client/request.rs @@ -47,10 +47,10 @@ impl Request { /// Create a new client request with a specific underlying NetworkStream. pub fn with_connector, S: NetworkStream>(method: method::Method, url: Url, connector: &mut C) -> HttpResult> { - debug!("{} {}", method, url); + debug!("{:?} {:?}", method, 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)); let mut headers = Headers::new(); @@ -110,17 +110,17 @@ impl Request { //TODO: this needs a test if let Some(ref q) = self.url.query { 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, "{} {} {}{}", self.method, uri, self.version, LINE_ENDING)); let stream = match self.method { Get | Head => { - debug!("headers [\n{}]", self.headers); + debug!("headers [\n{:?}]", self.headers); try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING)); EmptyWriter(self.body.unwrap()) }, @@ -139,7 +139,7 @@ impl Request { // cant do in match above, thanks borrowck if chunked { let encodings = match self.headers.get_mut::() { - Some(&common::TransferEncoding(ref mut encodings)) => { + Some(&mut common::TransferEncoding(ref mut encodings)) => { //TODO: check if chunked is already in encodings. use HashSet? encodings.push(common::transfer_encoding::Encoding::Chunked); false @@ -153,7 +153,7 @@ impl Request { } } - debug!("headers [\n{}]", self.headers); + debug!("headers [\n{:?}]", self.headers); try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING)); if chunked { @@ -218,7 +218,7 @@ mod tests { let stream = *req.body.end().unwrap() .into_inner().downcast::().ok().unwrap(); 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("Transfer-Encoding:")); } @@ -232,7 +232,7 @@ mod tests { let stream = *req.body.end().unwrap() .into_inner().downcast::().ok().unwrap(); 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("Transfer-Encoding:")); } diff --git a/src/client/response.rs b/src/client/response.rs index 49ab4ea2..73150b7c 100644 --- a/src/client/response.rs +++ b/src/client/response.rs @@ -35,16 +35,16 @@ impl Response { Some(status) => status, None => return Err(HttpStatusError) }; - debug!("{} {}", version, status); + debug!("{:?} {:?}", version, status); let headers = try!(header::Headers::from_raw(&mut stream)); - debug!("Headers: [\n{}]", headers); + debug!("Headers: [\n{:?}]", headers); let body = if headers.has::() { match headers.get::() { Some(&TransferEncoding(ref codings)) => { if codings.len() > 1 { - debug!("TODO: #2 handle other codings: {}", codings); + debug!("TODO: #2 handle other codings: {:?}", codings); }; if codings.contains(&Chunked) { @@ -88,7 +88,7 @@ impl Response { impl Reader for Response { #[inline] - fn read(&mut self, buf: &mut [u8]) -> IoResult { + fn read(&mut self, buf: &mut [u8]) -> IoResult { self.body.read(buf) } } diff --git a/src/header/common/accept.rs b/src/header/common/accept.rs index 79e2252f..d5527824 100644 --- a/src/header/common/accept.rs +++ b/src/header/common/accept.rs @@ -28,7 +28,7 @@ use mime; #[derive(Clone, PartialEq, Show)] pub struct Accept(pub Vec>); -deref!(Accept -> Vec>); +deref!(Accept => Vec>); impl header::Header for Accept { fn header_name(_: Option) -> &'static str { @@ -43,7 +43,7 @@ impl header::Header for Accept { impl header::HeaderFormat for Accept { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - shared::fmt_comma_delimited(fmt, self[]) + shared::fmt_comma_delimited(fmt, &self[]) } } diff --git a/src/header/common/accept_encoding.rs b/src/header/common/accept_encoding.rs index 5f86794e..0595ce4f 100644 --- a/src/header/common/accept_encoding.rs +++ b/src/header/common/accept_encoding.rs @@ -10,7 +10,7 @@ use header::shared; #[derive(Clone, PartialEq, Show)] pub struct AcceptEncoding(pub Vec>); -deref!(AcceptEncoding -> Vec>); +deref!(AcceptEncoding => Vec>); impl header::Header for AcceptEncoding { fn header_name(_: Option) -> &'static str { @@ -24,7 +24,7 @@ impl header::Header for AcceptEncoding { impl header::HeaderFormat for AcceptEncoding { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - shared::fmt_comma_delimited(fmt, self[]) + shared::fmt_comma_delimited(fmt, &self[]) } } diff --git a/src/header/common/access_control/allow_origin.rs b/src/header/common/access_control/allow_origin.rs index dfb1d118..07f67508 100644 --- a/src/header/common/access_control/allow_origin.rs +++ b/src/header/common/access_control/allow_origin.rs @@ -19,7 +19,7 @@ impl header::Header for AccessControlAllowOrigin { fn parse_header(raw: &[Vec]) -> Option { if raw.len() == 1 { - match str::from_utf8(unsafe { raw[].get_unchecked(0)[] }) { + match str::from_utf8(unsafe { &raw[].get_unchecked(0)[] }) { Ok(s) => { if s == "*" { Some(AccessControlAllowOrigin::AllowStar) diff --git a/src/header/common/allow.rs b/src/header/common/allow.rs index b49d29d6..666df2e8 100644 --- a/src/header/common/allow.rs +++ b/src/header/common/allow.rs @@ -9,7 +9,7 @@ use header::shared::util::{from_comma_delimited, fmt_comma_delimited}; #[derive(Clone, PartialEq, Show)] pub struct Allow(pub Vec); -deref!(Allow -> Vec); +deref!(Allow => Vec); impl Header for Allow { fn header_name(_: Option) -> &'static str { @@ -23,7 +23,7 @@ impl Header for Allow { impl HeaderFormat for Allow { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt_comma_delimited(fmt, self[]) + fmt_comma_delimited(fmt, &self[]) } } diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs index 7a8df60c..e4905366 100644 --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -29,7 +29,7 @@ impl Header for Authorization { fn parse_header(raw: &[Vec]) -> Option> { if raw.len() == 1 { - match (from_utf8(unsafe { raw[].get_unchecked(0)[] }), Scheme::scheme(None::)) { + match (from_utf8(unsafe { &raw[].get_unchecked(0)[] }), Scheme::scheme(None::)) { (Ok(header), Some(scheme)) if header.starts_with(scheme) && header.len() > scheme.len() + 1 => { header[scheme.len() + 1..].parse::().map(|s| Authorization(s)) @@ -96,7 +96,7 @@ impl Scheme for Basic { let mut text = self.username.clone(); text.push(':'); if let Some(ref pass) = self.password { - text.push_str(pass[]); + text.push_str(&pass[]); } text.as_bytes().to_base64(Config { char_set: Standard, @@ -112,7 +112,7 @@ impl FromStr for Basic { match s.from_base64() { Ok(decoded) => match String::from_utf8(decoded) { Ok(text) => { - let mut parts = text[].split(':'); + let mut parts = &mut text[].split(':'); let user = match parts.next() { Some(part) => part.to_string(), None => return None @@ -127,12 +127,12 @@ impl FromStr for Basic { }) }, Err(e) => { - debug!("Basic::from_utf8 error={}", e); + debug!("Basic::from_utf8 error={:?}", e); None } }, Err(e) => { - debug!("Basic::from_base64 error={}", e); + debug!("Basic::from_base64 error={:?}", e); None } } @@ -159,7 +159,7 @@ mod tests { #[test] fn test_raw_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: foo bar baz\r\n\r\n")).unwrap(); - assert_eq!(headers.get::>().unwrap().0[], "foo bar baz"); + assert_eq!(&headers.get::>().unwrap().0[], "foo bar baz"); } #[test] @@ -180,7 +180,7 @@ mod tests { fn test_basic_auth_parse() { let headers = Headers::from_raw(&mut mem("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n\r\n")).unwrap(); let auth = headers.get::>().unwrap(); - assert_eq!(auth.0.username[], "Aladdin"); + assert_eq!(&auth.0.username[], "Aladdin"); assert_eq!(auth.0.password, Some("open sesame".to_string())); } diff --git a/src/header/common/cache_control.rs b/src/header/common/cache_control.rs index 0cb0dbef..cb94f4cb 100644 --- a/src/header/common/cache_control.rs +++ b/src/header/common/cache_control.rs @@ -7,7 +7,7 @@ use header::shared::util::{from_one_comma_delimited, fmt_comma_delimited}; #[derive(PartialEq, Clone, Show)] pub struct CacheControl(pub Vec); -deref!(CacheControl -> Vec); +deref!(CacheControl => Vec); impl Header for CacheControl { fn header_name(_: Option) -> &'static str { @@ -16,7 +16,7 @@ impl Header for CacheControl { fn parse_header(raw: &[Vec]) -> Option { let directives = raw.iter() - .filter_map(|line| from_one_comma_delimited(line[])) + .filter_map(|line| from_one_comma_delimited(&line[])) .collect::>>() .concat(); if directives.len() > 0 { @@ -29,7 +29,7 @@ impl Header for CacheControl { impl HeaderFormat for CacheControl { 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 /// "max-age=delta" - MaxAge(uint), + MaxAge(usize), /// "max-stale=delta" - MaxStale(uint), + MaxStale(usize), /// "min-fresh=delta" - MinFresh(uint), + MinFresh(usize), // response directives /// "must-revalidate" @@ -63,13 +63,13 @@ pub enum CacheDirective { /// "proxy-revalidate" ProxyRevalidate, /// "s-maxage=delta" - SMaxAge(uint), + SMaxAge(usize), /// Extension directives. Optionally include an argument. Extension(String, Option) } -impl fmt::Show for CacheDirective { +impl fmt::String for CacheDirective { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::CacheDirective::*; match *self { @@ -88,13 +88,18 @@ impl fmt::Show for CacheDirective { ProxyRevalidate => "proxy-revalidate", 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), }.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 { fn from_str(s: &str) -> Option { use self::CacheDirective::*; @@ -109,7 +114,7 @@ impl FromStr for CacheDirective { "proxy-revalidate" => Some(ProxyRevalidate), "" => None, _ => 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-stale", secs) => secs.parse().map(MaxStale), ("min-fresh", secs) => secs.parse().map(MinFresh), diff --git a/src/header/common/connection.rs b/src/header/common/connection.rs index daed4bf3..1a631af8 100644 --- a/src/header/common/connection.rs +++ b/src/header/common/connection.rs @@ -9,7 +9,7 @@ pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader}; #[derive(Clone, PartialEq, Show)] pub struct Connection(pub Vec); -deref!(Connection -> Vec); +deref!(Connection => Vec); /// Values that can be in the `Connection` header. #[derive(Clone, PartialEq)] @@ -39,16 +39,22 @@ impl FromStr for ConnectionOption { } } -impl fmt::Show for ConnectionOption { +impl fmt::String for ConnectionOption { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - match *self { + write!(fmt, "{}", match *self { KeepAlive => "keep-alive", Close => "close", 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) + } +} + impl Header for Connection { fn header_name(_: Option) -> &'static str { "Connection" @@ -62,7 +68,7 @@ impl Header for Connection { impl HeaderFormat for Connection { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let Connection(ref parts) = *self; - fmt_comma_delimited(fmt, parts[]) + fmt_comma_delimited(fmt, &parts[]) } } diff --git a/src/header/common/content_length.rs b/src/header/common/content_length.rs index 13bb9f41..b91c3a2c 100644 --- a/src/header/common/content_length.rs +++ b/src/header/common/content_length.rs @@ -5,11 +5,11 @@ use header::shared::util::from_one_raw_str; /// The `Content-Length` header. /// -/// Simply a wrapper around a `uint`. +/// Simply a wrapper around a `usize`. #[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 { fn header_name(_: Option) -> &'static str { @@ -32,7 +32,7 @@ impl ContentLength { /// Returns the wrapped length. #[deprecated = "use Deref instead"] #[inline] - pub fn len(&self) -> uint { + pub fn len(&self) -> usize { **self } } diff --git a/src/header/common/content_type.rs b/src/header/common/content_type.rs index 1ccdbe86..cd421c5f 100644 --- a/src/header/common/content_type.rs +++ b/src/header/common/content_type.rs @@ -10,7 +10,7 @@ use mime::Mime; #[derive(Clone, PartialEq, Show)] pub struct ContentType(pub Mime); -deref!(ContentType -> Mime); +deref!(ContentType => Mime); impl Header for ContentType { fn header_name(_: Option) -> &'static str { diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs index dedb9496..bf0e658e 100644 --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -20,7 +20,7 @@ pub struct Cookies(pub Vec); unsafe impl Send for Cookies {} unsafe impl Sync for Cookies {} -deref!(Cookies -> Vec); +deref!(Cookies => Vec); impl Header for Cookies { fn header_name(_: Option) -> &'static str { @@ -30,7 +30,7 @@ impl Header for Cookies { fn parse_header(raw: &[Vec]) -> Option { let mut cookies = Vec::with_capacity(raw.len()); for cookies_raw in raw.iter() { - match from_utf8(cookies_raw[]) { + match from_utf8(&cookies_raw[]) { Ok(cookies_str) => { for cookie_str in cookies_str.split(';') { match cookie_str.trim().parse() { @@ -56,8 +56,8 @@ impl HeaderFormat for Cookies { let cookies = &self.0; let last = cookies.len() - 1; for (i, cookie) in cookies.iter().enumerate() { - try!(cookie.pair().fmt(fmt)); - if i < last { + try!(write!(fmt, "{}", cookie.pair())); + if i < last { try!("; ".fmt(fmt)); } } @@ -86,7 +86,7 @@ impl Cookies { #[test] 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 c2 = Cookie::new("baz".to_string(), "quux".to_string()); assert_eq!(h, Some(Cookies(vec![c1, c2]))); @@ -103,7 +103,7 @@ fn test_fmt() { let mut headers = Headers::new(); 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] diff --git a/src/header/common/date.rs b/src/header/common/date.rs index d7542799..50eb83ef 100644 --- a/src/header/common/date.rs +++ b/src/header/common/date.rs @@ -10,7 +10,7 @@ use header::shared::time::tm_from_str; #[derive(Copy, PartialEq, Clone)] pub struct Date(pub Tm); -deref!(Date -> Tm); +deref!(Date => Tm); impl Header for Date { fn header_name(_: Option) -> &'static str { diff --git a/src/header/common/etag.rs b/src/header/common/etag.rs index 93164245..fa53a789 100644 --- a/src/header/common/etag.rs +++ b/src/header/common/etag.rs @@ -38,8 +38,8 @@ impl Header for Etag { from_one_raw_str(raw).and_then(|s: String| { - let length: uint = s.len(); - let slice = s[]; + let length: usize = s.len(); + let slice = &s[]; // Early exits: // 1. The string is empty, or, diff --git a/src/header/common/expires.rs b/src/header/common/expires.rs index 638d928d..782c10d0 100644 --- a/src/header/common/expires.rs +++ b/src/header/common/expires.rs @@ -9,7 +9,7 @@ use header::shared::time::tm_from_str; #[derive(Copy, PartialEq, Clone)] pub struct Expires(pub Tm); -deref!(Expires -> Tm); +deref!(Expires => Tm); impl Header for Expires { fn header_name(_: Option) -> &'static str { diff --git a/src/header/common/host.rs b/src/header/common/host.rs index a9d23602..82b204e3 100644 --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -28,7 +28,7 @@ impl Header for Host { // FIXME: use rust-url to parse this // https://github.com/servo/rust-url/issues/42 let idx = { - let slice = s[]; + let slice = &s[]; if slice.char_at(1) == '[' { match slice.rfind(']') { Some(idx) => { diff --git a/src/header/common/if_modified_since.rs b/src/header/common/if_modified_since.rs index af5e9bdd..6090714f 100644 --- a/src/header/common/if_modified_since.rs +++ b/src/header/common/if_modified_since.rs @@ -9,7 +9,7 @@ use header::shared::time::tm_from_str; #[derive(Copy, PartialEq, Clone)] pub struct IfModifiedSince(pub Tm); -deref!(IfModifiedSince -> Tm); +deref!(IfModifiedSince => Tm); impl Header for IfModifiedSince { fn header_name(_: Option) -> &'static str { diff --git a/src/header/common/last_modified.rs b/src/header/common/last_modified.rs index e9b06afa..9b963b67 100644 --- a/src/header/common/last_modified.rs +++ b/src/header/common/last_modified.rs @@ -9,7 +9,7 @@ use header::shared::time::tm_from_str; #[derive(Copy, PartialEq, Clone)] pub struct LastModified(pub Tm); -deref!(LastModified -> Tm); +deref!(LastModified => Tm); impl Header for LastModified { fn header_name(_: Option) -> &'static str { diff --git a/src/header/common/location.rs b/src/header/common/location.rs index ace1c777..7541271a 100644 --- a/src/header/common/location.rs +++ b/src/header/common/location.rs @@ -16,7 +16,7 @@ use header::shared::util::from_one_raw_str; #[derive(Clone, PartialEq, Show)] pub struct Location(pub String); -deref!(Location -> String); +deref!(Location => String); impl Header for Location { fn header_name(_: Option) -> &'static str { diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs index dff6373e..ed684f84 100644 --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -42,13 +42,13 @@ macro_rules! bench_header( fn bench_parse(b: &mut Bencher) { let val = $value; b.iter(|| { - let _: $ty = Header::parse_header(val[]).unwrap(); + let _: $ty = Header::parse_header(&val[]).unwrap(); }); } #[bench] 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); b.iter(|| { format!("{}", fmt); @@ -59,7 +59,7 @@ macro_rules! bench_header( ); macro_rules! deref( - ($from:ty -> $to:ty) => { + ($from:ty => $to:ty) => { impl ::std::ops::Deref for $from { type Target = $to; diff --git a/src/header/common/server.rs b/src/header/common/server.rs index 4ae1a369..170f8597 100644 --- a/src/header/common/server.rs +++ b/src/header/common/server.rs @@ -8,7 +8,7 @@ use header::shared::util::from_one_raw_str; #[derive(Clone, PartialEq, Show)] pub struct Server(pub String); -deref!(Server -> String); +deref!(Server => String); impl Header for Server { fn header_name(_: Option) -> &'static str { diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs index 57f08633..34572423 100644 --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -17,7 +17,7 @@ pub struct SetCookie(pub Vec); unsafe impl Send for SetCookie {} unsafe impl Sync for SetCookie {} -deref!(SetCookie -> Vec); +deref!(SetCookie => Vec); impl Header for SetCookie { fn header_name(_: Option) -> &'static str { @@ -27,7 +27,7 @@ impl Header for SetCookie { fn parse_header(raw: &[Vec]) -> Option { let mut set_cookies = Vec::with_capacity(raw.len()); 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() => { match s.parse() { Some(cookie) => set_cookies.push(cookie), @@ -80,7 +80,7 @@ impl SetCookie { #[test] 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()); c1.httponly = true; @@ -98,7 +98,7 @@ fn test_fmt() { let mut headers = Headers::new(); 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] diff --git a/src/header/common/transfer_encoding.rs b/src/header/common/transfer_encoding.rs index 480a559c..4edddf21 100644 --- a/src/header/common/transfer_encoding.rs +++ b/src/header/common/transfer_encoding.rs @@ -21,7 +21,7 @@ use self::Encoding::{Chunked, Gzip, Deflate, Compress, EncodingExt}; #[derive(Clone, PartialEq, Show)] pub struct TransferEncoding(pub Vec); -deref!(TransferEncoding -> Vec); +deref!(TransferEncoding => Vec); /// A value to be used with the `Transfer-Encoding` header. /// @@ -47,18 +47,24 @@ pub enum Encoding { EncodingExt(String) } -impl fmt::Show for Encoding { +impl fmt::String for Encoding { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - match *self { + write!(fmt, "{}", match *self { Chunked => "chunked", Gzip => "gzip", Deflate => "deflate", Compress => "compress", 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) + } +} + impl FromStr for Encoding { fn from_str(s: &str) -> Option { match s { @@ -83,7 +89,7 @@ impl Header for TransferEncoding { impl HeaderFormat for TransferEncoding { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt_comma_delimited(fmt, self[]) + fmt_comma_delimited(fmt, &self[]) } } diff --git a/src/header/common/upgrade.rs b/src/header/common/upgrade.rs index a81b374f..31635a19 100644 --- a/src/header/common/upgrade.rs +++ b/src/header/common/upgrade.rs @@ -9,7 +9,7 @@ use self::Protocol::{WebSocket, ProtocolExt}; #[derive(Clone, PartialEq, Show)] pub struct Upgrade(pub Vec); -deref!(Upgrade -> Vec); +deref!(Upgrade => Vec); /// Protocol values that can appear in the Upgrade header. #[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 { - match *self { + write!(fmt, "{}", match *self { WebSocket => "websocket", 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 { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let Upgrade(ref parts) = *self; - fmt_comma_delimited(fmt, parts[]) + fmt_comma_delimited(fmt, &parts[]) } } diff --git a/src/header/common/user_agent.rs b/src/header/common/user_agent.rs index 2d477ddb..60291e47 100644 --- a/src/header/common/user_agent.rs +++ b/src/header/common/user_agent.rs @@ -8,7 +8,7 @@ use header::shared::util::from_one_raw_str; #[derive(Clone, PartialEq, Show)] pub struct UserAgent(pub String); -deref!(UserAgent -> String); +deref!(UserAgent => String); impl Header for UserAgent { fn header_name(_: Option) -> &'static str { diff --git a/src/header/common/vary.rs b/src/header/common/vary.rs index dcb80186..74a5280a 100644 --- a/src/header/common/vary.rs +++ b/src/header/common/vary.rs @@ -20,7 +20,7 @@ impl Header for Vary { fn parse_header(raw: &[Vec]) -> Option { from_one_raw_str(raw).and_then(|s: String| { - let slice = s[]; + let slice = &s[]; match slice { "" => None, "*" => Some(Vary::Any), @@ -34,7 +34,7 @@ impl HeaderFormat for Vary { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Vary::Any => { write!(fmt, "*") } - Vary::Headers(ref fields) => { fmt_comma_delimited(fmt, fields[]) } + Vary::Headers(ref fields) => { fmt_comma_delimited(fmt, &fields[]) } } } } diff --git a/src/header/mod.rs b/src/header/mod.rs index 4281092c..f3ea3eef 100644 --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -134,15 +134,15 @@ impl Headers { loop { match try!(http::read_header(rdr)) { Some((name, value)) => { - debug!("raw header: {}={}", name, value[]); + debug!("raw header: {:?}={:?}", name, &value[]); 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::Occupied(entry) => entry.into_mut() }; match &mut item.borrow_mut().raw { - &Some(ref mut raw) => raw.push(value), + &mut Some(ref mut raw) => raw.push(value), // Unreachable _ => {} }; @@ -178,7 +178,7 @@ impl Headers { .get(&CaseInsensitive(Borrowed(unsafe { mem::transmute::<&str, &str>(name) }))) .and_then(|item| { 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| { @@ -189,7 +189,7 @@ impl Headers { let item = item.borrow(); 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. - pub fn len(&self) -> uint { + pub fn len(&self) -> usize { 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 { for header in self.iter() { 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. pub struct HeadersItems<'a> { inner: Iter<'a, CaseInsensitive, MuCell> @@ -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 { 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> for Headers { fn extend>>(&mut self, mut iter: I) { for header in iter { @@ -375,7 +387,7 @@ fn get_or_parse(item: &MuCell) -> Option<&MuCell match item.borrow().typed { Some(ref typed) if typed.is::() => return Some(item), Some(ref typed) => { - warn!("attempted to access {} as wrong type", typed); + warn!("attempted to access {:?} as wrong type", typed); return None; } _ => () @@ -394,7 +406,7 @@ fn get_or_parse_mut(item: &mut MuCell) -> Option let is_correct_type = match item.borrow().typed { Some(ref typed) if typed.is::() => Some(true), Some(ref typed) => { - warn!("attempted to access {} as wrong type", typed); + warn!("attempted to access {:?} as wrong type", typed); Some(false) } _ => None @@ -416,7 +428,7 @@ fn get_or_parse_mut(item: &mut MuCell) -> Option fn parse(item: &mut Item) { item.typed = match item.raw { - Some(ref raw) => match Header::parse_header(raw[]) { + Some(ref raw) => match Header::parse_header(&raw[]) { Some::(h) => Some(box h as Box), None => None }, @@ -432,17 +444,17 @@ unsafe fn downcast_mut(item: &mut Item) -> &mut H { 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 { match self.typed { Some(ref h) => h.fmt_header(fmt), None => match self.raw { Some(ref raw) => { for part in raw.iter() { - match from_utf8(part[]) { + match from_utf8(&part[]) { Ok(s) => try!(fmt.write_str(s)), 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); } } @@ -455,12 +467,24 @@ impl fmt::Show for Item { } } -impl fmt::Show for Box { +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 { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { (**self).fmt_header(fmt) } } +impl fmt::Show for Box { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + self.to_string().fmt(fmt) + } +} + /// Case-insensitive string. 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 { 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 hash::Hash for CaseInsensitive { +impl hash::Hash for CaseInsensitive { #[inline] fn hash(&self, hasher: &mut H) { for b in self.as_slice().bytes() { @@ -514,6 +544,12 @@ impl hash::Hash for CaseInsensitive { /// outgoing TcpStream. 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> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_header(f) @@ -525,7 +561,7 @@ mod tests { use std::io::MemReader; use std::fmt; use std::borrow::Cow::Borrowed; - use std::hash::sip::hash; + use std::hash::{SipHasher, hash}; use mime::Mime; use mime::TopLevel::Text; use mime::SubLevel::Plain; @@ -546,7 +582,7 @@ mod tests { let b = CaseInsensitive(Borrowed("FOOBAR")); assert_eq!(a, b); - assert_eq!(hash(&a), hash(&b)); + assert_eq!(hash::<_, SipHasher>(&a), hash::<_, SipHasher>(&b)); } #[test] @@ -574,7 +610,7 @@ mod tests { } #[derive(Clone, Show)] - struct CrazyLength(Option, uint); + struct CrazyLength(Option, usize); impl Header for CrazyLength { fn header_name(_: Option) -> &'static str { @@ -588,7 +624,7 @@ mod tests { return None; } // 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), Err(_) => None }.map(|u| CrazyLength(Some(false), u)) @@ -598,7 +634,7 @@ mod tests { impl HeaderFormat for CrazyLength { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 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::>(); pieces.sort(); let s = pieces.into_iter().rev().collect::>().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] @@ -664,7 +700,7 @@ mod tests { let mut headers = Headers::new(); headers.set(ContentLength(10)); 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))); } diff --git a/src/header/shared/encoding.rs b/src/header/shared/encoding.rs index 67e91cd1..d50c4635 100644 --- a/src/header/shared/encoding.rs +++ b/src/header/shared/encoding.rs @@ -23,18 +23,24 @@ pub enum Encoding { EncodingExt(String) } -impl fmt::Show for Encoding { +impl fmt::String for Encoding { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - match *self { + write!(fmt, "{}", match *self { Chunked => "chunked", Gzip => "gzip", Deflate => "deflate", Compress => "compress", Identity => "identity", 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) + } +} impl str::FromStr for Encoding { fn from_str(s: &str) -> Option { diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs index 04bad305..e7405e34 100644 --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -26,7 +26,13 @@ impl QualityItem { } } -impl fmt::Show for QualityItem { +impl fmt::String for QualityItem { + 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 fmt::Show for QualityItem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}; q={}", self.item, format!("{:.3}", self.quality).trim_right_matches(['0', '.'].as_slice())) } diff --git a/src/header/shared/util.rs b/src/header/shared/util.rs index 73d0422c..ab8b14fc 100644 --- a/src/header/shared/util.rs +++ b/src/header/shared/util.rs @@ -9,7 +9,7 @@ pub fn from_one_raw_str(raw: &[Vec]) -> Option { return None; } // 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), Err(_) => None } @@ -22,7 +22,7 @@ pub fn from_comma_delimited(raw: &[Vec]) -> Option> return None; } // 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. @@ -40,7 +40,7 @@ pub fn from_one_comma_delimited(raw: &[u8]) -> Option> { } /// Format an array into a comma-delimited string. -pub fn fmt_comma_delimited(fmt: &mut fmt::Formatter, parts: &[T]) -> fmt::Result { +pub fn fmt_comma_delimited(fmt: &mut fmt::Formatter, parts: &[T]) -> fmt::Result { let last = parts.len() - 1; for (i, part) in parts.iter().enumerate() { try!(write!(fmt, "{}", part)); diff --git a/src/http.rs b/src/http.rs index fb1cf0f7..3bbff7c3 100644 --- a/src/http.rs +++ b/src/http.rs @@ -30,9 +30,9 @@ use self::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; /// include a Content-Length header. pub enum HttpReader { /// 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`. - ChunkedReader(R, Option), + ChunkedReader(R, Option), /// 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 @@ -68,10 +68,10 @@ impl HttpReader { } impl Reader for HttpReader { - fn read(&mut self, buf: &mut [u8]) -> IoResult { + fn read(&mut self, buf: &mut [u8]) -> IoResult { match *self { SizedReader(ref mut body, ref mut remaining) => { - debug!("Sized read, remaining={}", remaining); + debug!("Sized read, remaining={:?}", remaining); if *remaining == 0 { Err(io::standard_error(io::EndOfFile)) } else { @@ -90,7 +90,7 @@ impl Reader for HttpReader { // None means we don't know the size of the next chunk None => try!(read_chunk_size(body)) }; - debug!("Chunked read, remaining={}", rem); + debug!("Chunked read, remaining={:?}", rem); if rem == 0 { *opt_remaining = Some(0); @@ -133,8 +133,8 @@ fn eat(rdr: &mut R, bytes: &[u8]) -> IoResult<()> { } /// Chunked chunks start with 1*HEXDIGIT, indicating the size of the chunk. -fn read_chunk_size(rdr: &mut R) -> IoResult { - let mut size = 0u; +fn read_chunk_size(rdr: &mut R) -> IoResult { + let mut size = 0us; let radix = 16; let mut in_ext = false; let mut in_chunk_size = true; @@ -142,15 +142,15 @@ fn read_chunk_size(rdr: &mut R) -> IoResult { match try!(rdr.read_byte()) { b@b'0'...b'9' if in_chunk_size => { size *= radix; - size += (b - b'0') as uint; + size += (b - b'0') as usize; }, b@b'a'...b'f' if in_chunk_size => { 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 => { size *= radix; - size += (b + 10 - b'A') as uint; + size += (b + 10 - b'A') as usize; }, CR => { match try!(rdr.read_byte()) { @@ -183,7 +183,7 @@ fn read_chunk_size(rdr: &mut R) -> IoResult { } } } - debug!("chunk size={}", size); + debug!("chunk size={:?}", size); Ok(size) } @@ -196,7 +196,7 @@ pub enum HttpWriter { /// A Writer for when Content-Length is set. /// /// 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. EmptyWriter(W), } @@ -257,7 +257,7 @@ impl Writer for HttpWriter { ThroughWriter(ref mut w) => w.write(msg), ChunkedWriter(ref mut w) => { 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!(w.write(msg)); w.write_str(LINE_ENDING) @@ -311,12 +311,18 @@ pub struct LineEnding; impl Copy for LineEnding {} -impl fmt::Show for LineEnding { +impl fmt::String for LineEnding { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 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. /// /// > ```notrust @@ -392,7 +398,7 @@ pub fn read_method(stream: &mut R) -> HttpResult { return Err(HttpMethodError); } - let maybe_method = match buf[0..7] { + let maybe_method = match &buf[0..7] { b"GET " => Some(method::Method::Get), b"PUT " => Some(method::Method::Put), b"POST " => Some(method::Method::Post), @@ -405,9 +411,9 @@ pub fn read_method(stream: &mut R) -> HttpResult { _ => None, }; - debug!("maybe_method = {}", maybe_method); + debug!("maybe_method = {:?}", maybe_method); - match (maybe_method, buf[]) { + match (maybe_method, &buf[]) { (Some(method), _) => Ok(method), (None, ext) => { // We already checked that the buffer is ASCII @@ -442,7 +448,7 @@ pub fn read_uri(stream: &mut R) -> HttpResult { } } - debug!("uri buf = {}", s); + debug!("uri buf = {:?}", s); if s.as_slice().starts_with("/") { Ok(AbsolutePath(s)) @@ -491,8 +497,8 @@ pub fn read_http_version(stream: &mut R) -> HttpResult { } } -const MAX_HEADER_NAME_LENGTH: uint = 100; -const MAX_HEADER_FIELD_LENGTH: uint = 1000; +const MAX_HEADER_NAME_LENGTH: usize = 100; +const MAX_HEADER_FIELD_LENGTH: usize = 1000; /// The raw bytes when parsing a header line. /// @@ -541,7 +547,7 @@ pub fn read_header(stream: &mut R) -> HttpResult(stream: &mut R) -> HttpResult { debug!("read request line"); let method = try!(read_method(stream)); - debug!("method = {}", method); + debug!("method = {:?}", method); let uri = try!(read_uri(stream)); - debug!("uri = {}", uri); + debug!("uri = {:?}", uri); let version = try!(read_http_version(stream)); - debug!("version = {}", version); + debug!("version = {:?}", version); if try!(stream.read_byte()) != CR { return Err(HttpVersionError); @@ -660,7 +666,7 @@ pub fn read_status(stream: &mut R) -> HttpResult { b => match bufwrt.write_u8(b) { Ok(_) => (), Err(_) => { - for _ in range(0u, 128) { + for _ in range(0us, 128) { match try!(stream.read_byte()) { CR => match try!(stream.read_byte()) { LF => break 'read, @@ -676,7 +682,7 @@ pub fn read_status(stream: &mut R) -> HttpResult { } } - let reason = match str::from_utf8(buf[]) { + let reason = match str::from_utf8(&buf[]) { Ok(s) => s.trim(), Err(_) => return Err(HttpStatusError) }; @@ -833,7 +839,7 @@ mod tests { #[test] fn test_read_chunk_size() { - fn read(s: &str, result: IoResult) { + fn read(s: &str, result: IoResult) { assert_eq!(read_chunk_size(&mut mem(s)), result); } diff --git a/src/lib.rs b/src/lib.rs index bba1e984..5623f926 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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(warnings)] #![experimental] @@ -151,14 +152,14 @@ use self::HttpError::{HttpMethodError, HttpUriError, HttpVersionError, macro_rules! todo( ($($arg:tt)*) => (if cfg!(not(ndebug)) { - log!(5, "TODO: {}", format_args!($($arg)*)) + log!(5, "TODO: {:?}", format_args!($($arg)*)) }) ); macro_rules! inspect( ($name:expr, $value:expr) => ({ let v = $value; - debug!("inspect: {} = {}", $name, v); + debug!("inspect: {:?} = {:?}", $name, v); v }) ); diff --git a/src/method.rs b/src/method.rs index b49524f7..68aa100d 100644 --- a/src/method.rs +++ b/src/method.rs @@ -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 { match *self { 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)] mod tests { use std::collections::HashMap; @@ -141,7 +147,7 @@ mod tests { #[test] fn test_hashable() { - let mut counter: HashMap = HashMap::new(); + let mut counter: HashMap = HashMap::new(); counter.insert(Get, 1); assert_eq!(Some(&1), counter.get(&Get)); } diff --git a/src/mock.rs b/src/mock.rs index 714c4ac1..e5cda053 100644 --- a/src/mock.rs +++ b/src/mock.rs @@ -27,7 +27,7 @@ impl PartialEq for MockStream { impl fmt::Show for MockStream { 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()) } @@ -49,7 +49,7 @@ impl MockStream { } } impl Reader for MockStream { - fn read(&mut self, buf: &mut [u8]) -> IoResult { + fn read(&mut self, buf: &mut [u8]) -> IoResult { self.read.read(buf) } } @@ -85,7 +85,7 @@ macro_rules! mock_connector ( impl ::net::NetworkConnector<::mock::MockStream> for $name { fn connect(&mut self, host: &str, port: u16, scheme: &str) -> ::std::io::IoResult<::mock::MockStream> { use std::collections::HashMap; - debug!("MockStream::connect({}, {}, {})", host, port, scheme); + debug!("MockStream::connect({:?}, {:?}, {:?})", host, port, scheme); let mut map = HashMap::new(); $(map.insert($url, $res);)* @@ -97,7 +97,7 @@ macro_rules! mock_connector ( write: ::std::io::MemWriter::new(), 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) } } diff --git a/src/net.rs b/src/net.rs index b15d24c8..21d8fd98 100644 --- a/src/net.rs +++ b/src/net.rs @@ -80,7 +80,7 @@ impl Clone for Box { impl Reader for Box { #[inline] - fn read(&mut self, buf: &mut [u8]) -> IoResult { (**self).read(buf) } + fn read(&mut self, buf: &mut [u8]) -> IoResult { (**self).read(buf) } } impl Writer for Box { @@ -93,7 +93,7 @@ impl Writer for Box { impl<'a> Reader for &'a mut NetworkStream { #[inline] - fn read(&mut self, buf: &mut [u8]) -> IoResult { (**self).read(buf) } + fn read(&mut self, buf: &mut [u8]) -> IoResult { (**self).read(buf) } } impl<'a> Writer for &'a mut NetworkStream { @@ -219,7 +219,7 @@ pub enum HttpStream { impl Reader for HttpStream { #[inline] - fn read(&mut self, buf: &mut [u8]) -> IoResult { + fn read(&mut self, buf: &mut [u8]) -> IoResult { match *self { Http(ref mut inner) => inner.read(buf), Https(ref mut inner) => inner.read(buf) @@ -287,7 +287,7 @@ impl NetworkConnector for HttpConnector { } fn lift_ssl_error(ssl: SslError) -> IoError { - debug!("lift_ssl_error: {}", ssl); + debug!("lift_ssl_error: {:?}", ssl); match ssl { StreamError(err) => err, SslSessionClosed => IoError { @@ -300,7 +300,7 @@ fn lift_ssl_error(ssl: SslError) -> IoError { OpenSslErrors(errs) => IoError { kind: OtherIoError, desc: "Error in OpenSSL", - detail: Some(format!("{}", errs)) + detail: Some(format!("{:?}", errs)) } } } diff --git a/src/server/mod.rs b/src/server/mod.rs index e722b410..f9838a92 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -50,17 +50,17 @@ impl Server { } } -impl, S: NetworkStream, A: NetworkAcceptor> Server { - /// Binds to a socket, and starts handling connections using a task pool. +impl Server { + /// 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 /// something other than the provided HttpStream, HttpAcceptor, and HttpListener. - pub fn listen_network(self, handler: H, threads: uint) -> HttpResult> + pub fn listen_network(self, handler: H, threads: usize) -> HttpResult> where H: Handler, S: NetworkStream + Clone, A: NetworkAcceptor, L: NetworkListener, { - debug!("binding to {}:{}", self.ip, self.port); + debug!("binding to {:?}:{:?}", self.ip, self.port); let mut listener: L = try!(NetworkListener::::bind((self.ip, self.port))); let socket = try!(listener.socket_name()); @@ -68,9 +68,9 @@ impl, S: NetworkStream, A: NetworkAcceptor> Server, S: NetworkStream, A: NetworkAcceptor> Server addr, Err(e) => { - error!("Peer Name error: {}", e); + error!("Peer Name error: {:?}", e); return; } }; @@ -94,12 +94,12 @@ impl, S: NetworkStream, A: NetworkAcceptor> Server req, Err(e@HttpIoError(_)) => { - debug!("ioerror in keepalive loop = {}", e); + debug!("ioerror in keepalive loop = {:?}", e); return; } Err(e) => { //TODO: send a 400 response - error!("request error = {}", e); + error!("request error = {:?}", e); return; } }; @@ -111,7 +111,7 @@ impl, S: NetworkStream, A: NetworkAcceptor> Server, S: NetworkStream, A: NetworkAcceptor> Server, S: NetworkStream, A: NetworkAcceptor> Server { /// Binds to a socket and starts handling connections with the specified number of tasks. - pub fn listen_threads(self, handler: H, threads: uint) -> HttpResult> { + pub fn listen_threads(self, handler: H, threads: usize) -> HttpResult> { self.listen_network::(handler, threads) } @@ -150,11 +153,12 @@ impl, S: NetworkStream, A: NetworkAcceptor> Server { acceptor: A, - guard: Option>, + guard: Option>, /// The socket addresses that the server is bound to. pub socket: SocketAddr, } +#[old_impl_check] impl, S: NetworkStream> Listening { /// Causes the current thread to wait for this listening to complete. pub fn await(&mut self) { diff --git a/src/server/request.rs b/src/server/request.rs index b434ce1b..1a44d6a6 100644 --- a/src/server/request.rs +++ b/src/server/request.rs @@ -37,9 +37,9 @@ impl<'a> Request<'a> { /// immediately useful. pub fn new(mut stream: &'a mut (Reader + 'a), addr: SocketAddr) -> HttpResult> { 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)); - debug!("Headers: [\n{}]", headers); + debug!("Headers: [\n{:?}]", headers); let body = if method == Get || method == Head { @@ -68,7 +68,7 @@ impl<'a> Request<'a> { } impl<'a> Reader for Request<'a> { - fn read(&mut self, buf: &mut [u8]) -> IoResult { + fn read(&mut self, buf: &mut [u8]) -> IoResult { self.body.read(buf) } } diff --git a/src/server/response.rs b/src/server/response.rs index 9204e9cd..9f44cd7c 100644 --- a/src/server/response.rs +++ b/src/server/response.rs @@ -67,7 +67,7 @@ impl<'a> Response<'a, Fresh> { /// Consume this Response, writing the Headers and Status and creating a Response pub fn start(mut self) -> IoResult> { - 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)); if !self.headers.has::() { @@ -89,7 +89,7 @@ impl<'a> Response<'a, Fresh> { // cant do in match above, thanks borrowck if chunked { let encodings = match self.headers.get_mut::() { - Some(&common::TransferEncoding(ref mut encodings)) => { + Some(&mut common::TransferEncoding(ref mut encodings)) => { //TODO: check if chunked is already in encodings. use HashSet? encodings.push(common::transfer_encoding::Encoding::Chunked); 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!(self.body.write_str(LINE_ENDING)); @@ -143,7 +143,7 @@ impl<'a> Response<'a, Streaming> { impl<'a> Writer for Response<'a, Streaming> { fn write(&mut self, msg: &[u8]) -> IoResult<()> { - debug!("write {} bytes", msg.len()); + debug!("write {:?} bytes", msg.len()); self.body.write(msg) } diff --git a/src/status.rs b/src/status.rs index 496e82ab..249c8aba 100644 --- a/src/status.rs +++ b/src/status.rs @@ -1585,13 +1585,19 @@ impl Copy for StatusCode {} /// ``` /// /// 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 { write!(f, "{} {}", *self as u16, self.canonical_reason().unwrap_or("")) } } +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 // of writing, 1.2 seconds) and verbose (though the optimiser cuts it down to size). impl PartialEq for StatusCode { diff --git a/src/version.rs b/src/version.rs index b0a7efa6..5a35b148 100644 --- a/src/version.rs +++ b/src/version.rs @@ -19,7 +19,7 @@ pub enum HttpVersion { Http20 } -impl fmt::Show for HttpVersion { +impl fmt::String for HttpVersion { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Http09 => "HTTP/0.9", @@ -29,3 +29,10 @@ impl fmt::Show for HttpVersion { }.fmt(fmt) } } + +impl fmt::Show for HttpVersion { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + self.to_string().fmt(fmt) + } +} +