From 541e21dbd10febf7c9fdf2455bc39a37f30beb3c Mon Sep 17 00:00:00 2001 From: Jonathan Reem Date: Sat, 3 Jan 2015 13:15:21 +0100 Subject: [PATCH 1/8] Update for unsafe-any changes. --- src/net.rs | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/net.rs b/src/net.rs index c5fabf0c..63acf3c0 100644 --- a/src/net.rs +++ b/src/net.rs @@ -105,12 +105,20 @@ impl<'a> Writer for &'a mut NetworkStream { fn flush(&mut self) -> IoResult<()> { (**self).flush() } } -impl UncheckedBoxAnyDowncast for Box { - unsafe fn downcast_unchecked(self) -> Box { - let to = *mem::transmute::<&Box, &raw::TraitObject>(&self); - // Prevent double-free. - mem::forget(self); - mem::transmute(to.data) +impl UnsafeAnyExt for NetworkStream + Send { + unsafe fn downcast_ref_unchecked(&self) -> &T { + mem::transmute(mem::transmute::<&NetworkStream + Send, + raw::TraitObject>(self).data) + } + + unsafe fn downcast_mut_unchecked(&mut self) -> &mut T { + mem::transmute(mem::transmute::<&mut NetworkStream + Send, + raw::TraitObject>(self).data) + } + + unsafe fn downcast_unchecked(self: Box) -> Box { + mem::transmute(mem::transmute::, + raw::TraitObject>(self).data) } } From 7f3a33f903aca3d5eced9b465624ea44e4773ce3 Mon Sep 17 00:00:00 2001 From: Jonathan Reem Date: Sat, 3 Jan 2015 13:15:54 +0100 Subject: [PATCH 2/8] #[deriving] -> #[derive] --- benches/client.rs | 2 +- benches/client_mock_tcp.rs | 2 +- src/client/mod.rs | 2 +- src/header/common/accept.rs | 2 +- src/header/common/allow.rs | 2 +- src/header/common/authorization.rs | 4 ++-- src/header/common/cache_control.rs | 4 ++-- src/header/common/connection.rs | 4 ++-- src/header/common/content_length.rs | 2 +- src/header/common/content_type.rs | 2 +- src/header/common/cookie.rs | 2 +- src/header/common/date.rs | 2 +- src/header/common/etag.rs | 2 +- src/header/common/expires.rs | 2 +- src/header/common/host.rs | 2 +- src/header/common/if_modified_since.rs | 2 +- src/header/common/last_modified.rs | 2 +- src/header/common/location.rs | 2 +- src/header/common/server.rs | 2 +- src/header/common/set_cookie.rs | 2 +- src/header/common/transfer_encoding.rs | 4 ++-- src/header/common/upgrade.rs | 4 ++-- src/header/common/user_agent.rs | 2 +- src/header/common/vary.rs | 2 +- src/header/mod.rs | 8 ++++---- src/http.rs | 2 +- src/lib.rs | 2 +- src/method.rs | 2 +- src/net.rs | 4 ++-- src/status.rs | 6 +++--- src/uri.rs | 2 +- src/version.rs | 2 +- 32 files changed, 43 insertions(+), 43 deletions(-) diff --git a/benches/client.rs b/benches/client.rs index 6bcee6fb..c8a88639 100644 --- a/benches/client.rs +++ b/benches/client.rs @@ -46,7 +46,7 @@ fn bench_curl(b: &mut test::Bencher) { listening.close().unwrap(); } -#[deriving(Clone)] +#[derive(Clone)] struct Foo; impl hyper::header::Header for Foo { diff --git a/benches/client_mock_tcp.rs b/benches/client_mock_tcp.rs index 2fd2ce19..599206ec 100644 --- a/benches/client_mock_tcp.rs +++ b/benches/client_mock_tcp.rs @@ -65,7 +65,7 @@ fn bench_mock_curl(b: &mut test::Bencher) { }); } -#[deriving(Clone)] +#[derive(Clone)] struct Foo; impl hyper::header::Header for Foo { diff --git a/src/client/mod.rs b/src/client/mod.rs index 04bd8ef4..3eddc4b3 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -315,7 +315,7 @@ impl<'a> IntoUrl for &'a str { } /// Behavior regarding how to handle redirects within a Client. -#[deriving(Copy)] +#[derive(Copy)] pub enum RedirectPolicy { /// Don't follow any redirects. FollowNone, diff --git a/src/header/common/accept.rs b/src/header/common/accept.rs index 3617f6ee..79e2252f 100644 --- a/src/header/common/accept.rs +++ b/src/header/common/accept.rs @@ -25,7 +25,7 @@ use mime; /// qitem(Mime(Text, Html, vec![])), /// qitem(Mime(Text, Xml, vec![])) ])); /// ``` -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct Accept(pub Vec>); deref!(Accept -> Vec>); diff --git a/src/header/common/allow.rs b/src/header/common/allow.rs index 0efad670..dcd4bc28 100644 --- a/src/header/common/allow.rs +++ b/src/header/common/allow.rs @@ -6,7 +6,7 @@ use header::shared::util::{from_comma_delimited, fmt_comma_delimited}; /// The `Allow` header. /// See also https://tools.ietf.org/html/rfc7231#section-7.4.1 -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct Allow(pub Vec); deref!(Allow -> Vec); diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs index 0b69d4d4..d6daa17e 100644 --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -4,7 +4,7 @@ use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// The `Authorization` header field. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct Authorization(pub S); impl Deref for Authorization { @@ -72,7 +72,7 @@ impl Scheme for String { } /// Credential holder for Basic Authentication -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct Basic { /// The username as a possibly empty string pub username: String, diff --git a/src/header/common/cache_control.rs b/src/header/common/cache_control.rs index 8c309dff..0cb0dbef 100644 --- a/src/header/common/cache_control.rs +++ b/src/header/common/cache_control.rs @@ -4,7 +4,7 @@ use header::{Header, HeaderFormat}; use header::shared::util::{from_one_comma_delimited, fmt_comma_delimited}; /// The Cache-Control header. -#[deriving(PartialEq, Clone, Show)] +#[derive(PartialEq, Clone, Show)] pub struct CacheControl(pub Vec); deref!(CacheControl -> Vec); @@ -34,7 +34,7 @@ impl HeaderFormat for CacheControl { } /// CacheControl contains a list of these directives. -#[deriving(PartialEq, Clone)] +#[derive(PartialEq, Clone)] pub enum CacheDirective { /// "no-cache" NoCache, diff --git a/src/header/common/connection.rs b/src/header/common/connection.rs index ad2ce2b6..1c29f47f 100644 --- a/src/header/common/connection.rs +++ b/src/header/common/connection.rs @@ -6,13 +6,13 @@ use header::shared::util::{from_comma_delimited, fmt_comma_delimited}; pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader}; /// The `Connection` header. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct Connection(pub Vec); deref!(Connection -> Vec); /// Values that can be in the `Connection` header. -#[deriving(Clone, PartialEq)] +#[derive(Clone, PartialEq)] pub enum ConnectionOption { /// The `keep-alive` connection value. KeepAlive, diff --git a/src/header/common/content_length.rs b/src/header/common/content_length.rs index 3637d02b..cd73bae2 100644 --- a/src/header/common/content_length.rs +++ b/src/header/common/content_length.rs @@ -6,7 +6,7 @@ use header::shared::util::from_one_raw_str; /// The `Content-Length` header. /// /// Simply a wrapper around a `uint`. -#[deriving(Copy, Clone, PartialEq, Show)] +#[derive(Copy, Clone, PartialEq, Show)] pub struct ContentLength(pub uint); deref!(ContentLength -> uint); diff --git a/src/header/common/content_type.rs b/src/header/common/content_type.rs index d07c3542..fb5af41f 100644 --- a/src/header/common/content_type.rs +++ b/src/header/common/content_type.rs @@ -7,7 +7,7 @@ use mime::Mime; /// /// Used to describe the MIME type of message body. Can be used with both /// requests and responses. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct ContentType(pub Mime); deref!(ContentType -> Mime); diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs index 09c8b146..039f0e9a 100644 --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -13,7 +13,7 @@ use cookie::CookieJar; /// /// > When the user agent generates an HTTP request, the user agent MUST NOT /// > attach more than one Cookie header field. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct Cookies(pub Vec); //TODO: remove when fixed in libstd diff --git a/src/header/common/date.rs b/src/header/common/date.rs index 9398cefe..9dab54b6 100644 --- a/src/header/common/date.rs +++ b/src/header/common/date.rs @@ -7,7 +7,7 @@ use header::shared::time::tm_from_str; // Egh, replace as soon as something better than time::Tm exists. /// The `Date` header field. -#[deriving(Copy, PartialEq, Clone)] +#[derive(Copy, PartialEq, Clone)] pub struct Date(pub Tm); deref!(Date -> Tm); diff --git a/src/header/common/etag.rs b/src/header/common/etag.rs index 3bdd3a6b..d6c4eebf 100644 --- a/src/header/common/etag.rs +++ b/src/header/common/etag.rs @@ -8,7 +8,7 @@ use header::shared::util::from_one_raw_str; /// Preceding the first double quote is an optional weakness indicator, /// which always looks like this: W/ /// See also: https://tools.ietf.org/html/rfc7232#section-2.3 -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct Etag { /// Weakness indicator for the tag pub weak: bool, diff --git a/src/header/common/expires.rs b/src/header/common/expires.rs index 4f160ded..4933fbe0 100644 --- a/src/header/common/expires.rs +++ b/src/header/common/expires.rs @@ -6,7 +6,7 @@ use header::shared::util::from_one_raw_str; use header::shared::time::tm_from_str; /// The `Expires` header field. -#[deriving(Copy, PartialEq, Clone)] +#[derive(Copy, PartialEq, Clone)] pub struct Expires(pub Tm); deref!(Expires -> Tm); diff --git a/src/header/common/host.rs b/src/header/common/host.rs index 7298fa51..90759bae 100644 --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -10,7 +10,7 @@ use header::shared::util::from_one_raw_str; /// /// Currently is just a String, but it should probably become a better type, /// like url::Host or something. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct Host { /// The hostname, such a example.domain. pub hostname: String, diff --git a/src/header/common/if_modified_since.rs b/src/header/common/if_modified_since.rs index a462ed54..565c98ce 100644 --- a/src/header/common/if_modified_since.rs +++ b/src/header/common/if_modified_since.rs @@ -6,7 +6,7 @@ use header::shared::util::from_one_raw_str; use header::shared::time::tm_from_str; /// The `If-Modified-Since` header field. -#[deriving(Copy, PartialEq, Clone)] +#[derive(Copy, PartialEq, Clone)] pub struct IfModifiedSince(pub Tm); deref!(IfModifiedSince -> Tm); diff --git a/src/header/common/last_modified.rs b/src/header/common/last_modified.rs index 5369ae4d..73a5d2c0 100644 --- a/src/header/common/last_modified.rs +++ b/src/header/common/last_modified.rs @@ -6,7 +6,7 @@ use header::shared::util::from_one_raw_str; use header::shared::time::tm_from_str; /// The `LastModified` header field. -#[deriving(Copy, PartialEq, Clone)] +#[derive(Copy, PartialEq, Clone)] pub struct LastModified(pub Tm); deref!(LastModified -> Tm); diff --git a/src/header/common/location.rs b/src/header/common/location.rs index 31fdc962..c8ee186a 100644 --- a/src/header/common/location.rs +++ b/src/header/common/location.rs @@ -13,7 +13,7 @@ use header::shared::util::from_one_raw_str; /// /// Currently is just a String, but it should probably become a better type, /// like url::Url or something. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct Location(pub String); deref!(Location -> String); diff --git a/src/header/common/server.rs b/src/header/common/server.rs index a7d5d4ed..9e835299 100644 --- a/src/header/common/server.rs +++ b/src/header/common/server.rs @@ -5,7 +5,7 @@ use header::shared::util::from_one_raw_str; /// The `Server` header field. /// /// They can contain any value, so it just wraps a `String`. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct Server(pub String); deref!(Server -> String); diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs index 4bec8724..0b0a3912 100644 --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -10,7 +10,7 @@ use cookie::CookieJar; /// Informally, the Set-Cookie response header contains the header name /// "Set-Cookie" followed by a ":" and a cookie. Each cookie begins with /// a name-value-pair, followed by zero or more attribute-value pairs. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct SetCookie(pub Vec); //TODO: remove when fixed in libstd diff --git a/src/header/common/transfer_encoding.rs b/src/header/common/transfer_encoding.rs index 47c4ad50..480a559c 100644 --- a/src/header/common/transfer_encoding.rs +++ b/src/header/common/transfer_encoding.rs @@ -18,7 +18,7 @@ use self::Encoding::{Chunked, Gzip, Deflate, Compress, EncodingExt}; /// this header should include `chunked` as the last encoding. /// /// The implementation uses a vector of `Encoding` values. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct TransferEncoding(pub Vec); deref!(TransferEncoding -> Vec); @@ -33,7 +33,7 @@ deref!(TransferEncoding -> Vec); /// # use hyper::header::Headers; /// # let mut headers = Headers::new(); /// headers.set(TransferEncoding(vec![Gzip, Chunked])); -#[deriving(Clone, PartialEq)] +#[derive(Clone, PartialEq)] pub enum Encoding { /// The `chunked` encoding. Chunked, diff --git a/src/header/common/upgrade.rs b/src/header/common/upgrade.rs index 10c6009b..365ddcc4 100644 --- a/src/header/common/upgrade.rs +++ b/src/header/common/upgrade.rs @@ -6,13 +6,13 @@ use header::shared::util::{from_comma_delimited, fmt_comma_delimited}; use self::Protocol::{WebSocket, ProtocolExt}; /// The `Upgrade` header. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct Upgrade(pub Vec); deref!(Upgrade -> Vec); /// Protocol values that can appear in the Upgrade header. -#[deriving(Clone, PartialEq)] +#[derive(Clone, PartialEq)] pub enum Protocol { /// The websocket protocol. WebSocket, diff --git a/src/header/common/user_agent.rs b/src/header/common/user_agent.rs index a51bee3c..d0d80999 100644 --- a/src/header/common/user_agent.rs +++ b/src/header/common/user_agent.rs @@ -5,7 +5,7 @@ use header::shared::util::from_one_raw_str; /// The `User-Agent` header field. /// /// They can contain any value, so it just wraps a `String`. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct UserAgent(pub String); deref!(UserAgent -> String); diff --git a/src/header/common/vary.rs b/src/header/common/vary.rs index 1424c278..97497f49 100644 --- a/src/header/common/vary.rs +++ b/src/header/common/vary.rs @@ -5,7 +5,7 @@ use header::shared::util::{from_comma_delimited, fmt_comma_delimited, from_one_r /// The `Allow` header. /// See also https://tools.ietf.org/html/rfc7231#section-7.1.4 -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub enum Vary { /// This corresponds to '*'. Any, diff --git a/src/header/mod.rs b/src/header/mod.rs index ba308727..e6c0fe80 100644 --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -110,7 +110,7 @@ fn header_name() -> &'static str { } /// A map of header fields on requests and responses. -#[deriving(Clone)] +#[derive(Clone)] pub struct Headers { data: HashMap> } @@ -342,7 +342,7 @@ impl<'a> FromIterator> for Headers { } } -#[deriving(Clone)] +#[derive(Clone)] struct Item { raw: Option>>, typed: Option> @@ -450,7 +450,7 @@ impl fmt::Show for Box { } /// Case-insensitive string. -//#[deriving(Clone)] +//#[derive(Clone)] pub struct CaseInsensitive(SendStr); impl FromStr for CaseInsensitive { @@ -562,7 +562,7 @@ mod tests { assert_eq!(accept, Some(Accept(vec![application_vendor, text_plain]))); } - #[deriving(Clone, Show)] + #[derive(Clone, Show)] struct CrazyLength(Option, uint); impl Header for CrazyLength { diff --git a/src/http.rs b/src/http.rs index 33f2cda7..074bb021 100644 --- a/src/http.rs +++ b/src/http.rs @@ -582,7 +582,7 @@ pub fn read_request_line(stream: &mut R) -> HttpResult { pub type StatusLine = (HttpVersion, RawStatus); /// The raw status code and reason-phrase. -#[deriving(PartialEq, Show)] +#[derive(PartialEq, Show)] pub struct RawStatus(pub u16, pub SendStr); impl Clone for RawStatus { diff --git a/src/lib.rs b/src/lib.rs index 27eec2ec..6377a631 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -207,7 +207,7 @@ mod mimewrapper { pub type HttpResult = Result; /// A set of errors that can occur parsing HTTP streams. -#[deriving(Show, PartialEq, Clone)] +#[derive(Show, PartialEq, Clone)] pub enum HttpError { /// An invalid `Method`, such as `GE,T`. HttpMethodError, diff --git a/src/method.rs b/src/method.rs index 41d53d27..b49524f7 100644 --- a/src/method.rs +++ b/src/method.rs @@ -13,7 +13,7 @@ use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch, /// /// It may make sense to grow this to include all variants currently /// registered with IANA, if they are at all common to use. -#[deriving(Clone, PartialEq, Eq, Hash)] +#[derive(Clone, PartialEq, Eq, Hash)] pub enum Method { /// OPTIONS Options, diff --git a/src/net.rs b/src/net.rs index 63acf3c0..420e807d 100644 --- a/src/net.rs +++ b/src/net.rs @@ -182,7 +182,7 @@ impl NetworkListener for HttpListener { } /// A `NetworkAcceptor` for `HttpStream`s. -#[deriving(Clone)] +#[derive(Clone)] pub struct HttpAcceptor { inner: TcpAcceptor } @@ -202,7 +202,7 @@ impl NetworkAcceptor for HttpAcceptor { } /// A wrapper around a TcpStream. -#[deriving(Clone)] +#[derive(Clone)] pub enum HttpStream { /// A stream over the HTTP protocol. Http(TcpStream), diff --git a/src/status.rs b/src/status.rs index 189d29b7..4f25c584 100644 --- a/src/status.rs +++ b/src/status.rs @@ -1038,7 +1038,7 @@ impl StatusCode { /// other times. /// /// The reason phrase is defined as being exclusively for human readers. You should avoid - /// deriving any meaning from it at all costs. + /// derive any meaning from it at all costs. /// /// Bear in mind also that in HTTP/2.0 the reason phrase is abolished from transmission, and so /// this canonical reason phrase really is the only reason phrase you’ll find. @@ -1600,7 +1600,7 @@ impl PartialEq for StatusCode { impl Eq for StatusCode {} -// Ditto (though #[deriving(Clone)] only takes about 0.4 seconds). +// Ditto (though #[derive(Clone)] only takes about 0.4 seconds). impl Clone for StatusCode { #[inline] fn clone(&self) -> StatusCode { @@ -1686,7 +1686,7 @@ impl ToPrimitive for StatusCode { /// to get the appropriate *category* of status. /// /// For HTTP/2.0, the 1xx Informational class is invalid. -#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Copy)] +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy)] pub enum StatusClass { /// 1xx: Informational - Request received, continuing process Informational = 100, diff --git a/src/uri.rs b/src/uri.rs index 89fd92bf..7b0f80a9 100644 --- a/src/uri.rs +++ b/src/uri.rs @@ -16,7 +16,7 @@ use url::Url; /// > / authority-form /// > / asterisk-form /// > ``` -#[deriving(Show, PartialEq, Clone)] +#[derive(Show, PartialEq, Clone)] pub enum RequestUri { /// The most common request target, an absolute path and optional query. /// diff --git a/src/version.rs b/src/version.rs index d0ec828f..b0a7efa6 100644 --- a/src/version.rs +++ b/src/version.rs @@ -7,7 +7,7 @@ use std::fmt; use self::HttpVersion::{Http09, Http10, Http11, Http20}; /// Represents a version of the HTTP spec. -#[deriving(PartialEq, PartialOrd, Copy)] +#[derive(PartialEq, PartialOrd, Copy)] pub enum HttpVersion { /// `HTTP/0.9` Http09, From f0fe878ec826dd1a6a10c31dbc05a69d3c384b9c Mon Sep 17 00:00:00 2001 From: Jonathan Reem Date: Mon, 5 Jan 2015 22:50:10 +0100 Subject: [PATCH 3/8] More Rust updates: - Some stray deriving -> derive changes - use::{mod} -> use::{self} - fmt.write -> fmt.write_str This does not catch the last case of fmt.write_str in the Show impl of a Header Item. This will need to be changed separately. --- benches/client.rs | 2 +- benches/client_mock_tcp.rs | 2 +- src/client/request.rs | 2 +- src/header/common/accept_encoding.rs | 2 +- src/header/common/allow.rs | 4 +-- src/header/common/authorization.rs | 9 ++++--- src/header/common/connection.rs | 2 +- src/header/common/content_length.rs | 2 +- src/header/common/content_type.rs | 2 +- src/header/common/cookie.rs | 2 +- src/header/common/date.rs | 2 +- src/header/common/etag.rs | 4 +-- src/header/common/expires.rs | 2 +- src/header/common/host.rs | 2 +- src/header/common/if_modified_since.rs | 2 +- src/header/common/last_modified.rs | 2 +- src/header/common/location.rs | 2 +- src/header/common/mod.rs | 6 +++-- src/header/common/server.rs | 2 +- src/header/common/set_cookie.rs | 4 +-- src/header/common/upgrade.rs | 2 +- src/header/common/user_agent.rs | 2 +- src/header/common/vary.rs | 2 +- src/header/mod.rs | 37 +++++++++++++++----------- src/header/shared/encoding.rs | 2 +- src/header/shared/quality_item.rs | 2 +- src/http.rs | 7 ++--- src/lib.rs | 35 +++++++++++++----------- src/net.rs | 12 ++++----- src/server/request.rs | 2 +- src/status.rs | 3 +++ 31 files changed, 90 insertions(+), 73 deletions(-) diff --git a/benches/client.rs b/benches/client.rs index c8a88639..69179c00 100644 --- a/benches/client.rs +++ b/benches/client.rs @@ -4,7 +4,7 @@ extern crate hyper; extern crate test; -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use std::io::net::ip::Ipv4Addr; use hyper::server::{Request, Response, Server}; use hyper::header::Headers; diff --git a/benches/client_mock_tcp.rs b/benches/client_mock_tcp.rs index 599206ec..3776077c 100644 --- a/benches/client_mock_tcp.rs +++ b/benches/client_mock_tcp.rs @@ -4,7 +4,7 @@ extern crate hyper; extern crate test; -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use std::str::from_str; use std::io::{IoResult, MemReader}; use std::io::net::ip::SocketAddr; diff --git a/src/client/request.rs b/src/client/request.rs index 6787e86b..e83ed7c5 100644 --- a/src/client/request.rs +++ b/src/client/request.rs @@ -6,7 +6,7 @@ use url::Url; use method; use method::Method::{Get, Post, Delete, Put, Patch, Head, Options}; use header::Headers; -use header::common::{mod, Host}; +use header::common::{self, Host}; use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming}; use http::{HttpWriter, LINE_ENDING}; use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter}; diff --git a/src/header/common/accept_encoding.rs b/src/header/common/accept_encoding.rs index 622de977..5f86794e 100644 --- a/src/header/common/accept_encoding.rs +++ b/src/header/common/accept_encoding.rs @@ -7,7 +7,7 @@ use header::shared; /// /// The `Accept-Encoding` header can be used by clients to indicate what /// response encodings they accept. -#[deriving(Clone, PartialEq, Show)] +#[derive(Clone, PartialEq, Show)] pub struct AcceptEncoding(pub Vec>); deref!(AcceptEncoding -> Vec>); diff --git a/src/header/common/allow.rs b/src/header/common/allow.rs index dcd4bc28..b49d29d6 100644 --- a/src/header/common/allow.rs +++ b/src/header/common/allow.rs @@ -1,6 +1,6 @@ use header::{Header, HeaderFormat}; use method::Method; -use std::fmt::{mod}; +use std::fmt::{self}; use header::shared::util::{from_comma_delimited, fmt_comma_delimited}; /// The `Allow` header. @@ -31,7 +31,7 @@ impl HeaderFormat for Allow { mod tests { use super::Allow; use header::Header; - use method::Method::{mod, Options, Get, Put, Post, Delete, Head, Trace, Connect, Patch, Extension}; + use method::Method::{self, Options, Get, Put, Post, Delete, Head, Trace, Connect, Patch, Extension}; #[test] fn test_allow() { diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs index d6daa17e..7a8df60c 100644 --- a/src/header/common/authorization.rs +++ b/src/header/common/authorization.rs @@ -1,5 +1,6 @@ -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use std::str::{FromStr, from_utf8}; +use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; @@ -7,13 +8,15 @@ use header::{Header, HeaderFormat}; #[derive(Clone, PartialEq, Show)] pub struct Authorization(pub S); -impl Deref for Authorization { +impl Deref for Authorization { + type Target = S; + fn deref<'a>(&'a self) -> &'a S { &self.0 } } -impl DerefMut for Authorization { +impl DerefMut for Authorization { fn deref_mut<'a>(&'a mut self) -> &'a mut S { &mut self.0 } diff --git a/src/header/common/connection.rs b/src/header/common/connection.rs index 1c29f47f..daed4bf3 100644 --- a/src/header/common/connection.rs +++ b/src/header/common/connection.rs @@ -1,5 +1,5 @@ use header::{Header, HeaderFormat}; -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use std::str::FromStr; use header::shared::util::{from_comma_delimited, fmt_comma_delimited}; diff --git a/src/header/common/content_length.rs b/src/header/common/content_length.rs index cd73bae2..13bb9f41 100644 --- a/src/header/common/content_length.rs +++ b/src/header/common/content_length.rs @@ -1,4 +1,4 @@ -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use header::{Header, HeaderFormat}; use header::shared::util::from_one_raw_str; diff --git a/src/header/common/content_type.rs b/src/header/common/content_type.rs index fb5af41f..1ccdbe86 100644 --- a/src/header/common/content_type.rs +++ b/src/header/common/content_type.rs @@ -1,5 +1,5 @@ use header::{Header, HeaderFormat}; -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use header::shared::util::from_one_raw_str; use mime::Mime; diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs index 039f0e9a..dedb9496 100644 --- a/src/header/common/cookie.rs +++ b/src/header/common/cookie.rs @@ -1,5 +1,5 @@ use header::{Header, HeaderFormat}; -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use std::str::from_utf8; use cookie::Cookie; diff --git a/src/header/common/date.rs b/src/header/common/date.rs index 9dab54b6..d7542799 100644 --- a/src/header/common/date.rs +++ b/src/header/common/date.rs @@ -1,4 +1,4 @@ -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use std::str::FromStr; use time::Tm; use header::{Header, HeaderFormat}; diff --git a/src/header/common/etag.rs b/src/header/common/etag.rs index d6c4eebf..93164245 100644 --- a/src/header/common/etag.rs +++ b/src/header/common/etag.rs @@ -1,5 +1,5 @@ use header::{Header, HeaderFormat}; -use std::fmt::{mod}; +use std::fmt::{self}; use header::shared::util::from_one_raw_str; /// The `Etag` header. @@ -81,7 +81,7 @@ impl Header for Etag { impl HeaderFormat for Etag { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { if self.weak { - try!(fmt.write(b"W/")); + try!(fmt.write_str("W/")); } write!(fmt, "\"{}\"", self.tag) } diff --git a/src/header/common/expires.rs b/src/header/common/expires.rs index 4933fbe0..638d928d 100644 --- a/src/header/common/expires.rs +++ b/src/header/common/expires.rs @@ -1,4 +1,4 @@ -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use std::str::FromStr; use time::Tm; use header::{Header, HeaderFormat}; diff --git a/src/header/common/host.rs b/src/header/common/host.rs index 90759bae..a9d23602 100644 --- a/src/header/common/host.rs +++ b/src/header/common/host.rs @@ -1,6 +1,6 @@ use header::{Header, HeaderFormat}; use Port; -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use header::shared::util::from_one_raw_str; /// The `Host` header. diff --git a/src/header/common/if_modified_since.rs b/src/header/common/if_modified_since.rs index 565c98ce..af5e9bdd 100644 --- a/src/header/common/if_modified_since.rs +++ b/src/header/common/if_modified_since.rs @@ -1,4 +1,4 @@ -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use std::str::FromStr; use time::Tm; use header::{Header, HeaderFormat}; diff --git a/src/header/common/last_modified.rs b/src/header/common/last_modified.rs index 73a5d2c0..e9b06afa 100644 --- a/src/header/common/last_modified.rs +++ b/src/header/common/last_modified.rs @@ -1,4 +1,4 @@ -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use std::str::FromStr; use time::Tm; use header::{Header, HeaderFormat}; diff --git a/src/header/common/location.rs b/src/header/common/location.rs index c8ee186a..ace1c777 100644 --- a/src/header/common/location.rs +++ b/src/header/common/location.rs @@ -1,5 +1,5 @@ use header::{Header, HeaderFormat}; -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use header::shared::util::from_one_raw_str; /// The `Location` header. diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs index f6659afa..2b1f411e 100644 --- a/src/header/common/mod.rs +++ b/src/header/common/mod.rs @@ -60,13 +60,15 @@ macro_rules! bench_header( macro_rules! deref( ($from:ty -> $to:ty) => { - impl Deref<$to> for $from { + impl ::std::ops::Deref for $from { + type Target = $to; + fn deref<'a>(&'a self) -> &'a $to { &self.0 } } - impl DerefMut<$to> for $from { + impl ::std::ops::DerefMut for $from { fn deref_mut<'a>(&'a mut self) -> &'a mut $to { &mut self.0 } diff --git a/src/header/common/server.rs b/src/header/common/server.rs index 9e835299..4ae1a369 100644 --- a/src/header/common/server.rs +++ b/src/header/common/server.rs @@ -1,5 +1,5 @@ use header::{Header, HeaderFormat}; -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use header::shared::util::from_one_raw_str; /// The `Server` header field. diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs index 0b0a3912..57f08633 100644 --- a/src/header/common/set_cookie.rs +++ b/src/header/common/set_cookie.rs @@ -1,5 +1,5 @@ use header::{Header, HeaderFormat}; -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use std::str::from_utf8; use cookie::Cookie; @@ -52,7 +52,7 @@ impl HeaderFormat for SetCookie { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, cookie) in self.0.iter().enumerate() { if i != 0 { - try!(f.write(b"\r\nSet-Cookie: ")); + try!(f.write_str("\r\nSet-Cookie: ")); } try!(cookie.fmt(f)); } diff --git a/src/header/common/upgrade.rs b/src/header/common/upgrade.rs index 365ddcc4..a81b374f 100644 --- a/src/header/common/upgrade.rs +++ b/src/header/common/upgrade.rs @@ -1,5 +1,5 @@ use header::{Header, HeaderFormat}; -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use std::str::FromStr; use header::shared::util::{from_comma_delimited, fmt_comma_delimited}; diff --git a/src/header/common/user_agent.rs b/src/header/common/user_agent.rs index d0d80999..2d477ddb 100644 --- a/src/header/common/user_agent.rs +++ b/src/header/common/user_agent.rs @@ -1,5 +1,5 @@ use header::{Header, HeaderFormat}; -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use header::shared::util::from_one_raw_str; /// The `User-Agent` header field. diff --git a/src/header/common/vary.rs b/src/header/common/vary.rs index 97497f49..dcb80186 100644 --- a/src/header/common/vary.rs +++ b/src/header/common/vary.rs @@ -1,5 +1,5 @@ use header::{Header, HeaderFormat, CaseInsensitive}; -use std::fmt::{mod}; +use std::fmt::{self}; use header::shared::util::{from_comma_delimited, fmt_comma_delimited, from_one_raw_str}; /// The `Allow` header. diff --git a/src/header/mod.rs b/src/header/mod.rs index e6c0fe80..89e7dc42 100644 --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -7,18 +7,20 @@ use std::any::Any; use std::ascii::AsciiExt; use std::borrow::Cow::{Borrowed, Owned}; -use std::fmt::{mod, Show}; +use std::fmt::{self, Show}; use std::intrinsics::TypeId; use std::raw::TraitObject; use std::str::{SendStr, FromStr}; use std::collections::HashMap; use std::collections::hash_map::{Iter, Entry}; -use std::{hash, mem}; +use std::iter::FromIterator; +use std::borrow::IntoCow; +use std::{hash, mem, raw}; use mucell::MuCell; -use uany::{UncheckedAnyDowncast, UncheckedAnyMutDowncast}; +use uany::{UnsafeAnyExt}; -use http::{mod, LineEnding}; +use http::{self, LineEnding}; use {HttpResult}; pub use self::common::*; @@ -81,19 +83,20 @@ impl HeaderFormat { } } -impl<'a> UncheckedAnyDowncast<'a> for &'a HeaderFormat { +impl UnsafeAnyExt for HeaderFormat { #[inline] - unsafe fn downcast_ref_unchecked(self) -> &'a T { - let to: TraitObject = mem::transmute_copy(&self); - mem::transmute(to.data) + unsafe fn downcast_ref_unchecked(&self) -> &T { + mem::transmute(mem::transmute::<&HeaderFormat, raw::TraitObject>(self).data) } -} -impl<'a> UncheckedAnyMutDowncast<'a> for &'a mut HeaderFormat { #[inline] - unsafe fn downcast_mut_unchecked(self) -> &'a mut T { - let to: TraitObject = mem::transmute_copy(&self); - mem::transmute(to.data) + unsafe fn downcast_mut_unchecked(&mut self) -> &mut T { + mem::transmute(mem::transmute::<&mut HeaderFormat, raw::TraitObject>(self).data) + } + + #[inline] + unsafe fn downcast_unchecked(self: Box) -> Box { + mem::transmute(mem::transmute::, raw::TraitObject>(self).data) } } @@ -278,7 +281,9 @@ pub struct HeadersItems<'a> { inner: Iter<'a, CaseInsensitive, MuCell> } -impl<'a> Iterator> for HeadersItems<'a> { +impl<'a> Iterator for HeadersItems<'a> { + type Item = HeaderView<'a>; + fn next(&mut self) -> Option> { match self.inner.next() { Some((k, v)) => Some(HeaderView(k, v)), @@ -327,7 +332,7 @@ impl<'a> fmt::Show for HeaderView<'a> { } impl<'a> Extend> for Headers { - fn extend>>(&mut self, mut iter: I) { + fn extend>>(&mut self, mut iter: I) { for header in iter { self.data.insert((*header.0).clone(), (*header.1).clone()); } @@ -335,7 +340,7 @@ impl<'a> Extend> for Headers { } impl<'a> FromIterator> for Headers { - fn from_iter>>(iter: I) -> Headers { + fn from_iter>>(iter: I) -> Headers { let mut headers = Headers::new(); headers.extend(iter); headers diff --git a/src/header/shared/encoding.rs b/src/header/shared/encoding.rs index f05d79f1..67e91cd1 100644 --- a/src/header/shared/encoding.rs +++ b/src/header/shared/encoding.rs @@ -7,7 +7,7 @@ pub use self::Encoding::{Chunked, Gzip, Deflate, Compress, Identity, EncodingExt /// A value to represent an encoding used in `Transfer-Encoding` /// or `Accept-Encoding` header. -#[deriving(Clone, PartialEq)] +#[derive(Clone, PartialEq)] pub enum Encoding { /// The `chunked` encoding. Chunked, diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs index a58f4737..5272faac 100644 --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -9,7 +9,7 @@ use std::str; /// Represents an item with a quality value as defined in /// [RFC7231](https://tools.ietf.org/html/rfc7231#section-5.3.1). -#[deriving(Clone, PartialEq)] +#[derive(Clone, PartialEq)] pub struct QualityItem { /// The actual contents of the field. pub item: T, diff --git a/src/http.rs b/src/http.rs index 074bb021..610303ec 100644 --- a/src/http.rs +++ b/src/http.rs @@ -1,10 +1,11 @@ //! Pieces pertaining to the HTTP message protocol. use std::borrow::Cow::{Borrowed, Owned}; +use std::borrow::IntoCow; use std::cmp::min; use std::fmt; -use std::io::{mod, Reader, IoResult, BufWriter}; +use std::io::{self, Reader, IoResult, BufWriter}; use std::num::from_u16; -use std::str::{mod, SendStr, FromStr}; +use std::str::{self, SendStr, FromStr}; use url::Url; use url::ParseError as UrlError; @@ -693,7 +694,7 @@ fn expect(r: IoResult, expected: u8) -> HttpResult<()> { #[cfg(test)] mod tests { - use std::io::{mod, MemReader, MemWriter}; + use std::io::{self, MemReader, MemWriter}; use std::borrow::Cow::{Borrowed, Owned}; use test::Bencher; use uri::RequestUri; diff --git a/src/lib.rs b/src/lib.rs index 6377a631..9ad7b217 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,6 @@ -#![feature(macro_rules, phase, default_type_params, slicing_syntax, globs)] +#![feature(macro_rules, phase, default_type_params, + slicing_syntax, globs, associated_types, + old_orphan_check)] #![deny(missing_docs)] #![deny(warnings)] #![experimental] @@ -158,21 +160,22 @@ macro_rules! todo( }) ); -#[allow(dead_code)] -struct Trace; - -impl fmt::Show for Trace { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - let _ = backtrace::write(fmt); - Result::Ok(()) - } -} - -macro_rules! trace( - ($($arg:tt)*) => (if cfg!(not(ndebug)) { - log!(5, "{}\n{}", format_args!($($arg)*), ::Trace) - }) -); +// FIXME(reem): Uncomment this when backtrace::write can write to a fmt::Formatter. +// #[allow(dead_code)] +// struct Trace; +// +// impl fmt::Show for Trace { +// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { +// let _ = backtrace::write(fmt); +// Result::Ok(()) +// } +// } +// +// macro_rules! trace( +// ($($arg:tt)*) => (if cfg!(not(ndebug)) { +// log!(5, "{}\n{}", format_args!($($arg)*), ::Trace) +// }) +// ); macro_rules! inspect( ($name:expr, $value:expr) => ({ diff --git a/src/net.rs b/src/net.rs index 420e807d..0abeb27a 100644 --- a/src/net.rs +++ b/src/net.rs @@ -7,10 +7,10 @@ use std::io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError, Stream, Listener, Acceptor}; use std::io::net::ip::{SocketAddr, ToSocketAddr, Port}; use std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor}; -use std::mem::{mod, transmute, transmute_copy}; -use std::raw::{mod, TraitObject}; +use std::mem::{self, transmute, transmute_copy}; +use std::raw::{self, TraitObject}; -use uany::UncheckedBoxAnyDowncast; +use uany::UnsafeAnyExt; use openssl::ssl::{Ssl, SslStream, SslContext, VerifyCallback}; use openssl::ssl::SslVerifyMode::SslVerifyPeer; use openssl::ssl::SslMethod::Sslv23; @@ -107,12 +107,12 @@ impl<'a> Writer for &'a mut NetworkStream { impl UnsafeAnyExt for NetworkStream + Send { unsafe fn downcast_ref_unchecked(&self) -> &T { - mem::transmute(mem::transmute::<&NetworkStream + Send, + mem::transmute(mem::transmute::<&(NetworkStream + Send), raw::TraitObject>(self).data) } unsafe fn downcast_mut_unchecked(&mut self) -> &mut T { - mem::transmute(mem::transmute::<&mut NetworkStream + Send, + mem::transmute(mem::transmute::<&mut (NetworkStream + Send), raw::TraitObject>(self).data) } @@ -301,7 +301,7 @@ fn lift_ssl_error(ssl: SslError) -> IoError { #[cfg(test)] mod tests { use std::boxed::BoxAny; - use uany::UncheckedBoxAnyDowncast; + use uany::UnsafeAnyExt; use mock::MockStream; use super::NetworkStream; diff --git a/src/server/request.rs b/src/server/request.rs index 4a7697cd..c302706e 100644 --- a/src/server/request.rs +++ b/src/server/request.rs @@ -7,7 +7,7 @@ use std::io::net::ip::SocketAddr; use {HttpResult}; use version::{HttpVersion}; -use method::Method::{mod, Get, Head}; +use method::Method::{self, Get, Head}; use header::Headers; use header::common::{ContentLength, TransferEncoding}; use http::{read_request_line}; diff --git a/src/status.rs b/src/status.rs index 4f25c584..496e82ab 100644 --- a/src/status.rs +++ b/src/status.rs @@ -1,7 +1,10 @@ //! Status Codes use std::fmt; +use std::num::{FromPrimitive, ToPrimitive}; use std::mem::transmute; +use std::cmp::Ordering::{self, Less, Equal, Greater}; + // shamelessly lifted from Teepee. I tried a few schemes, this really // does seem like the best. From 66aa08ecddd0111f3cb5f0b2ee7a04d9a8bd2d74 Mon Sep 17 00:00:00 2001 From: Jonathan Reem Date: Tue, 6 Jan 2015 01:15:32 +0100 Subject: [PATCH 4/8] Make downcasting inherent methods on NetworkStream. --- src/net.rs | 49 ++++++++++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/src/net.rs b/src/net.rs index 0abeb27a..b15d24c8 100644 --- a/src/net.rs +++ b/src/net.rs @@ -1,13 +1,12 @@ //! A collection of traits abstracting over Listeners and Streams. -use std::any::{Any, AnyRefExt}; -use std::boxed::BoxAny; +use std::any::Any; use std::fmt; use std::intrinsics::TypeId; use std::io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError, Stream, Listener, Acceptor}; use std::io::net::ip::{SocketAddr, ToSocketAddr, Port}; use std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor}; -use std::mem::{self, transmute, transmute_copy}; +use std::mem; use std::raw::{self, TraitObject}; use uany::UnsafeAnyExt; @@ -105,46 +104,54 @@ impl<'a> Writer for &'a mut NetworkStream { fn flush(&mut self) -> IoResult<()> { (**self).flush() } } -impl UnsafeAnyExt for NetworkStream + Send { +impl UnsafeAnyExt for NetworkStream { unsafe fn downcast_ref_unchecked(&self) -> &T { - mem::transmute(mem::transmute::<&(NetworkStream + Send), + mem::transmute(mem::transmute::<&NetworkStream, raw::TraitObject>(self).data) } unsafe fn downcast_mut_unchecked(&mut self) -> &mut T { - mem::transmute(mem::transmute::<&mut (NetworkStream + Send), + mem::transmute(mem::transmute::<&mut NetworkStream, raw::TraitObject>(self).data) } - unsafe fn downcast_unchecked(self: Box) -> Box { - mem::transmute(mem::transmute::, + unsafe fn downcast_unchecked(self: Box) -> Box { + mem::transmute(mem::transmute::, raw::TraitObject>(self).data) } } -impl<'a> AnyRefExt<'a> for &'a (NetworkStream + 'static) { +impl NetworkStream { + /// Is the underlying type in this trait object a T? #[inline] - fn is(self) -> bool { + pub fn is(&self) -> bool { self.get_type_id() == TypeId::of::() } + /// If the underlying type is T, get a reference to the contained data. #[inline] - fn downcast_ref(self) -> Option<&'a T> { + pub fn downcast_ref(&self) -> Option<&T> { if self.is::() { - unsafe { - // Get the raw representation of the trait object - let to: TraitObject = transmute_copy(&self); - // Extract the data pointer - Some(transmute(to.data)) - } + Some(unsafe { self.downcast_ref_unchecked() }) } else { None } } -} -impl BoxAny for Box { - fn downcast(self) -> Result, Box> { + /// If the underlying type is T, get a mutable reference to the contained + /// data. + #[inline] + pub fn downcast_mut(&mut self) -> Option<&mut T> { + if self.is::() { + Some(unsafe { self.downcast_mut_unchecked() }) + } else { + None + } + } + + /// If the underlying type is T, extract it. + pub fn downcast(self: Box) + -> Result, Box> { if self.is::() { Ok(unsafe { self.downcast_unchecked() }) } else { @@ -310,7 +317,7 @@ mod tests { fn test_downcast_box_stream() { let stream = box MockStream::new() as Box; - let mock = stream.downcast::().unwrap(); + let mock = stream.downcast::().ok().unwrap(); assert_eq!(mock, box MockStream::new()); } From 93fcd05b9d3c2f424e0fe0d643a0124c39f26b50 Mon Sep 17 00:00:00 2001 From: Jonathan Reem Date: Tue, 6 Jan 2015 01:15:47 +0100 Subject: [PATCH 5/8] Miscellaneous fixes and test updates for all the other changes - http::LINE_ENDING is now an &'static str --- src/client/request.rs | 16 ++++++++-------- src/client/response.rs | 2 +- src/header/mod.rs | 12 ++++++------ src/header/shared/util.rs | 4 ++-- src/http.rs | 21 ++++++++------------- src/lib.rs | 20 -------------------- src/mock.rs | 2 +- src/server/request.rs | 14 ++++++++------ src/server/response.rs | 2 +- 9 files changed, 35 insertions(+), 58 deletions(-) diff --git a/src/client/request.rs b/src/client/request.rs index e83ed7c5..8b97034b 100644 --- a/src/client/request.rs +++ b/src/client/request.rs @@ -114,15 +114,14 @@ impl Request { } debug!("writing head: {} {} {}", self.method, uri, self.version); - try!(write!(&mut self.body, "{} {} {}", self.method, uri, self.version)); - try!(self.body.write(LINE_ENDING)); + try!(write!(&mut self.body, "{} {} {}{}", + self.method, uri, self.version, LINE_ENDING)); let stream = match self.method { Get | Head => { debug!("headers [\n{}]", self.headers); - try!(write!(&mut self.body, "{}", self.headers)); - try!(self.body.write(LINE_ENDING)); + try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING)); EmptyWriter(self.body.unwrap()) }, _ => { @@ -155,8 +154,7 @@ impl Request { } debug!("headers [\n{}]", self.headers); - try!(write!(&mut self.body, "{}", self.headers)); - try!(self.body.write(LINE_ENDING)); + try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING)); if chunked { ChunkedWriter(self.body.unwrap()) @@ -217,7 +215,8 @@ mod tests { Get, Url::parse("http://example.dom").unwrap(), &mut MockConnector ).unwrap(); let req = req.start().unwrap(); - let stream = *req.body.end().unwrap().into_inner().downcast::().unwrap(); + let stream = *req.body.end().unwrap() + .into_inner().downcast::().ok().unwrap(); let bytes = stream.write.into_inner(); let s = from_utf8(bytes[]).unwrap(); assert!(!s.contains("Content-Length:")); @@ -230,7 +229,8 @@ mod tests { Head, Url::parse("http://example.dom").unwrap(), &mut MockConnector ).unwrap(); let req = req.start().unwrap(); - let stream = *req.body.end().unwrap().into_inner().downcast::().unwrap(); + let stream = *req.body.end().unwrap() + .into_inner().downcast::().ok().unwrap(); let bytes = stream.write.into_inner(); let s = from_utf8(bytes[]).unwrap(); assert!(!s.contains("Content-Length:")); diff --git a/src/client/response.rs b/src/client/response.rs index 7bffe22d..f87dd936 100644 --- a/src/client/response.rs +++ b/src/client/response.rs @@ -120,7 +120,7 @@ mod tests { status_raw: RawStatus(200, Borrowed("OK")) }; - let b = res.into_inner().downcast::().unwrap(); + let b = res.into_inner().downcast::().ok().unwrap(); assert_eq!(b, box MockStream::new()); } diff --git a/src/header/mod.rs b/src/header/mod.rs index 89e7dc42..10ec5d83 100644 --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -10,7 +10,8 @@ use std::borrow::Cow::{Borrowed, Owned}; use std::fmt::{self, Show}; use std::intrinsics::TypeId; use std::raw::TraitObject; -use std::str::{SendStr, FromStr}; +use std::str::FromStr; +use std::string::CowString; use std::collections::HashMap; use std::collections::hash_map::{Iter, Entry}; use std::iter::FromIterator; @@ -135,8 +136,8 @@ impl Headers { Some((name, value)) => { debug!("raw header: {}={}", name, value[]); let name = CaseInsensitive(Owned(name)); - let mut item = match headers.data.entry(name) { - Entry::Vacant(entry) => entry.set(MuCell::new(Item::raw(vec![]))), + let mut item = match headers.data.entry(&name) { + Entry::Vacant(entry) => entry.insert(MuCell::new(Item::raw(vec![]))), Entry::Occupied(entry) => entry.into_mut() }; @@ -438,7 +439,7 @@ impl fmt::Show for Item { None => match self.raw { Some(ref raw) => { for part in raw.iter() { - try!(fmt.write(part.as_slice())); + try!(write!(fmt, "{}", part.as_slice())); } Ok(()) }, @@ -455,8 +456,7 @@ impl fmt::Show for Box { } /// Case-insensitive string. -//#[derive(Clone)] -pub struct CaseInsensitive(SendStr); +pub struct CaseInsensitive(CowString<'static>); impl FromStr for CaseInsensitive { fn from_str(s: &str) -> Option { diff --git a/src/header/shared/util.rs b/src/header/shared/util.rs index 86359d66..73d0422c 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(unsafe { raw[].unsafe_get(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(unsafe { raw.as_slice().unsafe_get(0).as_slice() }) + from_one_comma_delimited(raw[0][]) } /// Reads a comma-delimited raw string into a Vec. diff --git a/src/http.rs b/src/http.rs index 610303ec..d0c63e3a 100644 --- a/src/http.rs +++ b/src/http.rs @@ -5,7 +5,8 @@ use std::cmp::min; use std::fmt; use std::io::{self, Reader, IoResult, BufWriter}; use std::num::from_u16; -use std::str::{self, SendStr, FromStr}; +use std::str::{self, FromStr}; +use std::string::CowString; use url::Url; use url::ParseError as UrlError; @@ -108,7 +109,7 @@ impl Reader for HttpReader { *opt_remaining = if rem > 0 { Some(rem) } else { - try!(eat(body, LINE_ENDING)); + try!(eat(body, LINE_ENDING.as_bytes())); None }; Ok(count) @@ -237,9 +238,9 @@ impl Writer for HttpWriter { ChunkedWriter(ref mut w) => { let chunk_size = msg.len(); debug!("chunked write, size = {}", chunk_size); - try!(write!(w, "{:X}{}{}", chunk_size, CR as char, LF as char)); + try!(write!(w, "{:X}{}", chunk_size, LINE_ENDING)); try!(w.write(msg)); - w.write(LINE_ENDING) + w.write_str(LINE_ENDING) }, SizedWriter(ref mut w, ref mut remaining) => { let len = msg.len(); @@ -283,7 +284,7 @@ pub const SP: u8 = b' '; pub const CR: u8 = b'\r'; pub const LF: u8 = b'\n'; pub const STAR: u8 = b'*'; -pub const LINE_ENDING: &'static [u8] = &[CR, LF]; +pub const LINE_ENDING: &'static str = "\r\n"; /// A `Show`able struct to easily write line endings to a formatter. pub struct LineEnding; @@ -292,13 +293,7 @@ impl Copy for LineEnding {} impl fmt::Show for LineEnding { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.write(LINE_ENDING) - } -} - -impl AsSlice for LineEnding { - fn as_slice(&self) -> &[u8] { - LINE_ENDING + fmt.write_str(LINE_ENDING) } } @@ -584,7 +579,7 @@ pub type StatusLine = (HttpVersion, RawStatus); /// The raw status code and reason-phrase. #[derive(PartialEq, Show)] -pub struct RawStatus(pub u16, pub SendStr); +pub struct RawStatus(pub u16, pub CowString<'static>); impl Clone for RawStatus { fn clone(&self) -> RawStatus { diff --git a/src/lib.rs b/src/lib.rs index 9ad7b217..4b72a1c6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -145,12 +145,9 @@ pub use method::Method::{Get, Head, Post, Delete}; pub use status::StatusCode::{Ok, BadRequest, NotFound}; pub use server::Server; -use std::fmt; use std::error::{Error, FromError}; use std::io::IoError; -use std::rt::backtrace; - use self::HttpError::{HttpMethodError, HttpUriError, HttpVersionError, HttpHeaderError, HttpStatusError, HttpIoError}; @@ -160,23 +157,6 @@ macro_rules! todo( }) ); -// FIXME(reem): Uncomment this when backtrace::write can write to a fmt::Formatter. -// #[allow(dead_code)] -// struct Trace; -// -// impl fmt::Show for Trace { -// fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { -// let _ = backtrace::write(fmt); -// Result::Ok(()) -// } -// } -// -// macro_rules! trace( -// ($($arg:tt)*) => (if cfg!(not(ndebug)) { -// log!(5, "{}\n{}", format_args!($($arg)*), ::Trace) -// }) -// ); - macro_rules! inspect( ($name:expr, $value:expr) => ({ let v = $value; diff --git a/src/mock.rs b/src/mock.rs index db1fe05a..714c4ac1 100644 --- a/src/mock.rs +++ b/src/mock.rs @@ -92,7 +92,7 @@ macro_rules! mock_connector ( let key = format!("{}://{}", scheme, host); // ignore port for now - match map.find(&&*key) { + match map.get(&&*key) { Some(res) => Ok(::mock::MockStream { write: ::std::io::MemWriter::new(), read: ::std::io::MemReader::new(res.to_string().into_bytes()) diff --git a/src/server/request.rs b/src/server/request.rs index c302706e..5c808441 100644 --- a/src/server/request.rs +++ b/src/server/request.rs @@ -78,9 +78,11 @@ mod tests { use mock::MockStream; use super::Request; - macro_rules! sock( - ($s:expr) => (::std::str::from_str::<::std::io::net::ip::SocketAddr>($s).unwrap()) - ); + use std::io::net::ip::SocketAddr; + + fn sock(s: &str) -> SocketAddr { + s.parse().unwrap() + } #[test] fn test_get_empty_body() { @@ -91,7 +93,7 @@ mod tests { I'm a bad request.\r\n\ "); - let mut req = Request::new(&mut stream, sock!("127.0.0.1:80")).unwrap(); + let mut req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); assert_eq!(req.read_to_string(), Ok("".to_string())); } @@ -104,7 +106,7 @@ mod tests { I'm a bad request.\r\n\ "); - let mut req = Request::new(&mut stream, sock!("127.0.0.1:80")).unwrap(); + let mut req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); assert_eq!(req.read_to_string(), Ok("".to_string())); } @@ -117,7 +119,7 @@ mod tests { I'm a bad request.\r\n\ "); - let mut req = Request::new(&mut stream, sock!("127.0.0.1:80")).unwrap(); + let mut req = Request::new(&mut stream, sock("127.0.0.1:80")).unwrap(); assert_eq!(req.read_to_string(), Ok("".to_string())); } } diff --git a/src/server/response.rs b/src/server/response.rs index 7934dc23..9204e9cd 100644 --- a/src/server/response.rs +++ b/src/server/response.rs @@ -107,7 +107,7 @@ impl<'a> Response<'a, Fresh> { debug!("headers [\n{}]", self.headers); try!(write!(&mut self.body, "{}", self.headers)); - try!(self.body.write(LINE_ENDING)); + try!(self.body.write_str(LINE_ENDING)); let stream = if chunked { ChunkedWriter(self.body.unwrap()) From 4756544a1829ec4a6d2bdbc3972ec777c4c1818c Mon Sep 17 00:00:00 2001 From: Jonathan Reem Date: Tue, 6 Jan 2015 01:24:00 +0100 Subject: [PATCH 6/8] Fix the benches for latest rust changes. --- benches/client_mock_tcp.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/benches/client_mock_tcp.rs b/benches/client_mock_tcp.rs index 3776077c..db6efe80 100644 --- a/benches/client_mock_tcp.rs +++ b/benches/client_mock_tcp.rs @@ -5,7 +5,6 @@ extern crate hyper; extern crate test; use std::fmt::{self, Show}; -use std::str::from_str; use std::io::{IoResult, MemReader}; use std::io::net::ip::SocketAddr; use std::os; @@ -85,7 +84,7 @@ impl hyper::header::HeaderFormat for Foo { impl net::NetworkStream for MockStream { fn peer_name(&mut self) -> IoResult { - Ok(from_str("127.0.0.1:1337").unwrap()) + Ok("127.0.0.1:1337".parse().unwrap()) } } From 23aeb4993ad3710c6d4fad35302822a6bc4b34c2 Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Mon, 5 Jan 2015 19:16:34 -0800 Subject: [PATCH 7/8] fix writing raw headers, quality_item --- src/header/mod.rs | 17 +++++++++++++++-- src/header/shared/quality_item.rs | 4 ++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/header/mod.rs b/src/header/mod.rs index 10ec5d83..4281092c 100644 --- a/src/header/mod.rs +++ b/src/header/mod.rs @@ -10,7 +10,7 @@ use std::borrow::Cow::{Borrowed, Owned}; use std::fmt::{self, Show}; use std::intrinsics::TypeId; use std::raw::TraitObject; -use std::str::FromStr; +use std::str::{FromStr, from_utf8}; use std::string::CowString; use std::collections::HashMap; use std::collections::hash_map::{Iter, Entry}; @@ -439,7 +439,13 @@ impl fmt::Show for Item { None => match self.raw { Some(ref raw) => { for part in raw.iter() { - try!(write!(fmt, "{}", part.as_slice())); + match from_utf8(part[]) { + Ok(s) => try!(fmt.write_str(s)), + Err(e) => { + error!("raw header value is not utf8. header={}, error={}", part[], e); + return Err(fmt::Error); + } + } } Ok(()) }, @@ -646,6 +652,13 @@ mod tests { assert_eq!(s[], "Host: foo.bar\r\nContent-Length: 15\r\n"); } + #[test] + fn test_headers_show_raw() { + let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap(); + let s = headers.to_string(); + assert_eq!(s, "Content-Length: 10\r\n"); + } + #[test] fn test_set_raw() { let mut headers = Headers::new(); diff --git a/src/header/shared/quality_item.rs b/src/header/shared/quality_item.rs index 5272faac..04bad305 100644 --- a/src/header/shared/quality_item.rs +++ b/src/header/shared/quality_item.rs @@ -79,7 +79,7 @@ pub fn qitem(item: T) -> QualityItem { #[test] fn test_quality_item_show1() { let x = qitem(Chunked); - assert_eq!(format!("{}", x), "chunked; q=1.000"); + assert_eq!(format!("{}", x), "chunked; q=1"); } #[test] fn test_quality_item_show2() { @@ -93,7 +93,7 @@ fn test_quality_item_show3() { item: EncodingExt("identity".to_string()), quality: 0.5f32, }; - assert_eq!(format!("{}", x), "identity; q=0.500"); + assert_eq!(format!("{}", x), "identity; q=0.5"); } #[test] From 92b836dc0367f67d9e4502fc90eee0f53337b93a Mon Sep 17 00:00:00 2001 From: Sean McArthur Date: Mon, 5 Jan 2015 19:27:44 -0800 Subject: [PATCH 8/8] v0.0.21 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index c9228ab8..b33b4e33 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "hyper" -version = "0.0.20" +version = "0.0.21" description = "A modern HTTP library." readme = "README.md" documentation = "http://hyperium.github.io/hyper/hyper/index.html"