repo
stringclasses 1
value | pull_number
int64 20
3.81k
| instance_id
stringlengths 18
20
| issue_numbers
listlengths 1
2
| base_commit
stringlengths 40
40
| patch
stringlengths 214
153k
| test_patch
stringlengths 288
262k
| problem_statement
stringlengths 22
7.42k
| hints_text
stringlengths 0
66.9k
| created_at
stringlengths 20
20
| version
stringclasses 21
values | environment_setup_commit
stringclasses 21
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
hyperium/hyper
| 195
|
hyperium__hyper-195
|
[
"194"
] |
5e560cb1c10ba9da0f0763253d7c29de6a6675b4
|
diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs
--- a/src/header/common/authorization.rs
+++ b/src/header/common/authorization.rs
@@ -1,6 +1,6 @@
use std::fmt::{mod, Show};
use std::str::{FromStr, from_utf8};
-use serialize::base64::{ToBase64, FromBase64, Standard, Config};
+use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline};
use header::{Header, HeaderFormat};
/// The `Authorization` header field.
diff --git a/src/header/common/authorization.rs b/src/header/common/authorization.rs
--- a/src/header/common/authorization.rs
+++ b/src/header/common/authorization.rs
@@ -97,6 +97,7 @@ impl Scheme for Basic {
}
text.as_bytes().to_base64(Config {
char_set: Standard,
+ newline: Newline::CRLF,
pad: true,
line_length: None
}).fmt(f)
diff --git a/src/header/common/content_length.rs b/src/header/common/content_length.rs
--- a/src/header/common/content_length.rs
+++ b/src/header/common/content_length.rs
@@ -6,7 +6,7 @@ use super::util::from_one_raw_str;
/// The `Content-Length` header.
///
/// Simply a wrapper around a `uint`.
-#[deriving(Clone, PartialEq, Show)]
+#[deriving(Copy, Clone, PartialEq, Show)]
pub struct ContentLength(pub uint);
deref!(ContentLength -> uint)
diff --git a/src/header/common/date.rs b/src/header/common/date.rs
--- a/src/header/common/date.rs
+++ b/src/header/common/date.rs
@@ -6,7 +6,7 @@ use super::util::{from_one_raw_str, tm_from_str};
// Egh, replace as soon as something better than time::Tm exists.
/// The `Date` header field.
-#[deriving(PartialEq, Clone)]
+#[deriving(Copy, PartialEq, Clone)]
pub struct Date(pub Tm);
deref!(Date -> Tm)
diff --git a/src/header/common/expires.rs b/src/header/common/expires.rs
--- a/src/header/common/expires.rs
+++ b/src/header/common/expires.rs
@@ -5,7 +5,7 @@ use header::{Header, HeaderFormat};
use super::util::{from_one_raw_str, tm_from_str};
/// The `Expires` header field.
-#[deriving(PartialEq, Clone)]
+#[deriving(Copy, PartialEq, Clone)]
pub struct Expires(pub Tm);
deref!(Expires -> Tm)
diff --git a/src/header/common/if_modified_since.rs b/src/header/common/if_modified_since.rs
--- a/src/header/common/if_modified_since.rs
+++ b/src/header/common/if_modified_since.rs
@@ -5,7 +5,7 @@ use header::{Header, HeaderFormat};
use super::util::{from_one_raw_str, tm_from_str};
/// The `If-Modified-Since` header field.
-#[deriving(PartialEq, Clone)]
+#[deriving(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
--- a/src/header/common/last_modified.rs
+++ b/src/header/common/last_modified.rs
@@ -5,7 +5,7 @@ use header::{Header, HeaderFormat};
use super::util::{from_one_raw_str, tm_from_str};
/// The `LastModified` header field.
-#[deriving(PartialEq, Clone)]
+#[deriving(Copy, PartialEq, Clone)]
pub struct LastModified(pub Tm);
deref!(LastModified -> Tm)
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -285,6 +285,8 @@ pub const LINE_ENDING: &'static [u8] = &[CR, LF];
/// A `Show`able struct to easily write line endings to a formatter.
pub struct LineEnding;
+impl Copy for LineEnding {}
+
impl fmt::Show for LineEnding {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write(LINE_ENDING)
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -163,7 +163,7 @@ struct Trace;
impl fmt::Show for Trace {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let _ = backtrace::write(fmt);
- ::std::result::Ok(())
+ Result::Ok(())
}
}
diff --git a/src/net.rs b/src/net.rs
--- a/src/net.rs
+++ b/src/net.rs
@@ -18,9 +18,11 @@ use openssl::ssl::error::{SslError, StreamError, OpenSslErrors, SslSessionClosed
use self::HttpStream::{Http, Https};
/// The write-status indicating headers have not been written.
+#[allow(missing_copy_implementations)]
pub struct Fresh;
/// The write-status indicating headers have been written.
+#[allow(missing_copy_implementations)]
pub struct Streaming;
/// An abstraction to listen for connections on a certain port.
diff --git a/src/net.rs b/src/net.rs
--- a/src/net.rs
+++ b/src/net.rs
@@ -236,6 +238,7 @@ impl NetworkStream for HttpStream {
}
/// A connector that will produce HttpStreams.
+#[allow(missing_copy_implementations)]
pub struct HttpConnector;
impl NetworkConnector<HttpStream> for HttpConnector {
diff --git a/src/status.rs b/src/status.rs
--- a/src/status.rs
+++ b/src/status.rs
@@ -1569,6 +1569,8 @@ impl StatusCode {
}
}
+impl Copy for StatusCode {}
+
/// Formats the status code, *including* the canonical reason.
///
/// ```rust
diff --git a/src/status.rs b/src/status.rs
--- a/src/status.rs
+++ b/src/status.rs
@@ -1684,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)]
+#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Copy)]
pub enum StatusClass {
/// 1xx: Informational - Request received, continuing process
Informational = 100,
diff --git a/src/version.rs b/src/version.rs
--- 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)]
+#[deriving(PartialEq, PartialOrd, Copy)]
pub enum HttpVersion {
/// `HTTP/0.9`
Http09,
|
diff --git a/src/header/common/etag.rs b/src/header/common/etag.rs
--- a/src/header/common/etag.rs
+++ b/src/header/common/etag.rs
@@ -118,7 +118,7 @@ mod tests {
etag = Header::parse_header([b"W/\"\x65\x62\"".to_vec()].as_slice());
assert_eq!(etag, Some(Etag {
weak: true,
- tag: "\u0065\u0062".into_string()
+ tag: "\u{0065}\u{0062}".into_string()
}));
etag = Header::parse_header([b"W/\"\"".to_vec()].as_slice());
diff --git a/src/header/common/etag.rs b/src/header/common/etag.rs
--- a/src/header/common/etag.rs
+++ b/src/header/common/etag.rs
@@ -153,4 +153,4 @@ mod tests {
}
}
-bench_header!(bench, Etag, { vec![b"W/\"nonemptytag\"".to_vec()] })
\ No newline at end of file
+bench_header!(bench, Etag, { vec![b"W/\"nonemptytag\"".to_vec()] })
|
Cannot build hyper
I can't seem to build hyper:
```
$ cargo build
Compiling hyper v0.0.1 (https://github.com/hyperium/hyper#5e560cb1)
/home/danilo/.cargo/git/checkouts/hyper-3d407dab77cf6838/master/src/header/common/etag.rs:121:20: 121:25 warning: \U00ABCD12 and \uABCD escapes are deprecated
/home/danilo/.cargo/git/checkouts/hyper-3d407dab77cf6838/master/src/header/common/etag.rs:121 tag: "\u0065\u0062".into_string()
^~~~~
/home/danilo/.cargo/git/checkouts/hyper-3d407dab77cf6838/master/src/header/common/etag.rs:121:20: 121:25 help: use \u{ABCD12} escapes instead
/home/danilo/.cargo/git/checkouts/hyper-3d407dab77cf6838/master/src/header/common/etag.rs:121 tag: "\u0065\u0062".into_string()
^~~~~
/home/danilo/.cargo/git/checkouts/hyper-3d407dab77cf6838/master/src/header/common/etag.rs:121:26: 121:31 warning: \U00ABCD12 and \uABCD escapes are deprecated
/home/danilo/.cargo/git/checkouts/hyper-3d407dab77cf6838/master/src/header/common/etag.rs:121 tag: "\u0065\u0062".into_string()
^~~~~
/home/danilo/.cargo/git/checkouts/hyper-3d407dab77cf6838/master/src/header/common/etag.rs:121:26: 121:31 help: use \u{ABCD12} escapes instead
/home/danilo/.cargo/git/checkouts/hyper-3d407dab77cf6838/master/src/header/common/etag.rs:121 tag: "\u0065\u0062".into_string()
^~~~~
/home/danilo/.cargo/git/checkouts/hyper-3d407dab77cf6838/master/src/lib.rs:166:9: 166:26 error: unresolved name `std::result::Ok`
/home/danilo/.cargo/git/checkouts/hyper-3d407dab77cf6838/master/src/lib.rs:166 ::std::result::Ok(())
^~~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `hyper`.
```
My versions:
```
$ rustc --version
rustc 0.13.0-nightly (193390d0e 2014-12-11 22:56:54 +0000)
$ cargo --version
cargo 0.0.1-pre-nightly (0f6667c 2014-12-08 21:19:01 +0000)
```
It's possible that I'm doing something wrong though, as I'm new to Rust and Cargo.
|
The latest rustc updates seem to have introduced some breaking changes. These same build errors are also holding up a PR I have.
|
2014-12-12T20:25:31Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
hyperium/hyper
| 182
|
hyperium__hyper-182
|
[
"62"
] |
2d6c8819cdf196e1467f162d89da5559570b7705
|
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -42,18 +42,18 @@ Client:
```rust
fn main() {
- // Creating an outgoing request.
- let mut req = Request::get(Url::parse("http://www.gooogle.com/").unwrap()).unwrap();
+ // Create a client.
+ let mut client = Client::new();
- // Setting a header.
- req.headers_mut().set(Connection(vec![Close]));
+ // Creating an outgoing request.
+ let mut res = client.get("http://www.gooogle.com/")
+ // set a header
+ .header(Connection(vec![Close]))
+ // let 'er go!
+ .send();
- // Start the Request, writing headers and starting streaming.
- let res = req.start().unwrap()
- // Send the Request.
- .send().unwrap()
- // Read the Response.
- .read_to_string().unwrap();
+ // Read the Response.
+ let body = res.read_to_string().unwrap();
println!("Response: {}", res);
}
diff --git a/benches/client.rs b/benches/client.rs
--- a/benches/client.rs
+++ b/benches/client.rs
@@ -22,9 +26,10 @@ macro_rules! try_return(
}
}})
-fn handle(_: Request, res: Response) {
+fn handle(_r: Request, res: Response) {
+ static BODY: &'static [u8] = b"Benchmarking hyper vs others!";
let mut res = try_return!(res.start());
- try_return!(res.write(b"Benchmarking hyper vs others!"))
+ try_return!(res.write(BODY))
try_return!(res.end());
}
diff --git a/examples/client.rs b/examples/client.rs
--- a/examples/client.rs
+++ b/examples/client.rs
@@ -4,8 +4,7 @@ use std::os;
use std::io::stdout;
use std::io::util::copy;
-use hyper::Url;
-use hyper::client::Request;
+use hyper::Client;
fn main() {
let args = os::args();
diff --git a/examples/client.rs b/examples/client.rs
--- a/examples/client.rs
+++ b/examples/client.rs
@@ -17,26 +16,17 @@ fn main() {
}
};
- let url = match Url::parse(args[1].as_slice()) {
- Ok(url) => {
- println!("GET {}...", url)
- url
- },
- Err(e) => panic!("Invalid URL: {}", e)
- };
+ let url = &*args[1];
+ let mut client = Client::new();
- let req = match Request::get(url) {
- Ok(req) => req,
+ let mut res = match client.get(url).send() {
+ Ok(res) => res,
Err(err) => panic!("Failed to connect: {}", err)
};
- let mut res = req
- .start().unwrap() // failure: Error writing Headers
- .send().unwrap(); // failure: Error reading Response head.
-
println!("Response: {}", res.status);
- println!("{}", res.headers);
+ println!("Headers:\n{}", res.headers);
match copy(&mut res, &mut stdout()) {
Ok(..) => (),
Err(e) => panic!("Stream failure: {}", e)
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -8,12 +8,11 @@ use method::Method::{Get, Post, Delete, Put, Patch, Head, Options};
use header::Headers;
use header::common::{mod, Host};
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
-use HttpError::HttpUriError;
use http::{HttpWriter, LINE_ENDING};
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
use version;
use HttpResult;
-use client::Response;
+use client::{Response, get_host_and_port};
/// A client request to a remote server.
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -42,23 +41,14 @@ impl<W> Request<W> {
impl Request<Fresh> {
/// Create a new client request.
pub fn new(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
- let mut conn = HttpConnector;
+ let mut conn = HttpConnector(None);
Request::with_connector(method, url, &mut conn)
}
/// Create a new client request with a specific underlying NetworkStream.
pub fn with_connector<C: NetworkConnector<S>, S: NetworkStream>(method: method::Method, url: Url, connector: &mut C) -> HttpResult<Request<Fresh>> {
debug!("{} {}", method, url);
- let host = match url.serialize_host() {
- Some(host) => host,
- None => return Err(HttpUriError)
- };
- debug!("host={}", host);
- let port = match url.port_or_default() {
- Some(port) => port,
- None => return Err(HttpUriError)
- };
- debug!("port={}", port);
+ let (host, port) = try!(get_host_and_port(&url));
let stream: S = try!(connector.connect(host[], port, &*url.scheme));
let stream = ThroughWriter(BufferedWriter::new(box stream as Box<NetworkStream + Send>));
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -80,30 +70,37 @@ impl Request<Fresh> {
/// Create a new GET request.
#[inline]
+ #[deprecated = "use hyper::Client"]
pub fn get(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Get, url) }
/// Create a new POST request.
#[inline]
+ #[deprecated = "use hyper::Client"]
pub fn post(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Post, url) }
/// Create a new DELETE request.
#[inline]
+ #[deprecated = "use hyper::Client"]
pub fn delete(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Delete, url) }
/// Create a new PUT request.
#[inline]
+ #[deprecated = "use hyper::Client"]
pub fn put(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Put, url) }
/// Create a new PATCH request.
#[inline]
+ #[deprecated = "use hyper::Client"]
pub fn patch(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Patch, url) }
/// Create a new HEAD request.
#[inline]
+ #[deprecated = "use hyper::Client"]
pub fn head(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Head, url) }
/// Create a new OPTIONS request.
#[inline]
+ #[deprecated = "use hyper::Client"]
pub fn options(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Options, url) }
/// Consume a Fresh Request, writing the headers and method,
diff --git a/src/client/response.rs b/src/client/response.rs
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -38,7 +38,7 @@ impl Response {
debug!("{} {}", version, status);
let headers = try!(header::Headers::from_raw(&mut stream));
- debug!("{}", headers);
+ debug!("Headers: [\n{}]", headers);
let body = if headers.has::<TransferEncoding>() {
match headers.get::<TransferEncoding>() {
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -30,7 +30,7 @@ pub mod common;
///
/// This trait represents the construction and identification of headers,
/// and contains trait-object unsafe methods.
-pub trait Header: Any + Send + Sync {
+pub trait Header: Clone + Any + Send + Sync {
/// Returns the name of the header field this belongs to.
///
/// The market `Option` is to hint to the type system which implementation
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -7,6 +7,7 @@ use std::num::from_u16;
use std::str::{mod, SendStr};
use url::Url;
+use url::ParseError as UrlError;
use method;
use status::StatusCode;
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -234,6 +235,7 @@ impl<W: Writer> Writer for HttpWriter<W> {
ThroughWriter(ref mut w) => w.write(msg),
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!(w.write(msg));
w.write(LINE_ENDING)
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -419,7 +421,7 @@ pub fn read_uri<R: Reader>(stream: &mut R) -> HttpResult<uri::RequestUri> {
break;
},
CR | LF => {
- return Err(HttpUriError)
+ return Err(HttpUriError(UrlError::InvalidCharacter))
},
b => s.push(b as char)
}
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -431,26 +433,13 @@ pub fn read_uri<R: Reader>(stream: &mut R) -> HttpResult<uri::RequestUri> {
if s.as_slice().starts_with("/") {
Ok(AbsolutePath(s))
} else if s.as_slice().contains("/") {
- match Url::parse(s.as_slice()) {
- Ok(u) => Ok(AbsoluteUri(u)),
- Err(_e) => {
- debug!("URL err {}", _e);
- Err(HttpUriError)
- }
- }
+ Ok(AbsoluteUri(try!(Url::parse(s.as_slice()))))
} else {
let mut temp = "http://".to_string();
temp.push_str(s.as_slice());
- match Url::parse(temp.as_slice()) {
- Ok(_u) => {
- todo!("compare vs u.authority()");
- Ok(Authority(s))
- }
- Err(_e) => {
- debug!("URL err {}", _e);
- Err(HttpUriError)
- }
- }
+ try!(Url::parse(temp.as_slice()));
+ todo!("compare vs u.authority()");
+ Ok(Authority(s))
}
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -138,6 +138,7 @@ extern crate mucell;
pub use std::io::net::ip::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr, Port};
pub use mimewrapper::mime;
pub use url::Url;
+pub use client::Client;
pub use method::Method::{Get, Head, Post, Delete};
pub use status::StatusCode::{Ok, BadRequest, NotFound};
pub use server::Server;
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -208,7 +212,7 @@ pub enum HttpError {
/// An invalid `Method`, such as `GE,T`.
HttpMethodError,
/// An invalid `RequestUri`, such as `exam ple.domain`.
- HttpUriError,
+ HttpUriError(url::ParseError),
/// An invalid `HttpVersion`, such as `HTP/1.1`
HttpVersionError,
/// An invalid `Header`.
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -223,7 +227,7 @@ impl Error for HttpError {
fn description(&self) -> &str {
match *self {
HttpMethodError => "Invalid Method specified",
- HttpUriError => "Invalid Request URI specified",
+ HttpUriError(_) => "Invalid Request URI specified",
HttpVersionError => "Invalid HTTP version specified",
HttpHeaderError => "Invalid Header provided",
HttpStatusError => "Invalid Status provided",
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -234,6 +238,7 @@ impl Error for HttpError {
fn cause(&self) -> Option<&Error> {
match *self {
HttpIoError(ref error) => Some(error as &Error),
+ HttpUriError(ref error) => Some(error as &Error),
_ => None,
}
}
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -245,6 +250,12 @@ impl FromError<IoError> for HttpError {
}
}
+impl FromError<url::ParseError> for HttpError {
+ fn from_error(err: url::ParseError) -> HttpError {
+ HttpUriError(err)
+ }
+}
+
//FIXME: when Opt-in Built-in Types becomes a thing, we can force these structs
//to be Send. For now, this has the compiler do a static check.
fn _assert_send<T: Send>() {
diff --git a/src/mock.rs b/src/mock.rs
--- a/src/mock.rs
+++ b/src/mock.rs
@@ -73,3 +73,35 @@ impl NetworkConnector<MockStream> for MockConnector {
Ok(MockStream::new())
}
}
+
+/// new connectors must be created if you wish to intercept requests.
+macro_rules! mock_connector (
+ ($name:ident {
+ $($url:expr => $res:expr)*
+ }) => (
+
+ struct $name;
+
+ 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);
+ let mut map = HashMap::new();
+ $(map.insert($url, $res);)*
+
+
+ let key = format!("{}://{}", scheme, host);
+ // ignore port for now
+ match map.find(&&*key) {
+ Some(res) => Ok(::mock::MockStream {
+ write: ::std::io::MemWriter::new(),
+ read: ::std::io::MemReader::new(res.to_string().into_bytes())
+ }),
+ None => panic!("{} doesn't know url {}", stringify!($name), key)
+ }
+ }
+
+ }
+
+ )
+)
diff --git a/src/net.rs b/src/net.rs
--- a/src/net.rs
+++ b/src/net.rs
@@ -11,7 +11,8 @@ use std::mem::{mod, transmute, transmute_copy};
use std::raw::{mod, TraitObject};
use uany::UncheckedBoxAnyDowncast;
-use openssl::ssl::{SslStream, SslContext, Ssl};
+use openssl::ssl::{Ssl, SslStream, SslContext, VerifyCallback};
+use openssl::ssl::SslVerifyMode::SslVerifyPeer;
use openssl::ssl::SslMethod::Sslv23;
use openssl::ssl::error::{SslError, StreamError, OpenSslErrors, SslSessionClosed};
diff --git a/src/net.rs b/src/net.rs
--- a/src/net.rs
+++ b/src/net.rs
@@ -239,7 +240,7 @@ impl NetworkStream for HttpStream {
/// A connector that will produce HttpStreams.
#[allow(missing_copy_implementations)]
-pub struct HttpConnector;
+pub struct HttpConnector(pub Option<VerifyCallback>);
impl NetworkConnector<HttpStream> for HttpConnector {
fn connect(&mut self, host: &str, port: Port, scheme: &str) -> IoResult<HttpStream> {
diff --git a/src/net.rs b/src/net.rs
--- a/src/net.rs
+++ b/src/net.rs
@@ -252,12 +253,11 @@ impl NetworkConnector<HttpStream> for HttpConnector {
"https" => {
debug!("https scheme");
let stream = try!(TcpStream::connect(addr));
- let context = try!(SslContext::new(Sslv23).map_err(lift_ssl_error));
+ let mut context = try!(SslContext::new(Sslv23).map_err(lift_ssl_error));
+ self.0.as_ref().map(|cb| context.set_verify(SslVerifyPeer, Some(*cb)));
let ssl = try!(Ssl::new(&context).map_err(lift_ssl_error));
- debug!("ssl set_hostname = {}", host);
try!(ssl.set_hostname(host).map_err(lift_ssl_error));
- debug!("ssl set_hostname done");
- let stream = try!(SslStream::new_from(ssl, stream).map_err(lift_ssl_error));
+ let stream = try!(SslStream::new(&context, stream).map_err(lift_ssl_error));
Ok(Https(stream))
},
_ => {
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -105,8 +105,8 @@ impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L
};
keep_alive = match (req.version, req.headers.get::<Connection>()) {
- (Http10, Some(conn)) if !conn.0.contains(&KeepAlive) => false,
- (Http11, Some(conn)) if conn.0.contains(&Close) => false,
+ (Http10, Some(conn)) if !conn.contains(&KeepAlive) => false,
+ (Http11, Some(conn)) if conn.contains(&Close) => false,
_ => true
};
res.version = req.version;
|
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -64,22 +64,20 @@ fn main() {
[Client Bench:](./benches/client.rs)
```
-
running 3 tests
-test bench_curl ... bench: 298416 ns/iter (+/- 132455)
-test bench_http ... bench: 292725 ns/iter (+/- 167575)
-test bench_hyper ... bench: 222819 ns/iter (+/- 86615)
+test bench_curl ... bench: 400253 ns/iter (+/- 143539)
+test bench_hyper ... bench: 181703 ns/iter (+/- 46529)
-test result: ok. 0 passed; 0 failed; 0 ignored; 3 measured
+test result: ok. 0 passed; 0 failed; 0 ignored; 2 measured
```
[Mock Client Bench:](./benches/client_mock_tcp.rs)
```
running 3 tests
-test bench_mock_curl ... bench: 25254 ns/iter (+/- 2113)
-test bench_mock_http ... bench: 43585 ns/iter (+/- 1206)
-test bench_mock_hyper ... bench: 27153 ns/iter (+/- 2227)
+test bench_mock_curl ... bench: 53987 ns/iter (+/- 1735)
+test bench_mock_http ... bench: 43569 ns/iter (+/- 1409)
+test bench_mock_hyper ... bench: 20996 ns/iter (+/- 1742)
test result: ok. 0 passed; 0 failed; 0 ignored; 3 measured
```
diff --git a/benches/client.rs b/benches/client.rs
--- a/benches/client.rs
+++ b/benches/client.rs
@@ -8,6 +8,10 @@ extern crate test;
use std::fmt::{mod, Show};
use std::io::net::ip::Ipv4Addr;
use hyper::server::{Request, Response, Server};
+use hyper::method::Method::Get;
+use hyper::header::Headers;
+use hyper::Client;
+use hyper::client::RequestBuilder;
fn listen() -> hyper::server::Listening {
let server = Server::http(Ipv4Addr(127, 0, 0, 1), 0);
diff --git a/benches/client.rs b/benches/client.rs
--- a/benches/client.rs
+++ b/benches/client.rs
@@ -41,7 +46,7 @@ fn bench_curl(b: &mut test::Bencher) {
.exec()
.unwrap()
});
- listening.close().unwrap()
+ listening.close().unwrap();
}
#[deriving(Clone)]
diff --git a/benches/client.rs b/benches/client.rs
--- a/benches/client.rs
+++ b/benches/client.rs
@@ -67,17 +72,17 @@ fn bench_hyper(b: &mut test::Bencher) {
let mut listening = listen();
let s = format!("http://{}/", listening.socket);
let url = s.as_slice();
+ let mut client = Client::new();
+ let mut headers = Headers::new();
+ headers.set(Foo);
b.iter(|| {
- let mut req = hyper::client::Request::get(hyper::Url::parse(url).unwrap()).unwrap();
- req.headers_mut().set(Foo);
-
- req.start().unwrap()
- .send().unwrap()
- .read_to_string().unwrap()
+ client.get(url).header(Foo).send().unwrap().read_to_string().unwrap();
});
listening.close().unwrap()
}
+/*
+doesn't handle keep-alive properly...
#[bench]
fn bench_http(b: &mut test::Bencher) {
let mut listening = listen();
diff --git a/benches/client.rs b/benches/client.rs
--- a/benches/client.rs
+++ b/benches/client.rs
@@ -92,9 +97,10 @@ fn bench_http(b: &mut test::Bencher) {
// cant unwrap because Err contains RequestWriter, which does not implement Show
let mut res = match req.read_response() {
Ok(res) => res,
- Err(..) => panic!("http response failed")
+ Err((_, ioe)) => panic!("http response failed = {}", ioe)
};
res.read_to_string().unwrap();
});
listening.close().unwrap()
}
+*/
diff --git a/benches/server.rs b/benches/server.rs
--- a/benches/server.rs
+++ b/benches/server.rs
@@ -9,12 +9,13 @@ use test::Bencher;
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use http::server::Server;
+use hyper::method::Method::Get;
use hyper::server::{Request, Response};
static PHRASE: &'static [u8] = b"Benchmarking hyper vs others!";
fn request(url: hyper::Url) {
- let req = hyper::client::Request::get(url).unwrap();
+ let req = hyper::client::Request::new(Get, url).unwrap();
req.start().unwrap().send().unwrap().read_to_string().unwrap();
}
diff --git a/src/client/mod.rs b/src/client/mod.rs
--- a/src/client/mod.rs
+++ b/src/client/mod.rs
@@ -1,7 +1,399 @@
//! HTTP Client
+//!
+//! # Usage
+//!
+//! The `Client` API is designed for most people to make HTTP requests.
+//! It utilizes the lower level `Request` API.
+//!
+//! ```no_run
+//! use hyper::Client;
+//!
+//! let mut client = Client::new();
+//!
+//! let mut res = client.get("http://example.domain").send().unwrap();
+//! assert_eq!(res.status, hyper::Ok);
+//! ```
+//!
+//! The returned value from is a `Response`, which provides easy access
+//! to the `status`, the `headers`, and the response body via the `Writer`
+//! trait.
+use std::default::Default;
+use std::io::IoResult;
+use std::io::util::copy;
+use std::iter::Extend;
+
+use url::UrlParser;
+use url::ParseError as UrlError;
+
+use openssl::ssl::VerifyCallback;
+
+use header::{Headers, Header, HeaderFormat};
+use header::common::{ContentLength, Location};
+use method::Method;
+use net::{NetworkConnector, NetworkStream, HttpConnector};
+use status::StatusClass::Redirection;
+use {Url, Port, HttpResult};
+use HttpError::HttpUriError;
+
pub use self::request::Request;
pub use self::response::Response;
pub mod request;
pub mod response;
+/// A Client to use additional features with Requests.
+///
+/// Clients can handle things such as: redirect policy.
+pub struct Client<C> {
+ connector: C,
+ redirect_policy: RedirectPolicy,
+}
+
+impl Client<HttpConnector> {
+
+ /// Create a new Client.
+ pub fn new() -> Client<HttpConnector> {
+ Client::with_connector(HttpConnector(None))
+ }
+
+ /// Set the SSL verifier callback for use with OpenSSL.
+ pub fn set_ssl_verifier(&mut self, verifier: VerifyCallback) {
+ self.connector = HttpConnector(Some(verifier));
+ }
+
+}
+
+impl<C: NetworkConnector<S>, S: NetworkStream> Client<C> {
+
+ /// Create a new client with a specific connector.
+ pub fn with_connector(connector: C) -> Client<C> {
+ Client {
+ connector: connector,
+ redirect_policy: Default::default()
+ }
+ }
+
+ /// Set the RedirectPolicy.
+ pub fn set_redirect_policy(&mut self, policy: RedirectPolicy) {
+ self.redirect_policy = policy;
+ }
+
+ /// Execute a Get request.
+ pub fn get<U: IntoUrl>(&mut self, url: U) -> RequestBuilder<U, C, S> {
+ self.request(Method::Get, url)
+ }
+
+ /// Execute a Head request.
+ pub fn head<U: IntoUrl>(&mut self, url: U) -> RequestBuilder<U, C, S> {
+ self.request(Method::Head, url)
+ }
+
+ /// Execute a Post request.
+ pub fn post<U: IntoUrl>(&mut self, url: U) -> RequestBuilder<U, C, S> {
+ self.request(Method::Post, url)
+ }
+
+ /// Execute a Put request.
+ pub fn put<U: IntoUrl>(&mut self, url: U) -> RequestBuilder<U, C, S> {
+ self.request(Method::Put, url)
+ }
+
+ /// Execute a Delete request.
+ pub fn delete<U: IntoUrl>(&mut self, url: U) -> RequestBuilder<U, C, S> {
+ self.request(Method::Delete, url)
+ }
+
+
+ /// Build a new request using this Client.
+ pub fn request<U: IntoUrl>(&mut self, method: Method, url: U) -> RequestBuilder<U, C, S> {
+ RequestBuilder {
+ client: self,
+ method: method,
+ url: url,
+ body: None,
+ headers: None,
+ }
+ }
+}
+
+/// Options for an individual Request.
+///
+/// One of these will be built for you if you use one of the convenience
+/// methods, such as `get()`, `post()`, etc.
+pub struct RequestBuilder<'a, U: IntoUrl, C: NetworkConnector<S> + 'a, S: NetworkStream> {
+ client: &'a mut Client<C>,
+ url: U,
+ headers: Option<Headers>,
+ method: Method,
+ body: Option<Body<'a>>,
+}
+
+impl<'a, U: IntoUrl, C: NetworkConnector<S>, S: NetworkStream> RequestBuilder<'a, U, C, S> {
+
+ /// Set a request body to be sent.
+ pub fn body<B: IntoBody<'a>>(mut self, body: B) -> RequestBuilder<'a, U, C, S> {
+ self.body = Some(body.into_body());
+ self
+ }
+
+ /// Add additional headers to the request.
+ pub fn headers(mut self, headers: Headers) -> RequestBuilder<'a, U, C, S> {
+ self.headers = Some(headers);
+ self
+ }
+
+ /// Add an individual new header to the request.
+ pub fn header<H: Header + HeaderFormat>(mut self, header: H) -> RequestBuilder<'a, U, C, S> {
+ {
+ let mut headers = match self.headers {
+ Some(ref mut h) => h,
+ None => {
+ self.headers = Some(Headers::new());
+ self.headers.as_mut().unwrap()
+ }
+ };
+
+ headers.set(header);
+ }
+ self
+ }
+
+ /// Execute this request and receive a Response back.
+ pub fn send(self) -> HttpResult<Response> {
+ let RequestBuilder { client, method, url, headers, body } = self;
+ let mut url = try!(url.into_url());
+ debug!("client.request {} {}", method, url);
+
+ let can_have_body = match &method {
+ &Method::Get | &Method::Head => false,
+ _ => true
+ };
+
+ let mut body = if can_have_body {
+ body.map(|b| b.into_body())
+ } else {
+ None
+ };
+
+ loop {
+ let mut req = try!(Request::with_connector(method.clone(), url.clone(), &mut client.connector));
+ headers.as_ref().map(|headers| req.headers_mut().extend(headers.iter()));
+
+ match (can_have_body, body.as_ref()) {
+ (true, Some(ref body)) => match body.size() {
+ Some(size) => req.headers_mut().set(ContentLength(size)),
+ None => (), // chunked, Request will add it automatically
+ },
+ (true, None) => req.headers_mut().set(ContentLength(0)),
+ _ => () // neither
+ }
+ let mut streaming = try!(req.start());
+ body.take().map(|mut rdr| copy(&mut rdr, &mut streaming));
+ let res = try!(streaming.send());
+ if res.status.class() != Redirection {
+ return Ok(res)
+ }
+ debug!("redirect code {} for {}", res.status, url);
+
+ let loc = {
+ // punching borrowck here
+ let loc = match res.headers.get::<Location>() {
+ Some(&Location(ref loc)) => {
+ Some(UrlParser::new().base_url(&url).parse(loc[]))
+ }
+ None => {
+ debug!("no Location header");
+ // could be 304 Not Modified?
+ None
+ }
+ };
+ match loc {
+ Some(r) => r,
+ None => return Ok(res)
+ }
+ };
+ url = match loc {
+ Ok(u) => {
+ inspect!("Location", u)
+ },
+ Err(e) => {
+ debug!("Location header had invalid URI: {}", e);
+ return Ok(res);
+ }
+ };
+ match client.redirect_policy {
+ // separate branches because they cant be one
+ RedirectPolicy::FollowAll => (), //continue
+ RedirectPolicy::FollowIf(cond) if cond(&url) => (), //continue
+ _ => return Ok(res),
+ }
+ }
+ }
+}
+
+/// A helper trait to allow overloading of the body parameter.
+pub trait IntoBody<'a> {
+ /// Consumes self into an instance of `Body`.
+ fn into_body(self) -> Body<'a>;
+}
+
+/// The target enum for the IntoBody trait.
+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),
+ /// A String has a size, and uses Content-Length.
+ BufBody(&'a [u8] , uint),
+}
+
+impl<'a> Body<'a> {
+ fn size(&self) -> Option<uint> {
+ match *self {
+ Body::SizedBody(_, len) | Body::BufBody(_, len) => Some(len),
+ _ => None
+ }
+ }
+}
+
+impl<'a> Reader for Body<'a> {
+ #[inline]
+ fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
+ match *self {
+ Body::ChunkedBody(ref mut r) => r.read(buf),
+ Body::SizedBody(ref mut r, _) => r.read(buf),
+ Body::BufBody(ref mut r, _) => r.read(buf),
+ }
+ }
+}
+
+// To allow someone to pass a `Body::SizedBody()` themselves.
+impl<'a> IntoBody<'a> for Body<'a> {
+ #[inline]
+ fn into_body(self) -> Body<'a> {
+ self
+ }
+}
+
+impl<'a> IntoBody<'a> for &'a [u8] {
+ #[inline]
+ fn into_body(self) -> Body<'a> {
+ Body::BufBody(self, self.len())
+ }
+}
+
+impl<'a> IntoBody<'a> for &'a str {
+ #[inline]
+ fn into_body(self) -> Body<'a> {
+ self.as_bytes().into_body()
+ }
+}
+
+impl<'a, R: Reader> IntoBody<'a> for &'a mut R {
+ #[inline]
+ fn into_body(self) -> Body<'a> {
+ Body::ChunkedBody(self)
+ }
+}
+
+/// A helper trait to convert common objects into a Url.
+pub trait IntoUrl {
+ /// Consumes the object, trying to return a Url.
+ fn into_url(self) -> Result<Url, UrlError>;
+}
+
+impl IntoUrl for Url {
+ fn into_url(self) -> Result<Url, UrlError> {
+ Ok(self)
+ }
+}
+
+impl<'a> IntoUrl for &'a str {
+ fn into_url(self) -> Result<Url, UrlError> {
+ Url::parse(self)
+ }
+}
+
+/// Behavior regarding how to handle redirects within a Client.
+#[deriving(Copy, Clone)]
+pub enum RedirectPolicy {
+ /// Don't follow any redirects.
+ FollowNone,
+ /// Follow all redirects.
+ FollowAll,
+ /// Follow a redirect if the contained function returns true.
+ FollowIf(fn(&Url) -> bool),
+}
+
+impl Default for RedirectPolicy {
+ fn default() -> RedirectPolicy {
+ RedirectPolicy::FollowAll
+ }
+}
+
+fn get_host_and_port(url: &Url) -> HttpResult<(String, Port)> {
+ let host = match url.serialize_host() {
+ Some(host) => host,
+ None => return Err(HttpUriError(UrlError::EmptyHost))
+ };
+ debug!("host={}", host);
+ let port = match url.port_or_default() {
+ Some(port) => port,
+ None => return Err(HttpUriError(UrlError::InvalidPort))
+ };
+ debug!("port={}", port);
+ Ok((host, port))
+}
+
+#[cfg(test)]
+mod tests {
+ use header::common::Server;
+ use super::{Client, RedirectPolicy};
+ use url::Url;
+
+ mock_connector!(MockRedirectPolicy {
+ "http://127.0.0.1" => "HTTP/1.1 301 Redirect\r\n\
+ Location: http://127.0.0.2\r\n\
+ Server: mock1\r\n\
+ \r\n\
+ "
+ "http://127.0.0.2" => "HTTP/1.1 302 Found\r\n\
+ Location: https://127.0.0.3\r\n\
+ Server: mock2\r\n\
+ \r\n\
+ "
+ "https://127.0.0.3" => "HTTP/1.1 200 OK\r\n\
+ Server: mock3\r\n\
+ \r\n\
+ "
+ })
+
+ #[test]
+ fn test_redirect_followall() {
+ let mut client = Client::with_connector(MockRedirectPolicy);
+ client.set_redirect_policy(RedirectPolicy::FollowAll);
+
+ let res = client.get("http://127.0.0.1").send().unwrap();
+ assert_eq!(res.headers.get(), Some(&Server("mock3".into_string())));
+ }
+
+ #[test]
+ fn test_redirect_dontfollow() {
+ let mut client = Client::with_connector(MockRedirectPolicy);
+ client.set_redirect_policy(RedirectPolicy::FollowNone);
+ let res = client.get("http://127.0.0.1").send().unwrap();
+ assert_eq!(res.headers.get(), Some(&Server("mock1".into_string())));
+ }
+
+ #[test]
+ fn test_redirect_followif() {
+ fn follow_if(url: &Url) -> bool {
+ !url.serialize()[].contains("127.0.0.3")
+ }
+ let mut client = Client::with_connector(MockRedirectPolicy);
+ client.set_redirect_policy(RedirectPolicy::FollowIf(follow_if));
+ let res = client.get("http://127.0.0.1").send().unwrap();
+ assert_eq!(res.headers.get(), Some(&Server("mock2".into_string())));
+ }
+
+}
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -181,6 +182,10 @@ macro_rules! inspect(
})
)
+#[cfg(test)]
+#[macro_escape]
+mod mock;
+
pub mod client;
pub mod method;
pub mod header;
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -191,7 +196,6 @@ pub mod status;
pub mod uri;
pub mod version;
-#[cfg(test)] mod mock;
mod mimewrapper {
/// Re-exporting the mime crate, for convenience.
|
Helper function `http_get`
In two projects of mine, I've wanted a function with the signature:
`fn http_get(url: String) -> Result<(StatusCode, Vec<u8>), SomeError>`
I could hack this together with methods currently in Hyper, but I think it would provide value to group it together in a helper function.
|
I've been thinking that a Request Builder should be provided, to ease
making simple requests. Something like rust-curl's interface.
I think that the long road for hyper is two or more layers - core hyper, which includes a fast http parser and low-level header and body access and a higher level or levels for both the server and client that provide more advanced features like typed headers and a builder interface.
I'm not entirely sure how I think the lines should be drawn, but I see the need for a core implementation separate from a higher-level interface.
|
2014-12-07T07:37:46Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
hyperium/hyper
| 180
|
hyperium__hyper-180
|
[
"170"
] |
db2a9f40d8462e7c5550d21716f01d1306edc8c5
|
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs
--- a/src/header/common/mod.rs
+++ b/src/header/common/mod.rs
@@ -14,6 +14,7 @@ pub use self::connection::Connection;
pub use self::content_length::ContentLength;
pub use self::content_type::ContentType;
pub use self::date::Date;
+pub use self::etag::Etag;
pub use self::expires::Expires;
pub use self::host::Host;
pub use self::last_modified::LastModified;
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs
--- a/src/header/common/mod.rs
+++ b/src/header/common/mod.rs
@@ -93,6 +94,9 @@ pub mod content_type;
/// Exposes the Date header.
pub mod date;
+/// Exposes the Etag header.
+pub mod etag;
+
/// Exposes the Expires header.
pub mod expires;
|
diff --git /dev/null b/src/header/common/etag.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/etag.rs
@@ -0,0 +1,156 @@
+use header::{Header, HeaderFormat};
+use std::fmt::{mod};
+use super::util::from_one_raw_str;
+
+/// The `Etag` header.
+///
+/// An Etag consists of a string enclosed by two literal double quotes.
+/// 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)]
+pub struct Etag {
+ /// Weakness indicator for the tag
+ pub weak: bool,
+ /// The opaque string in between the DQUOTEs
+ pub tag: String
+}
+
+impl Header for Etag {
+ fn header_name(_: Option<Etag>) -> &'static str {
+ "Etag"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<Etag> {
+ // check that each char in the slice is either:
+ // 1. %x21, or
+ // 2. in the range %x23 to %x7E, or
+ // 3. in the range %x80 to %xFF
+ fn check_slice_validity(slice: &str) -> bool {
+ for c in slice.bytes() {
+ match c {
+ b'\x21' | b'\x23' ... b'\x7e' | b'\x80' ... b'\xff' => (),
+ _ => { return false; }
+ }
+ }
+ true
+ }
+
+
+ from_one_raw_str(raw).and_then(|s: String| {
+ let length: uint = s.len();
+ let slice = s[];
+
+ // Early exits:
+ // 1. The string is empty, or,
+ // 2. it doesn't terminate in a DQUOTE.
+ if slice.is_empty() || !slice.ends_with("\"") {
+ return None;
+ }
+
+ // The etag is weak if its first char is not a DQUOTE.
+ if slice.char_at(0) == '"' {
+ // No need to check if the last char is a DQUOTE,
+ // we already did that above.
+ if check_slice_validity(slice.slice_chars(1, length-1)) {
+ return Some(Etag {
+ weak: false,
+ tag: slice.slice_chars(1, length-1).into_string()
+ });
+ } else {
+ return None;
+ }
+ }
+
+ if slice.slice_chars(0, 3) == "W/\"" {
+ if check_slice_validity(slice.slice_chars(3, length-1)) {
+ return Some(Etag {
+ weak: true,
+ tag: slice.slice_chars(3, length-1).into_string()
+ });
+ } else {
+ return None;
+ }
+ }
+
+ None
+ })
+ }
+}
+
+impl HeaderFormat for Etag {
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ if self.weak {
+ try!(fmt.write(b"W/"));
+ }
+ write!(fmt, "\"{}\"", self.tag)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::Etag;
+ use header::Header;
+
+ #[test]
+ fn test_etag_successes() {
+ // Expected successes
+ let mut etag: Option<Etag>;
+
+ etag = Header::parse_header([b"\"foobar\"".to_vec()].as_slice());
+ assert_eq!(etag, Some(Etag {
+ weak: false,
+ tag: "foobar".into_string()
+ }));
+
+ etag = Header::parse_header([b"\"\"".to_vec()].as_slice());
+ assert_eq!(etag, Some(Etag {
+ weak: false,
+ tag: "".into_string()
+ }));
+
+ etag = Header::parse_header([b"W/\"weak-etag\"".to_vec()].as_slice());
+ assert_eq!(etag, Some(Etag {
+ weak: true,
+ tag: "weak-etag".into_string()
+ }));
+
+ etag = Header::parse_header([b"W/\"\x65\x62\"".to_vec()].as_slice());
+ assert_eq!(etag, Some(Etag {
+ weak: true,
+ tag: "\u0065\u0062".into_string()
+ }));
+
+ etag = Header::parse_header([b"W/\"\"".to_vec()].as_slice());
+ assert_eq!(etag, Some(Etag {
+ weak: true,
+ tag: "".into_string()
+ }));
+ }
+
+ #[test]
+ fn test_etag_failures() {
+ // Expected failures
+ let mut etag: Option<Etag>;
+
+ etag = Header::parse_header([b"no-dquotes".to_vec()].as_slice());
+ assert_eq!(etag, None);
+
+ etag = Header::parse_header([b"w/\"the-first-w-is-case-sensitive\"".to_vec()].as_slice());
+ assert_eq!(etag, None);
+
+ etag = Header::parse_header([b"".to_vec()].as_slice());
+ assert_eq!(etag, None);
+
+ etag = Header::parse_header([b"\"unmatched-dquotes1".to_vec()].as_slice());
+ assert_eq!(etag, None);
+
+ etag = Header::parse_header([b"unmatched-dquotes2\"".to_vec()].as_slice());
+ assert_eq!(etag, None);
+
+ etag = Header::parse_header([b"matched-\"dquotes\"".to_vec()].as_slice());
+ assert_eq!(etag, None);
+ }
+}
+
+bench_header!(bench, Etag, { vec![b"W/\"nonemptytag\"".to_vec()] })
\ No newline at end of file
|
add Etag Header
See https://tools.ietf.org/html/rfc7232#section-2.3
|
2014-12-05T22:22:45Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
|
hyperium/hyper
| 166
|
hyperium__hyper-166
|
[
"155"
] |
0ccd1acaa198488176b74ac97ae5cfc971d816a5
|
diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs
--- a/src/header/common/cookie.rs
+++ b/src/header/common/cookie.rs
@@ -66,11 +66,17 @@ impl Cookies {
/// to manipulate cookies and create a corresponding `SetCookie` header afterwards.
pub fn to_cookie_jar(&self, key: &[u8]) -> CookieJar<'static> {
let mut jar = CookieJar::new(key);
- for cookie in self.0.iter() {
- jar.add_original((*cookie).clone());
+ for cookie in self.iter() {
+ jar.add_original(cookie.clone());
}
jar
}
+
+ /// Extracts all cookies from `CookieJar` and creates Cookie header.
+ /// Useful for clients.
+ pub fn from_cookie_jar(jar: &CookieJar) -> Cookies {
+ Cookies(jar.iter().collect())
+ }
}
diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs
--- a/src/header/common/set_cookie.rs
+++ b/src/header/common/set_cookie.rs
@@ -63,6 +63,14 @@ impl SetCookie {
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
SetCookie(jar.delta())
}
+
+ /// Use this on client to apply changes from SetCookie to CookieJar.
+ /// Note that this will `panic!` if `CookieJar` is not root.
+ pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
+ for cookie in self.iter() {
+ jar.add_original(cookie.clone())
+ }
+ }
}
|
diff --git a/src/header/common/cookie.rs b/src/header/common/cookie.rs
--- a/src/header/common/cookie.rs
+++ b/src/header/common/cookie.rs
@@ -96,4 +102,15 @@ fn test_fmt() {
assert_eq!(headers.to_string()[], "Cookie: foo=bar; baz=quux\r\n");
}
+#[test]
+fn cookie_jar() {
+ let cookie = Cookie::new("foo".to_string(), "bar".to_string());
+ let cookies = Cookies(vec![cookie]);
+ let jar = cookies.to_cookie_jar(&[]);
+ let new_cookies = Cookies::from_cookie_jar(&jar);
+
+ assert_eq!(cookies, new_cookies);
+}
+
+
bench_header!(bench, Cookies, { vec![b"foo=bar; baz=quux".to_vec()] })
diff --git a/src/header/common/set_cookie.rs b/src/header/common/set_cookie.rs
--- a/src/header/common/set_cookie.rs
+++ b/src/header/common/set_cookie.rs
@@ -88,3 +96,18 @@ fn test_fmt() {
assert_eq!(headers.to_string()[], "Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n");
}
+
+#[test]
+fn cookie_jar() {
+ let jar = CookieJar::new("secret".as_bytes());
+ let cookie = Cookie::new("foo".to_string(), "bar".to_string());
+ jar.encrypted().add(cookie);
+
+ let cookies = SetCookie::from_cookie_jar(&jar);
+
+ let mut new_jar = CookieJar::new("secret".as_bytes());
+ cookies.apply_to_cookie_jar(&mut new_jar);
+
+ assert_eq!(jar.encrypted().find("foo"), new_jar.encrypted().find("foo"));
+ assert_eq!(jar.iter().collect::<Vec<Cookie>>(), new_jar.iter().collect::<Vec<Cookie>>());
+}
|
CookieJar isn't helpful for clients
Currently `Cookies` provides a method to convert to a `CookieJar` and `SetCookies` has a method to be created from a `CookieJar`, which is useful for servers, but clients need methods that do the opposite.
|
@retep998 To be sure, you need:
1. a conversion from CookieJar to Cookies header;
2. a conversion from SetCookie header to CookieJar;
Is it correct?
Yes, a way to turn a `CookieJar` into `Cookies` and a way to apply the changes from `SetCookie` to the `CookieJar`. Those two things would make working with cookies significantly easier.
@retep998 I made a PR alexcrichton/cookie-rs#14. We need this for the first part.
|
2014-12-02T07:40:32Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
hyperium/hyper
| 165
|
hyperium__hyper-165
|
[
"119"
] |
1ed4ea5a279d2b9098a717f2d4b44df0be593669
|
diff --git a/src/header/common/date.rs b/src/header/common/date.rs
--- a/src/header/common/date.rs
+++ b/src/header/common/date.rs
@@ -1,8 +1,8 @@
-use header::{Header, HeaderFormat};
use std::fmt::{mod, Show};
-use super::util::from_one_raw_str;
use std::str::FromStr;
-use time::{Tm, strptime};
+use time::Tm;
+use header::{Header, HeaderFormat};
+use super::util::{from_one_raw_str, tm_from_str};
// Egh, replace as soon as something better than time::Tm exists.
/// The `Date` header field.
diff --git a/src/header/common/date.rs b/src/header/common/date.rs
--- a/src/header/common/date.rs
+++ b/src/header/common/date.rs
@@ -21,17 +21,10 @@ impl Header for Date {
}
}
+
impl HeaderFormat for Date {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- self.fmt(fmt)
- }
-}
-
-impl fmt::Show for Date {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- let Date(ref tm) = *self;
- // bummer that tm.strftime allocates a string. It would nice if it
- // returned a Show instead, since I don't need the String here
+ let tm = **self;
match tm.tm_utcoff {
0 => tm.rfc822().fmt(fmt),
_ => tm.to_utc().rfc822().fmt(fmt)
diff --git a/src/header/common/date.rs b/src/header/common/date.rs
--- a/src/header/common/date.rs
+++ b/src/header/common/date.rs
@@ -40,34 +33,8 @@ impl fmt::Show for Date {
}
impl FromStr for Date {
- // Prior to 1995, there were three different formats commonly used by
- // servers to communicate timestamps. For compatibility with old
- // implementations, all three are defined here. The preferred format is
- // a fixed-length and single-zone subset of the date and time
- // specification used by the Internet Message Format [RFC5322].
- //
- // HTTP-date = IMF-fixdate / obs-date
- //
- // An example of the preferred format is
- //
- // Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate
- //
- // Examples of the two obsolete formats are
- //
- // Sunday, 06-Nov-94 08:49:37 GMT ; obsolete RFC 850 format
- // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
- //
- // A recipient that parses a timestamp value in an HTTP header field
- // MUST accept all three HTTP-date formats. When a sender generates a
- // header field that contains one or more timestamps defined as
- // HTTP-date, the sender MUST generate those timestamps in the
- // IMF-fixdate format.
fn from_str(s: &str) -> Option<Date> {
- strptime(s, "%a, %d %b %Y %T %Z").or_else(|_| {
- strptime(s, "%A, %d-%b-%y %T %Z")
- }).or_else(|_| {
- strptime(s, "%c")
- }).ok().map(|tm| Date(tm))
+ tm_from_str(s).map(Date)
}
}
diff --git /dev/null b/src/header/common/expires.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/expires.rs
@@ -0,0 +1,42 @@
+use std::fmt::{mod, Show};
+use std::str::FromStr;
+use time::Tm;
+use header::{Header, HeaderFormat};
+use super::util::{from_one_raw_str, tm_from_str};
+
+/// The `Expires` header field.
+#[deriving(PartialEq, Clone)]
+pub struct Expires(pub Tm);
+
+deref!(Expires -> Tm)
+
+impl Header for Expires {
+ fn header_name(_: Option<Expires>) -> &'static str {
+ "Expires"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<Expires> {
+ from_one_raw_str(raw)
+ }
+}
+
+
+impl HeaderFormat for Expires {
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ let tm = **self;
+ match tm.tm_utcoff {
+ 0 => tm.rfc822().fmt(fmt),
+ _ => tm.to_utc().rfc822().fmt(fmt)
+ }
+ }
+}
+
+impl FromStr for Expires {
+ fn from_str(s: &str) -> Option<Expires> {
+ tm_from_str(s).map(Expires)
+ }
+}
+
+bench_header!(imf_fixdate, Expires, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] })
+bench_header!(rfc_850, Expires, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] })
+bench_header!(asctime, Expires, { vec![b"Sun Nov 6 08:49:37 1994".to_vec()] })
diff --git /dev/null b/src/header/common/last_modified.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/last_modified.rs
@@ -0,0 +1,42 @@
+use std::fmt::{mod, Show};
+use std::str::FromStr;
+use time::Tm;
+use header::{Header, HeaderFormat};
+use super::util::{from_one_raw_str, tm_from_str};
+
+/// The `LastModified` header field.
+#[deriving(PartialEq, Clone)]
+pub struct LastModified(pub Tm);
+
+deref!(LastModified -> Tm)
+
+impl Header for LastModified {
+ fn header_name(_: Option<LastModified>) -> &'static str {
+ "Last-Modified"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<LastModified> {
+ from_one_raw_str(raw)
+ }
+}
+
+
+impl HeaderFormat for LastModified {
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ let tm = **self;
+ match tm.tm_utcoff {
+ 0 => tm.rfc822().fmt(fmt),
+ _ => tm.to_utc().rfc822().fmt(fmt)
+ }
+ }
+}
+
+impl FromStr for LastModified {
+ fn from_str(s: &str) -> Option<LastModified> {
+ tm_from_str(s).map(LastModified)
+ }
+}
+
+bench_header!(imf_fixdate, LastModified, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] })
+bench_header!(rfc_850, LastModified, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] })
+bench_header!(asctime, LastModified, { vec![b"Sun Nov 6 08:49:37 1994".to_vec()] })
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs
--- a/src/header/common/mod.rs
+++ b/src/header/common/mod.rs
@@ -8,12 +8,15 @@
pub use self::accept::Accept;
pub use self::authorization::Authorization;
+pub use self::cache_control::CacheControl;
pub use self::cookie::Cookies;
pub use self::connection::Connection;
pub use self::content_length::ContentLength;
pub use self::content_type::ContentType;
pub use self::date::Date;
+pub use self::expires::Expires;
pub use self::host::Host;
+pub use self::last_modified::LastModified;
pub use self::location::Location;
pub use self::transfer_encoding::TransferEncoding;
pub use self::upgrade::Upgrade;
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs
--- a/src/header/common/mod.rs
+++ b/src/header/common/mod.rs
@@ -81,6 +84,9 @@ pub mod accept;
/// Exposes the Authorization header.
pub mod authorization;
+/// Exposes the CacheControl header.
+pub mod cache_control;
+
/// Exposes the Cookie header.
pub mod cookie;
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs
--- a/src/header/common/mod.rs
+++ b/src/header/common/mod.rs
@@ -96,9 +102,15 @@ pub mod content_type;
/// Exposes the Date header.
pub mod date;
+/// Exposes the Expires header.
+pub mod expires;
+
/// Exposes the Host header.
pub mod host;
+/// Exposes the LastModified header.
+pub mod last_modified;
+
/// Exposes the Location header.
pub mod location;
diff --git a/src/header/common/transfer_encoding.rs b/src/header/common/transfer_encoding.rs
--- a/src/header/common/transfer_encoding.rs
+++ b/src/header/common/transfer_encoding.rs
@@ -76,14 +76,13 @@ impl Header for TransferEncoding {
}
fn parse_header(raw: &[Vec<u8>]) -> Option<TransferEncoding> {
- from_comma_delimited(raw).map(|vec| TransferEncoding(vec))
+ from_comma_delimited(raw).map(TransferEncoding)
}
}
impl HeaderFormat for TransferEncoding {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- let TransferEncoding(ref parts) = *self;
- fmt_comma_delimited(fmt, parts[])
+ fmt_comma_delimited(fmt, self[])
}
}
diff --git a/src/header/common/util.rs b/src/header/common/util.rs
--- a/src/header/common/util.rs
+++ b/src/header/common/util.rs
@@ -2,6 +2,7 @@
use std::str::{FromStr, from_utf8};
use std::fmt::{mod, Show};
+use time::{Tm, strptime};
/// Reads a single raw string when parsing a header
pub fn from_one_raw_str<T: FromStr>(raw: &[Vec<u8>]) -> Option<T> {
diff --git a/src/header/common/util.rs b/src/header/common/util.rs
--- a/src/header/common/util.rs
+++ b/src/header/common/util.rs
@@ -15,13 +16,19 @@ pub fn from_one_raw_str<T: FromStr>(raw: &[Vec<u8>]) -> Option<T> {
}
}
-/// Reads a comma-delimited raw string into a Vec.
+/// Reads a comma-delimited raw header into a Vec.
+#[inline]
pub fn from_comma_delimited<T: FromStr>(raw: &[Vec<u8>]) -> Option<Vec<T>> {
if raw.len() != 1 {
return None;
}
// we JUST checked that raw.len() == 1, so raw[0] WILL exist.
- match from_utf8(unsafe { raw.as_slice().unsafe_get(0).as_slice() }) {
+ from_one_comma_delimited(unsafe { raw.as_slice().unsafe_get(0).as_slice() })
+}
+
+/// Reads a comma-delimited raw string into a Vec.
+pub fn from_one_comma_delimited<T: FromStr>(raw: &[u8]) -> Option<Vec<T>> {
+ match from_utf8(raw) {
Some(s) => {
Some(s.as_slice()
.split([',', ' '].as_slice())
diff --git a/src/header/common/util.rs b/src/header/common/util.rs
--- a/src/header/common/util.rs
+++ b/src/header/common/util.rs
@@ -43,3 +50,34 @@ pub fn fmt_comma_delimited<T: Show>(fmt: &mut fmt::Formatter, parts: &[T]) -> fm
}
Ok(())
}
+
+/// Get a Tm from HTTP date formats.
+// Prior to 1995, there were three different formats commonly used by
+// servers to communicate timestamps. For compatibility with old
+// implementations, all three are defined here. The preferred format is
+// a fixed-length and single-zone subset of the date and time
+// specification used by the Internet Message Format [RFC5322].
+//
+// HTTP-date = IMF-fixdate / obs-date
+//
+// An example of the preferred format is
+//
+// Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate
+//
+// Examples of the two obsolete formats are
+//
+// Sunday, 06-Nov-94 08:49:37 GMT ; obsolete RFC 850 format
+// Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
+//
+// A recipient that parses a timestamp value in an HTTP header field
+// MUST accept all three HTTP-date formats. When a sender generates a
+// header field that contains one or more timestamps defined as
+// HTTP-date, the sender MUST generate those timestamps in the
+// IMF-fixdate format.
+pub fn tm_from_str(s: &str) -> Option<Tm> {
+ strptime(s, "%a, %d %b %Y %T %Z").or_else(|_| {
+ strptime(s, "%A, %d-%b-%y %T %Z")
+ }).or_else(|_| {
+ strptime(s, "%c")
+ }).ok()
+}
|
diff --git /dev/null b/src/header/common/cache_control.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/cache_control.rs
@@ -0,0 +1,165 @@
+use std::fmt;
+use std::str::FromStr;
+use header::{Header, HeaderFormat};
+use super::util::{from_one_comma_delimited, fmt_comma_delimited};
+
+/// The Cache-Control header.
+#[deriving(PartialEq, Clone, Show)]
+pub struct CacheControl(pub Vec<CacheDirective>);
+
+deref!(CacheControl -> Vec<CacheDirective>)
+
+impl Header for CacheControl {
+ fn header_name(_: Option<CacheControl>) -> &'static str {
+ "Cache-Control"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<CacheControl> {
+ let directives = raw.iter()
+ .filter_map(|line| from_one_comma_delimited(line[]))
+ .collect::<Vec<Vec<CacheDirective>>>()
+ .concat_vec();
+ if directives.len() > 0 {
+ Some(CacheControl(directives))
+ } else {
+ None
+ }
+ }
+}
+
+impl HeaderFormat for CacheControl {
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ fmt_comma_delimited(fmt, self[])
+ }
+}
+
+/// CacheControl contains a list of these directives.
+#[deriving(PartialEq, Clone)]
+pub enum CacheDirective {
+ /// "no-cache"
+ NoCache,
+ /// "no-store"
+ NoStore,
+ /// "no-transform"
+ NoTransform,
+ /// "only-if-cached"
+ OnlyIfCached,
+
+ // request directives
+ /// "max-age=delta"
+ MaxAge(uint),
+ /// "max-stale=delta"
+ MaxStale(uint),
+ /// "min-fresh=delta"
+ MinFresh(uint),
+
+ // response directives
+ /// "must-revalidate"
+ MustRevalidate,
+ /// "public"
+ Public,
+ /// "private"
+ Private,
+ /// "proxy-revalidate"
+ ProxyRevalidate,
+ /// "s-maxage=delta"
+ SMaxAge(uint),
+
+ /// Extension directives. Optionally include an argument.
+ Extension(String, Option<String>)
+}
+
+impl fmt::Show for CacheDirective {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ use self::CacheDirective::*;
+ match *self {
+ NoCache => "no-cache",
+ NoStore => "no-store",
+ NoTransform => "no-transform",
+ OnlyIfCached => "only-if-cached",
+
+ MaxAge(secs) => return write!(f, "max-age={}", secs),
+ MaxStale(secs) => return write!(f, "max-stale={}", secs),
+ MinFresh(secs) => return write!(f, "min-fresh={}", secs),
+
+ MustRevalidate => "must-revalidate",
+ Public => "public",
+ Private => "private",
+ ProxyRevalidate => "proxy-revalidate",
+ SMaxAge(secs) => return write!(f, "s-maxage={}", secs),
+
+ Extension(ref name, None) => name[],
+ Extension(ref name, Some(ref arg)) => return write!(f, "{}={}", name, arg),
+
+ }.fmt(f)
+ }
+}
+
+impl FromStr for CacheDirective {
+ fn from_str(s: &str) -> Option<CacheDirective> {
+ use self::CacheDirective::*;
+ match s {
+ "no-cache" => Some(NoCache),
+ "no-store" => Some(NoStore),
+ "no-transform" => Some(NoTransform),
+ "only-if-cached" => Some(OnlyIfCached),
+ "must-revalidate" => Some(MustRevalidate),
+ "public" => Some(Public),
+ "private" => Some(Private),
+ "proxy-revalidate" => Some(ProxyRevalidate),
+ "" => None,
+ _ => match s.find('=') {
+ Some(idx) if idx+1 < s.len() => match (s[..idx], s[idx+1..].trim_chars('"')) {
+ ("max-age" , secs) => from_str::<uint>(secs).map(MaxAge),
+ ("max-stale", secs) => from_str::<uint>(secs).map(MaxStale),
+ ("min-fresh", secs) => from_str::<uint>(secs).map(MinFresh),
+ ("s-maxage", secs) => from_str::<uint>(secs).map(SMaxAge),
+ (left, right) => Some(Extension(left.into_string(), Some(right.into_string())))
+ },
+ Some(_) => None,
+ None => Some(Extension(s.into_string(), None))
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use header::Header;
+ use super::*;
+
+ #[test]
+ fn test_parse_multiple_headers() {
+ let cache = Header::parse_header(&[b"no-cache".to_vec(), b"private".to_vec()]);
+ assert_eq!(cache, Some(CacheControl(vec![CacheDirective::NoCache,
+ CacheDirective::Private])))
+ }
+
+ #[test]
+ fn test_parse_argument() {
+ let cache = Header::parse_header(&[b"max-age=100, private".to_vec()]);
+ assert_eq!(cache, Some(CacheControl(vec![CacheDirective::MaxAge(100),
+ CacheDirective::Private])))
+ }
+
+ #[test]
+ fn test_parse_quote_form() {
+ let cache = Header::parse_header(&[b"max-age=\"200\"".to_vec()]);
+ assert_eq!(cache, Some(CacheControl(vec![CacheDirective::MaxAge(200)])))
+ }
+
+ #[test]
+ fn test_parse_extension() {
+ let cache = Header::parse_header(&[b"foo, bar=baz".to_vec()]);
+ assert_eq!(cache, Some(CacheControl(vec![CacheDirective::Extension("foo".to_string(), None),
+ CacheDirective::Extension("bar".to_string(), Some("baz".to_string()))])))
+ }
+
+ #[test]
+ fn test_parse_bad_syntax() {
+ let cache: Option<CacheControl> = Header::parse_header(&[b"foo=".to_vec()]);
+ assert_eq!(cache, None)
+ }
+}
+
+bench_header!(normal, CacheControl, { vec![b"no-cache, private".to_vec(), b"max-age=100".to_vec()] })
|
Add CacheControl header
It's valid to receive multiple `Cache-Control` headers, so this should parse:
```
Cache-Control: no-cache, max-age=0
Cache-Control: no-store
```
into:
```
CacheControl(vec![NoCache, NoStore, MaxAge(0)])
```
/cc @jdm
|
Just to be clear, the support for this only needs to come in the parse_header implementation for CacheControl, right? We already support multiple raw header lines.
Also is this a `servo` issue?
Yes, servo wants it.
Also yes, it's just a reminder that `parse_header` cannot ignore multiple lines, like many other headers can.
|
2014-12-02T05:04:50Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
hyperium/hyper
| 153
|
hyperium__hyper-153
|
[
"152"
] |
ba758ecde10849298de7660cafd360e3ad662628
|
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -187,7 +187,7 @@ impl Request<Streaming> {
///
/// Consumes the Request.
pub fn send(self) -> HttpResult<Response> {
- let raw = try!(self.body.end()).unwrap();
+ let raw = try!(self.body.end()).into_inner();
Response::new(raw)
}
}
diff --git a/src/client/response.rs b/src/client/response.rs
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -80,9 +80,9 @@ impl Response {
&self.status_raw
}
- /// Unwraps the Request to return the NetworkStream underneath.
- pub fn unwrap(self) -> Box<NetworkStream + Send> {
- self.body.unwrap().unwrap()
+ /// Consumes the Request to return the NetworkStream underneath.
+ pub fn into_inner(self) -> Box<NetworkStream + Send> {
+ self.body.unwrap().into_inner()
}
}
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -6,10 +6,11 @@
//! are already provided, such as `Host`, `ContentType`, `UserAgent`, and others.
use std::any::Any;
use std::ascii::{AsciiExt, AsciiCast};
+use std::borrow::{Borrowed, Owned};
use std::fmt::{mod, Show};
use std::intrinsics::TypeId;
use std::raw::TraitObject;
-use std::str::{SendStr, Slice, Owned};
+use std::str::SendStr;
use std::collections::HashMap;
use std::collections::hash_map::{Entries, Occupied, Vacant};
use std::sync::RWLock;
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -95,7 +96,7 @@ fn header_name<T: Header>() -> &'static str {
/// A map of header fields on requests and responses.
#[deriving(Clone)]
pub struct Headers {
- data: HashMap<CaseInsensitive<SendStr>, RWLock<Item>>
+ data: HashMap<CaseInsensitive, RWLock<Item>>
}
impl Headers {
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -136,7 +137,7 @@ impl Headers {
///
/// The field is determined by the type of the value being set.
pub fn set<H: Header + HeaderFormat>(&mut self, value: H) {
- self.data.insert(CaseInsensitive(Slice(header_name::<H>())),
+ self.data.insert(CaseInsensitive(Borrowed(header_name::<H>())),
RWLock::new(Item::typed(box value as Box<HeaderFormat + Send + Sync>)));
}
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -154,7 +155,7 @@ impl Headers {
pub fn get_raw(&self, name: &str) -> Option<&[Vec<u8>]> {
self.data
// FIXME(reem): Find a better way to do this lookup without find_equiv.
- .get(&CaseInsensitive(Slice(unsafe { mem::transmute::<&str, &str>(name) })))
+ .get(&CaseInsensitive(Borrowed(unsafe { mem::transmute::<&str, &str>(name) })))
.and_then(|item| {
let lock = item.read();
if let Some(ref raw) = lock.raw {
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -177,8 +178,8 @@ impl Headers {
/// # let mut headers = Headers::new();
/// headers.set_raw("content-length", vec!["5".as_bytes().to_vec()]);
/// ```
- pub fn set_raw<K: IntoMaybeOwned<'static>>(&mut self, name: K, value: Vec<Vec<u8>>) {
- self.data.insert(CaseInsensitive(name.into_maybe_owned()), RWLock::new(Item::raw(value)));
+ pub fn set_raw<K: IntoCow<'static, String, str>>(&mut self, name: K, value: Vec<Vec<u8>>) {
+ self.data.insert(CaseInsensitive(name.into_cow()), RWLock::new(Item::raw(value)));
}
/// Get a reference to the header field's value, if it exists.
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -200,7 +201,7 @@ impl Headers {
}
fn get_or_parse<H: Header + HeaderFormat>(&self) -> Option<&RWLock<Item>> {
- self.data.get(&CaseInsensitive(Slice(header_name::<H>()))).and_then(|item| get_or_parse::<H>(item))
+ self.data.get(&CaseInsensitive(Borrowed(header_name::<H>()))).and_then(|item| get_or_parse::<H>(item))
}
/// Returns a boolean of whether a certain header is in the map.
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -214,13 +215,13 @@ impl Headers {
/// let has_type = headers.has::<ContentType>();
/// ```
pub fn has<H: Header + HeaderFormat>(&self) -> bool {
- self.data.contains_key(&CaseInsensitive(Slice(header_name::<H>())))
+ self.data.contains_key(&CaseInsensitive(Borrowed(header_name::<H>())))
}
/// Removes a header from the map, if one existed.
/// Returns true if a header has been removed.
pub fn remove<H: Header + HeaderFormat>(&mut self) -> bool {
- self.data.remove(&CaseInsensitive(Slice(Header::header_name(None::<H>)))).is_some()
+ self.data.remove(&CaseInsensitive(Borrowed(Header::header_name(None::<H>)))).is_some()
}
/// Returns an iterator over the header fields.
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -252,7 +253,7 @@ impl fmt::Show for Headers {
/// An `Iterator` over the fields in a `Headers` map.
pub struct HeadersItems<'a> {
- inner: Entries<'a, CaseInsensitive<SendStr>, RWLock<Item>>
+ inner: Entries<'a, CaseInsensitive, RWLock<Item>>
}
impl<'a> Iterator<HeaderView<'a>> for HeadersItems<'a> {
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -265,13 +266,13 @@ impl<'a> Iterator<HeaderView<'a>> for HeadersItems<'a> {
}
/// Returned with the `HeadersItems` iterator.
-pub struct HeaderView<'a>(&'a CaseInsensitive<SendStr>, &'a RWLock<Item>);
+pub struct HeaderView<'a>(&'a CaseInsensitive, &'a RWLock<Item>);
impl<'a> HeaderView<'a> {
/// Check if a HeaderView is a certain Header.
#[inline]
pub fn is<H: Header>(&self) -> bool {
- CaseInsensitive(header_name::<H>().into_maybe_owned()) == *self.0
+ CaseInsensitive(header_name::<H>().into_cow()) == *self.0
}
/// Get the Header name as a slice.
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -432,10 +433,16 @@ impl fmt::Show for Box<HeaderFormat + Send + Sync> {
}
}
-#[deriving(Clone)]
-struct CaseInsensitive<S: Str>(S);
+//#[deriving(Clone)]
+struct CaseInsensitive(SendStr);
+
+impl Clone for CaseInsensitive {
+ fn clone(&self) -> CaseInsensitive {
+ CaseInsensitive((*self.0).clone().into_cow())
+ }
+}
-impl<S: Str> Str for CaseInsensitive<S> {
+impl Str for CaseInsensitive {
fn as_slice(&self) -> &str {
let CaseInsensitive(ref s) = *self;
s.as_slice()
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -443,29 +450,27 @@ impl<S: Str> Str for CaseInsensitive<S> {
}
-impl<S: Str> fmt::Show for CaseInsensitive<S> {
+impl fmt::Show for CaseInsensitive {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
self.as_slice().fmt(fmt)
}
}
-impl<S: Str> PartialEq for CaseInsensitive<S> {
- fn eq(&self, other: &CaseInsensitive<S>) -> bool {
+impl PartialEq for CaseInsensitive {
+ fn eq(&self, other: &CaseInsensitive) -> bool {
self.as_slice().eq_ignore_ascii_case(other.as_slice())
}
}
-impl<S: Str> Eq for CaseInsensitive<S> {}
+impl Eq for CaseInsensitive {}
-impl<S: Str, S2: Str> Equiv<CaseInsensitive<S2>> for CaseInsensitive<S> {
- fn equiv(&self, other: &CaseInsensitive<S2>) -> bool {
- let left = CaseInsensitive(self.as_slice());
- let right = CaseInsensitive(other.as_slice());
- left == right
+impl Equiv<CaseInsensitive> for CaseInsensitive {
+ fn equiv(&self, other: &CaseInsensitive) -> bool {
+ self == other
}
}
-impl<S: Str, H: hash::Writer> hash::Hash<H> for CaseInsensitive<S> {
+impl<H: hash::Writer> hash::Hash<H> for CaseInsensitive {
#[inline]
fn hash(&self, hasher: &mut H) {
for b in self.as_slice().bytes() {
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -1,9 +1,10 @@
//! Pieces pertaining to the HTTP message protocol.
+use std::borrow::{Borrowed, Owned};
use std::cmp::min;
use std::fmt;
use std::io::{mod, Reader, IoResult, BufWriter};
use std::num::from_u16;
-use std::str::{mod, SendStr, Slice, Owned};
+use std::str::{mod, SendStr};
use url::Url;
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -559,9 +560,15 @@ pub fn read_request_line<R: Reader>(stream: &mut R) -> HttpResult<RequestLine> {
pub type StatusLine = (HttpVersion, RawStatus);
/// The raw status code and reason-phrase.
-#[deriving(PartialEq, Show, Clone)]
+#[deriving(PartialEq, Show)]
pub struct RawStatus(pub u16, pub SendStr);
+impl Clone for RawStatus {
+ fn clone(&self) -> RawStatus {
+ RawStatus(self.0, (*self.1).clone().into_cow())
+ }
+}
+
/// Read the StatusLine, such as `HTTP/1.1 200 OK`.
///
/// > The first line of a response message is the status-line, consisting
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -632,7 +639,7 @@ pub fn read_status<R: Reader>(stream: &mut R) -> HttpResult<RawStatus> {
Some(status) => match status.canonical_reason() {
Some(phrase) => {
if phrase == reason {
- Slice(phrase)
+ Borrowed(phrase)
} else {
Owned(reason.into_string())
}
|
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -219,8 +219,8 @@ mod tests {
Get, Url::parse("http://example.dom").unwrap()
).unwrap();
let req = req.start().unwrap();
- let stream = *req.body.end().unwrap().unwrap().downcast::<MockStream>().unwrap();
- let bytes = stream.write.unwrap();
+ let stream = *req.body.end().unwrap().into_inner().downcast::<MockStream>().unwrap();
+ let bytes = stream.write.into_inner();
let s = from_utf8(bytes[]).unwrap();
assert!(!s.contains("Content-Length:"));
assert!(!s.contains("Transfer-Encoding:"));
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -232,8 +232,8 @@ mod tests {
Head, Url::parse("http://example.dom").unwrap()
).unwrap();
let req = req.start().unwrap();
- let stream = *req.body.end().unwrap().unwrap().downcast::<MockStream>().unwrap();
- let bytes = stream.write.unwrap();
+ let stream = *req.body.end().unwrap().into_inner().downcast::<MockStream>().unwrap();
+ let bytes = stream.write.into_inner();
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
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -95,9 +95,9 @@ impl Reader for Response {
#[cfg(test)]
mod tests {
+ use std::borrow::Borrowed;
use std::boxed::BoxAny;
use std::io::BufferedReader;
- use std::str::Slice;
use header::Headers;
use http::HttpReader::EofReader;
diff --git a/src/client/response.rs b/src/client/response.rs
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -117,10 +117,10 @@ mod tests {
headers: Headers::new(),
version: version::HttpVersion::Http11,
body: EofReader(BufferedReader::new(box MockStream::new() as Box<NetworkStream + Send>)),
- status_raw: RawStatus(200, Slice("OK"))
+ status_raw: RawStatus(200, Borrowed("OK"))
};
- let b = res.unwrap().downcast::<MockStream>().unwrap();
+ let b = res.into_inner().downcast::<MockStream>().unwrap();
assert_eq!(b, box MockStream::new());
}
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -491,7 +496,7 @@ impl<H: HeaderFormat> Show for HeaderFormatter<H> {
mod tests {
use std::io::MemReader;
use std::fmt;
- use std::str::Slice;
+ use std::borrow::Borrowed;
use std::hash::sip::hash;
use mime::{Mime, Text, Plain};
use super::CaseInsensitive;
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -506,8 +511,8 @@ mod tests {
#[test]
fn test_case_insensitive() {
- let a = CaseInsensitive(Slice("foobar"));
- let b = CaseInsensitive(Slice("FOOBAR"));
+ let a = CaseInsensitive(Borrowed("foobar"));
+ let b = CaseInsensitive(Borrowed("FOOBAR"));
assert_eq!(a, b);
assert_eq!(hash(&a), hash(&b));
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -657,7 +664,7 @@ fn expect(r: IoResult<u8>, expected: u8) -> HttpResult<()> {
#[cfg(test)]
mod tests {
use std::io::{mod, MemReader, MemWriter};
- use std::str::{Slice, Owned};
+ use std::borrow::{Borrowed, Owned};
use test::Bencher;
use uri::RequestUri;
use uri::RequestUri::{Star, AbsoluteUri, AbsolutePath, Authority};
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -727,8 +734,8 @@ mod tests {
assert_eq!(read_status(&mut mem(s)), result);
}
- read("200 OK\r\n", Ok(RawStatus(200, Slice("OK"))));
- read("404 Not Found\r\n", Ok(RawStatus(404, Slice("Not Found"))));
+ read("200 OK\r\n", Ok(RawStatus(200, Borrowed("OK"))));
+ read("404 Not Found\r\n", Ok(RawStatus(404, Borrowed("Not Found"))));
read("200 crazy pants\r\n", Ok(RawStatus(200, Owned("crazy pants".to_string()))));
}
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -748,7 +755,7 @@ mod tests {
let mut w = super::HttpWriter::ChunkedWriter(MemWriter::new());
w.write(b"foo bar").unwrap();
w.write(b"baz quux herp").unwrap();
- let buf = w.end().unwrap().unwrap();
+ let buf = w.end().unwrap().into_inner();
let s = from_utf8(buf.as_slice()).unwrap();
assert_eq!(s, "7\r\nfoo bar\r\nD\r\nbaz quux herp\r\n0\r\n\r\n");
}
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -760,7 +767,7 @@ mod tests {
w.write(b"foo bar").unwrap();
assert_eq!(w.write(b"baz"), Err(io::standard_error(io::ShortWrite(1))));
- let buf = w.end().unwrap().unwrap();
+ let buf = w.end().unwrap().into_inner();
let s = from_utf8(buf.as_slice()).unwrap();
assert_eq!(s, "foo barb");
}
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -774,7 +781,7 @@ mod tests {
#[bench]
fn bench_read_status(b: &mut Bencher) {
b.bytes = b"404 Not Found\r\n".len() as u64;
- b.iter(|| assert_eq!(read_status(&mut mem("404 Not Found\r\n")), Ok(RawStatus(404, Slice("Not Found")))));
+ b.iter(|| assert_eq!(read_status(&mut mem("404 Not Found\r\n")), Ok(RawStatus(404, Borrowed("Not Found")))));
}
}
|
Fix unwrap() => into_inner()
This pr also renames Response.unwrap() into Response.into_inner() to match new conventions.
|
2014-11-27T20:04:06Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
|
hyperium/hyper
| 113
|
hyperium__hyper-113
|
[
"112"
] |
d5982378d140891f5ac15143801ea0d0513808dd
|
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -16,9 +16,6 @@ git = "https://github.com/hyperium/mime.rs"
[dependencies.unsafe-any]
git = "https://github.com/reem/rust-unsafe-any"
-[dependencies.intertwine]
-git = "https://github.com/reem/rust-intertwine"
-
[dependencies.move-acceptor]
git = "https://github.com/reem/rust-move-acceptor"
diff --git a/benches/server.rs b/benches/server.rs
--- a/benches/server.rs
+++ b/benches/server.rs
@@ -31,7 +31,7 @@ fn bench_hyper(b: &mut Bencher) {
let server = hyper::Server::http(Ipv4Addr(127, 0, 0, 1), 0);
let mut listener = server.listen(hyper_handle).unwrap();
- let url = hyper::Url::parse(format!("http://{}", listener.sockets[0]).as_slice()).unwrap();
+ let url = hyper::Url::parse(format!("http://{}", listener.socket).as_slice()).unwrap();
b.iter(|| request(url.clone()));
listener.close().unwrap();
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -1,10 +1,9 @@
//! HTTP Server
-use std::io::{Listener, IoResult, EndOfFile};
+use std::io::{Listener, EndOfFile};
use std::io::net::ip::{IpAddr, Port, SocketAddr};
use std::task::TaskBuilder;
-use intertwine::{Intertwine, Intertwined};
-use macceptor::MoveAcceptor;
+use macceptor::{MoveAcceptor, MoveConnections};
pub use self::request::Request;
pub use self::response::Response;
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -22,7 +21,8 @@ pub mod response;
/// Once listening, it will create a `Request`/`Response` pair for each
/// incoming connection, and hand them to the provided handler.
pub struct Server<L = HttpListener> {
- pairs: Vec<(IpAddr, Port)>
+ ip: IpAddr,
+ port: Port
}
macro_rules! try_option(
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -37,12 +37,10 @@ macro_rules! try_option(
impl Server<HttpListener> {
/// Creates a new server that will handle `HttpStream`s.
pub fn http(ip: IpAddr, port: Port) -> Server {
- Server { pairs: vec![(ip, port)] }
- }
-
- /// Creates a server that can listen to many (ip, port) pairs.
- pub fn many(pairs: Vec<(IpAddr, Port)>) -> Server {
- Server { pairs: pairs }
+ Server {
+ ip: ip,
+ port: port
+ }
}
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -56,30 +54,21 @@ impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L
S: NetworkStream,
A: NetworkAcceptor<S>,
L: NetworkListener<S, A>, {
- let mut acceptors = Vec::new();
- let mut sockets = Vec::new();
- for (ip, port) in self.pairs.into_iter() {
- debug!("binding to {}:{}", ip, port);
- let mut listener: L = try_io!(NetworkListener::<S, A>::bind((ip, port)));
+ debug!("binding to {}:{}", self.ip, self.port);
+ let mut listener: L = try_io!(NetworkListener::<S, A>::bind((self.ip, self.port)));
- sockets.push(try_io!(listener.socket_name()));
+ let socket = try_io!(listener.socket_name());
- let acceptor = try_io!(listener.listen());
- acceptors.push(acceptor.clone());
- }
-
- let connections = acceptors.clone()
- .into_iter()
- .map(|acceptor| acceptor.move_incoming())
- .intertwine();
+ let acceptor = try_io!(listener.listen());
+ let captured = acceptor.clone();
TaskBuilder::new().named("hyper acceptor").spawn(proc() {
- handler.handle(Incoming { from: connections });
+ handler.handle(Incoming { from: captured.move_incoming() });
});
Ok(Listening {
- acceptors: acceptors,
- sockets: sockets,
+ acceptor: acceptor,
+ socket: socket,
})
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -90,11 +79,11 @@ impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L
}
/// An iterator over incoming `Connection`s.
-pub struct Incoming<S: Send = HttpStream> {
- from: Intertwined<IoResult<S>>
+pub struct Incoming<A = HttpAcceptor> {
+ from: MoveConnections<A>
}
-impl<S: NetworkStream + 'static> Iterator<Connection<S>> for Incoming<S> {
+impl<S: NetworkStream + 'static, A: NetworkAcceptor<S>> Iterator<Connection<S>> for Incoming<A> {
fn next(&mut self) -> Option<Connection<S>> {
for conn in self.from {
match conn {
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -130,9 +119,9 @@ impl<S: NetworkStream + 'static> Connection<S> {
/// A listening server, which can later be closed.
pub struct Listening<A = HttpAcceptor> {
- acceptors: Vec<A>,
+ acceptor: A,
/// The socket addresses that the server is bound to.
- pub sockets: Vec<SocketAddr>,
+ pub socket: SocketAddr,
}
impl<A: NetworkAcceptor<S>, S: NetworkStream> Listening<A> {
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -142,9 +131,7 @@ impl<A: NetworkAcceptor<S>, S: NetworkStream> Listening<A> {
/// and does not close the rest of the acceptors.
pub fn close(&mut self) -> HttpResult<()> {
debug!("closing server");
- for acceptor in self.acceptors.iter_mut() {
- try_io!(acceptor.close());
- }
+ try_io!(self.acceptor.close());
Ok(())
}
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -154,11 +141,11 @@ pub trait Handler<A: NetworkAcceptor<S>, S: NetworkStream>: Send {
/// Receives a `Request`/`Response` pair, and should perform some action on them.
///
/// This could reading from the request, and writing to the response.
- fn handle(self, Incoming<S>);
+ fn handle(self, Incoming<A>);
}
-impl<A: NetworkAcceptor<S>, S: NetworkStream> Handler<A, S> for fn(Incoming<S>) {
- fn handle(self, incoming: Incoming<S>) {
+impl<A: NetworkAcceptor<S>, S: NetworkStream> Handler<A, S> for fn(Incoming<A>) {
+ fn handle(self, incoming: Incoming<A>) {
(self)(incoming)
}
}
|
diff --git a/benches/client.rs b/benches/client.rs
--- a/benches/client.rs
+++ b/benches/client.rs
@@ -35,7 +35,7 @@ fn handle(mut incoming: Incoming) {
#[bench]
fn bench_curl(b: &mut test::Bencher) {
let mut listening = listen();
- let s = format!("http://{}/", listening.sockets[0]);
+ let s = format!("http://{}/", listening.socket);
let url = s.as_slice();
b.iter(|| {
curl::http::handle()
diff --git a/benches/client.rs b/benches/client.rs
--- a/benches/client.rs
+++ b/benches/client.rs
@@ -67,7 +67,7 @@ impl hyper::header::HeaderFormat for Foo {
#[bench]
fn bench_hyper(b: &mut test::Bencher) {
let mut listening = listen();
- let s = format!("http://{}/", listening.sockets[0]);
+ let s = format!("http://{}/", listening.socket);
let url = s.as_slice();
b.iter(|| {
let mut req = hyper::client::Request::get(hyper::Url::parse(url).unwrap()).unwrap();
diff --git a/benches/client.rs b/benches/client.rs
--- a/benches/client.rs
+++ b/benches/client.rs
@@ -83,7 +83,7 @@ fn bench_hyper(b: &mut test::Bencher) {
#[bench]
fn bench_http(b: &mut test::Bencher) {
let mut listening = listen();
- let s = format!("http://{}/", listening.sockets[0]);
+ let s = format!("http://{}/", listening.socket);
let url = s.as_slice();
b.iter(|| {
let mut req: http::client::RequestWriter = http::client::RequestWriter::new(
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -134,7 +134,6 @@ extern crate openssl;
#[cfg(test)] extern crate test;
extern crate "unsafe-any" as uany;
extern crate "move-acceptor" as macceptor;
-extern crate intertwine;
extern crate typeable;
extern crate cookie;
|
intertwining is slow
Benchmarks with intertwining are in the README. Here's benchmarks with intertwining removed:
```
test bench_http ... bench: 307062 ns/iter (+/- 68288)
test bench_hyper ... bench: 233069 ns/iter (+/- 90194)
```
It'd be neat if intertwining itself could be made faster, but at the least, intertwining shouldn't be used if only listening on 1 port, and there is overhead in sending the messages between 2 threads when the main `hyper acceptor` thread is mostly idle.
|
I've actually just been working on this when it started showing up in profiles and was just about to make a PR, if you already have one ready feel free to make it or I'll just put up mine.
I don't have one yet. I had simply reverted out the interwining commit to compare the benchmarks.
I'll make the PR then, since I've got all the work done.
|
2014-11-11T01:14:38Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
hyperium/hyper
| 108
|
hyperium__hyper-108
|
[
"77"
] |
caab60e37401d50b574e015d43090260137afa47
|
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -7,7 +7,7 @@ use method::{mod, Get, Post, Delete, Put, Patch, Head, Options};
use header::Headers;
use header::common::{mod, Host};
use net::{NetworkStream, NetworkConnector, HttpStream, Fresh, Streaming};
-use http::{HttpWriter, ThroughWriter, ChunkedWriter, SizedWriter, LINE_ENDING};
+use http::{HttpWriter, ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter, LINE_ENDING};
use version;
use {HttpResult, HttpUriError};
use client::Response;
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -117,43 +117,50 @@ impl Request<Fresh> {
try_io!(self.body.write(LINE_ENDING));
- let mut chunked = true;
- let mut len = 0;
-
- match self.headers.get::<common::ContentLength>() {
- Some(cl) => {
- chunked = false;
- len = cl.len();
+ let stream = match self.method {
+ Get | Head => {
+ EmptyWriter(self.body.unwrap())
},
- None => ()
- };
-
- // cant do in match above, thanks borrowck
- if chunked {
- let encodings = match self.headers.get_mut::<common::TransferEncoding>() {
- Some(&common::TransferEncoding(ref mut encodings)) => {
- //TODO: check if chunked is already in encodings. use HashSet?
- encodings.push(common::transfer_encoding::Chunked);
- false
- },
- None => true
- };
-
- if encodings {
- self.headers.set::<common::TransferEncoding>(
- common::TransferEncoding(vec![common::transfer_encoding::Chunked]))
+ _ => {
+ let mut chunked = true;
+ let mut len = 0;
+
+ match self.headers.get::<common::ContentLength>() {
+ Some(cl) => {
+ chunked = false;
+ len = cl.len();
+ },
+ None => ()
+ };
+
+ // cant do in match above, thanks borrowck
+ if chunked {
+ let encodings = match self.headers.get_mut::<common::TransferEncoding>() {
+ Some(&common::TransferEncoding(ref mut encodings)) => {
+ //TODO: check if chunked is already in encodings. use HashSet?
+ encodings.push(common::transfer_encoding::Chunked);
+ false
+ },
+ None => true
+ };
+
+ if encodings {
+ self.headers.set::<common::TransferEncoding>(
+ common::TransferEncoding(vec![common::transfer_encoding::Chunked]))
+ }
+ }
+
+ debug!("headers [\n{}]", self.headers);
+ try_io!(write!(self.body, "{}", self.headers));
+
+ try_io!(self.body.write(LINE_ENDING));
+
+ if chunked {
+ ChunkedWriter(self.body.unwrap())
+ } else {
+ SizedWriter(self.body.unwrap(), len)
+ }
}
- }
-
- debug!("headers [\n{}]", self.headers);
- try_io!(write!(self.body, "{}", self.headers));
-
- try_io!(self.body.write(LINE_ENDING));
-
- let stream = if chunked {
- ChunkedWriter(self.body.unwrap())
- } else {
- SizedWriter(self.body.unwrap(), len)
};
Ok(Request {
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -157,6 +157,8 @@ pub enum HttpWriter<W: Writer> {
///
/// Enforces that the body is not longer than the Content-Length header.
SizedWriter(W, uint),
+ /// A writer that should not write any body.
+ EmptyWriter(W),
}
impl<W: Writer> HttpWriter<W> {
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -166,7 +168,8 @@ impl<W: Writer> HttpWriter<W> {
match self {
ThroughWriter(w) => w,
ChunkedWriter(w) => w,
- SizedWriter(w, _) => w
+ SizedWriter(w, _) => w,
+ EmptyWriter(w) => w,
}
}
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -204,6 +207,18 @@ impl<W: Writer> Writer for HttpWriter<W> {
*remaining -= len;
w.write(msg)
}
+ },
+ EmptyWriter(..) => {
+ let bytes = msg.len();
+ if bytes == 0 {
+ Ok(())
+ } else {
+ Err(io::IoError {
+ kind: io::ShortWrite(bytes),
+ desc: "EmptyWriter cannot write any bytes",
+ detail: Some("Cannot include a body with this kind of message".into_string())
+ })
+ }
}
}
}
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -214,6 +229,7 @@ impl<W: Writer> Writer for HttpWriter<W> {
ThroughWriter(ref mut w) => w.flush(),
ChunkedWriter(ref mut w) => w.flush(),
SizedWriter(ref mut w, _) => w.flush(),
+ EmptyWriter(ref mut w) => w.flush(),
}
}
}
diff --git a/src/mock.rs b/src/mock.rs
--- a/src/mock.rs
+++ b/src/mock.rs
@@ -1,20 +1,55 @@
-use std::io::IoResult;
+use std::fmt;
+use std::io::{IoResult, MemReader, MemWriter};
use std::io::net::ip::{SocketAddr, ToSocketAddr};
use net::{NetworkStream, NetworkConnector};
-#[deriving(Clone, PartialEq, Show)]
-pub struct MockStream;
+pub struct MockStream {
+ pub read: MemReader,
+ pub write: MemWriter,
+}
+
+impl Clone for MockStream {
+ fn clone(&self) -> MockStream {
+ MockStream {
+ read: MemReader::new(self.read.get_ref().to_vec()),
+ write: MemWriter::from_vec(self.write.get_ref().to_vec()),
+ }
+ }
+}
+
+impl PartialEq for MockStream {
+ fn eq(&self, other: &MockStream) -> bool {
+ self.read.get_ref() == other.read.get_ref() &&
+ self.write.get_ref() == other.write.get_ref()
+ }
+}
+impl fmt::Show for MockStream {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "MockStream {{ read: {}, write: {} }}",
+ self.read.get_ref(), self.write.get_ref())
+ }
+
+}
+
+impl MockStream {
+ pub fn new() -> MockStream {
+ MockStream {
+ read: MemReader::new(vec![]),
+ write: MemWriter::new(),
+ }
+ }
+}
impl Reader for MockStream {
- fn read(&mut self, _buf: &mut [u8]) -> IoResult<uint> {
- unimplemented!()
+ fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
+ self.read.read(buf)
}
}
impl Writer for MockStream {
- fn write(&mut self, _msg: &[u8]) -> IoResult<()> {
- unimplemented!()
+ fn write(&mut self, msg: &[u8]) -> IoResult<()> {
+ self.write.write(msg)
}
}
diff --git a/src/mock.rs b/src/mock.rs
--- a/src/mock.rs
+++ b/src/mock.rs
@@ -27,6 +62,6 @@ impl NetworkStream for MockStream {
impl NetworkConnector for MockStream {
fn connect<To: ToSocketAddr>(_addr: To, _scheme: &str) -> IoResult<MockStream> {
- Ok(MockStream)
+ Ok(MockStream::new())
}
}
|
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -192,3 +199,38 @@ impl Writer for Request<Streaming> {
}
}
+#[cfg(test)]
+mod tests {
+ use std::boxed::BoxAny;
+ use std::str::from_utf8;
+ use url::Url;
+ use method::{Get, Head};
+ use mock::MockStream;
+ use super::Request;
+
+ #[test]
+ fn test_get_empty_body() {
+ let req = Request::with_stream::<MockStream>(
+ Get, Url::parse("http://example.dom").unwrap()
+ ).unwrap();
+ let req = req.start().unwrap();
+ let stream = *req.body.end().unwrap().unwrap().downcast::<MockStream>().unwrap();
+ let bytes = stream.write.unwrap();
+ let s = from_utf8(bytes[]).unwrap();
+ assert!(!s.contains("Content-Length:"));
+ assert!(!s.contains("Transfer-Encoding:"));
+ }
+
+ #[test]
+ fn test_head_empty_body() {
+ let req = Request::with_stream::<MockStream>(
+ Head, Url::parse("http://example.dom").unwrap()
+ ).unwrap();
+ let req = req.start().unwrap();
+ let stream = *req.body.end().unwrap().unwrap().downcast::<MockStream>().unwrap();
+ let bytes = stream.write.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
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -100,11 +100,11 @@ mod tests {
status: status::Ok,
headers: Headers::new(),
version: version::Http11,
- body: EofReader(BufferedReader::new(box MockStream as Box<NetworkStream + Send>))
+ body: EofReader(BufferedReader::new(box MockStream::new() as Box<NetworkStream + Send>))
};
let b = res.unwrap().downcast::<MockStream>().unwrap();
- assert_eq!(b, box MockStream);
+ assert_eq!(b, box MockStream::new());
}
}
diff --git a/src/net.rs b/src/net.rs
--- a/src/net.rs
+++ b/src/net.rs
@@ -274,19 +274,19 @@ mod tests {
#[test]
fn test_downcast_box_stream() {
- let stream = box MockStream as Box<NetworkStream + Send>;
+ let stream = box MockStream::new() as Box<NetworkStream + Send>;
let mock = stream.downcast::<MockStream>().unwrap();
- assert_eq!(mock, box MockStream);
+ assert_eq!(mock, box MockStream::new());
}
#[test]
fn test_downcast_unchecked_box_stream() {
- let stream = box MockStream as Box<NetworkStream + Send>;
+ let stream = box MockStream::new() as Box<NetworkStream + Send>;
let mock = unsafe { stream.downcast_unchecked::<MockStream>() };
- assert_eq!(mock, box MockStream);
+ assert_eq!(mock, box MockStream::new());
}
|
Don't send Chunked for requests that shouldn't have bodies
Sounds like `Get`, `Head`, `Options`, `Connect`...
|
2014-11-10T04:59:55Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
|
hyperium/hyper
| 76
|
hyperium__hyper-76
|
[
"75"
] |
08402a1cbf1f039e817d8b056e9de506584d0304
|
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -184,4 +190,3 @@ impl Writer for Request<Streaming> {
self.body.flush()
}
}
-
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,4 +1,4 @@
-#![feature(macro_rules, phase, default_type_params)]
+#![feature(macro_rules, phase, default_type_params, if_let, slicing_syntax)]
#![deny(missing_doc)]
#![deny(warnings)]
#![experimental]
|
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -101,7 +101,13 @@ impl Request<Fresh> {
/// Consume a Fresh Request, writing the headers and method,
/// returning a Streaming Request.
pub fn start(mut self) -> HttpResult<Request<Streaming>> {
- let uri = self.url.serialize_path().unwrap();
+ let mut uri = self.url.serialize_path().unwrap();
+ //TODO: this needs a test
+ if let Some(ref q) = self.url.query {
+ uri.push('?');
+ uri.push_str(q[]);
+ }
+
debug!("writing head: {} {} {}", self.method, uri, self.version);
try_io!(write!(self.body, "{} {} {}", self.method, uri, self.version))
try_io!(self.body.write(LINE_ENDING));
|
Hyper client discards query string when making requests
Hi all,
Found an issue while using Hyper's HTTP client.
When starting the request, Hyper calls `rust-url`'s `serialize_path` function to generate the first header line, but `serialize_path` discards the query string from the URL. This breaks any GET request that depends on query parameters.
I sent a new pull request to rust-url that introduces a `serialize_path_with_query` method specifically so that Hyper can use it.
https://github.com/servo/rust-url/pull/38
If `serialize_path_with_query` gets merged into `rust-url`, I'm happy to create a pull request that updates Hyper to match.
|
If that gets merged into a rust-url, I'd be happy to use it. Until then, I'll just submit a fix to unblock you (or anyone else) right now.
|
2014-10-13T17:17:18Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
hyperium/hyper
| 59
|
hyperium__hyper-59
|
[
"51"
] |
41164fece9d8ae493ba7836c60016d6adc2c3147
|
diff --git a/src/client/response.rs b/src/client/response.rs
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -65,6 +65,11 @@ impl Response {
body: body,
})
}
+
+ /// Unwraps the Request to return the NetworkStream underneath.
+ pub fn unwrap(self) -> Box<NetworkStream + Send> {
+ self.body.unwrap().unwrap()
+ }
}
impl Reader for Response {
diff --git a/src/header/common/connection.rs b/src/header/common/connection.rs
--- a/src/header/common/connection.rs
+++ b/src/header/common/connection.rs
@@ -1,45 +1,62 @@
use header::Header;
use std::fmt::{mod, Show};
-use super::util::from_one_raw_str;
+use super::{from_comma_delimited, fmt_comma_delimited};
use std::from_str::FromStr;
/// The `Connection` header.
-///
-/// Describes whether the socket connection should be closed or reused after
-/// this request/response is completed.
#[deriving(Clone, PartialEq, Show)]
-pub enum Connection {
+pub struct Connection(Vec<ConnectionOption>);
+
+/// Values that can be in the `Connection` header.
+#[deriving(Clone, PartialEq)]
+pub enum ConnectionOption {
/// The `keep-alive` connection value.
KeepAlive,
/// The `close` connection value.
- Close
+ Close,
+ /// Values in the Connection header that are supposed to be names of other Headers.
+ ///
+ /// > When a header field aside from Connection is used to supply control
+ /// > information for or about the current connection, the sender MUST list
+ /// > the corresponding field-name within the Connection header field.
+ // TODO: it would be nice if these "Strings" could be stronger types, since
+ // they are supposed to relate to other Header fields (which we have strong
+ // types for).
+ ConnectionHeader(String),
}
-impl FromStr for Connection {
- fn from_str(s: &str) -> Option<Connection> {
- debug!("Connection::from_str =? {}", s);
+impl FromStr for ConnectionOption {
+ fn from_str(s: &str) -> Option<ConnectionOption> {
match s {
"keep-alive" => Some(KeepAlive),
"close" => Some(Close),
- _ => None
+ s => Some(ConnectionHeader(s.to_string()))
}
}
}
+impl fmt::Show for ConnectionOption {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ KeepAlive => "keep-alive",
+ Close => "close",
+ ConnectionHeader(ref s) => s.as_slice()
+ }.fmt(fmt)
+ }
+}
+
impl Header for Connection {
fn header_name(_: Option<Connection>) -> &'static str {
"Connection"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<Connection> {
- from_one_raw_str(raw)
+ from_comma_delimited(raw).map(|vec| Connection(vec))
}
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- match *self {
- KeepAlive => "keep-alive",
- Close => "close",
- }.fmt(fmt)
+ let Connection(ref parts) = *self;
+ fmt_comma_delimited(fmt, parts[])
}
}
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs
--- a/src/header/common/mod.rs
+++ b/src/header/common/mod.rs
@@ -6,19 +6,27 @@
//! strongly-typed theme, the [mime](http://seanmonstar.github.io/mime.rs) crate
//! is used, such as `ContentType(pub Mime)`.
-pub use self::host::Host;
-pub use self::content_length::ContentLength;
-pub use self::content_type::ContentType;
pub use self::accept::Accept;
pub use self::connection::Connection;
+pub use self::content_length::ContentLength;
+pub use self::content_type::ContentType;
+pub use self::date::Date;
+pub use self::host::Host;
+pub use self::location::Location;
pub use self::transfer_encoding::TransferEncoding;
+pub use self::upgrade::Upgrade;
pub use self::user_agent::UserAgent;
pub use self::server::Server;
-pub use self::date::Date;
-pub use self::location::Location;
-/// Exposes the Host header.
-pub mod host;
+use std::fmt::{mod, Show};
+use std::from_str::FromStr;
+use std::str::from_utf8;
+
+/// Exposes the Accept header.
+pub mod accept;
+
+/// Exposes the Connection header.
+pub mod connection;
/// Exposes the ContentLength header.
pub mod content_length;
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs
--- a/src/header/common/mod.rs
+++ b/src/header/common/mod.rs
@@ -26,23 +34,24 @@ pub mod content_length;
/// Exposes the ContentType header.
pub mod content_type;
-/// Exposes the Accept header.
-pub mod accept;
+/// Exposes the Date header.
+pub mod date;
-/// Exposes the Connection header.
-pub mod connection;
+/// Exposes the Host header.
+pub mod host;
+
+/// Exposes the Server header.
+pub mod server;
/// Exposes the TransferEncoding header.
pub mod transfer_encoding;
+/// Exposes the Upgrade header.
+pub mod upgrade;
+
/// Exposes the UserAgent header.
pub mod user_agent;
-/// Exposes the Server header.
-pub mod server;
-
-/// Exposes the Date header.
-pub mod date;
/// Exposes the Location header.
pub mod location;
diff --git a/src/header/common/mod.rs b/src/header/common/mod.rs
--- a/src/header/common/mod.rs
+++ b/src/header/common/mod.rs
@@ -50,3 +59,29 @@ pub mod location;
pub mod util;
+fn from_comma_delimited<T: FromStr>(raw: &[Vec<u8>]) -> Option<Vec<T>> {
+ if raw.len() != 1 {
+ return None;
+ }
+ // we JUST checked that raw.len() == 1, so raw[0] WILL exist.
+ match from_utf8(unsafe { raw.as_slice().unsafe_get(0).as_slice() }) {
+ Some(s) => {
+ Some(s.as_slice()
+ .split([',', ' '].as_slice())
+ .filter_map(from_str)
+ .collect())
+ }
+ None => None
+ }
+}
+
+fn fmt_comma_delimited<T: Show>(fmt: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {
+ let last = parts.len() - 1;
+ for (i, part) in parts.iter().enumerate() {
+ try!(part.fmt(fmt));
+ if i < last {
+ try!(", ".fmt(fmt));
+ }
+ }
+ Ok(())
+}
diff --git a/src/header/common/transfer_encoding.rs b/src/header/common/transfer_encoding.rs
--- a/src/header/common/transfer_encoding.rs
+++ b/src/header/common/transfer_encoding.rs
@@ -1,7 +1,7 @@
use header::Header;
-use std::fmt::{mod, Show};
+use std::fmt;
use std::from_str::FromStr;
-use std::str::from_utf8;
+use super::{from_comma_delimited, fmt_comma_delimited};
/// The `Transfer-Encoding` header.
///
diff --git a/src/header/common/transfer_encoding.rs b/src/header/common/transfer_encoding.rs
--- a/src/header/common/transfer_encoding.rs
+++ b/src/header/common/transfer_encoding.rs
@@ -28,7 +28,7 @@ pub struct TransferEncoding(pub Vec<Encoding>);
/// # use hyper::header::Headers;
/// # let mut headers = Headers::new();
/// headers.set(TransferEncoding(vec![Gzip, Chunked]));
-#[deriving(Clone, PartialEq, Show)]
+#[deriving(Clone, PartialEq)]
pub enum Encoding {
/// The `chunked` encoding.
Chunked,
diff --git a/src/header/common/transfer_encoding.rs b/src/header/common/transfer_encoding.rs
--- a/src/header/common/transfer_encoding.rs
+++ b/src/header/common/transfer_encoding.rs
@@ -43,6 +43,18 @@ pub enum Encoding {
EncodingExt(String)
}
+impl fmt::Show for Encoding {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ Chunked => "chunked",
+ Gzip => "gzip",
+ Deflate => "deflate",
+ Compress => "compress",
+ EncodingExt(ref s) => s.as_slice()
+ }.fmt(fmt)
+ }
+}
+
impl FromStr for Encoding {
fn from_str(s: &str) -> Option<Encoding> {
match s {
diff --git a/src/header/common/transfer_encoding.rs b/src/header/common/transfer_encoding.rs
--- a/src/header/common/transfer_encoding.rs
+++ b/src/header/common/transfer_encoding.rs
@@ -61,31 +73,12 @@ impl Header for TransferEncoding {
}
fn parse_header(raw: &[Vec<u8>]) -> Option<TransferEncoding> {
- if raw.len() != 1 {
- return None;
- }
- // we JUST checked that raw.len() == 1, so raw[0] WILL exist.
- match from_utf8(unsafe { raw.as_slice().unsafe_get(0).as_slice() }) {
- Some(s) => {
- Some(TransferEncoding(s.as_slice()
- .split([',', ' '].as_slice())
- .filter_map(from_str)
- .collect()))
- }
- None => None
- }
+ from_comma_delimited(raw).map(|vec| TransferEncoding(vec))
}
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let TransferEncoding(ref parts) = *self;
- let last = parts.len() - 1;
- for (i, part) in parts.iter().enumerate() {
- try!(part.fmt(fmt));
- if i < last {
- try!(", ".fmt(fmt));
- }
- }
- Ok(())
+ fmt_comma_delimited(fmt, parts[])
}
}
diff --git /dev/null b/src/header/common/upgrade.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/upgrade.rs
@@ -0,0 +1,51 @@
+use header::Header;
+use std::fmt::{mod, Show};
+use super::{from_comma_delimited, fmt_comma_delimited};
+use std::from_str::FromStr;
+
+/// The `Upgrade` header.
+#[deriving(Clone, PartialEq, Show)]
+pub struct Upgrade(Vec<Protocol>);
+
+/// Protocol values that can appear in the Upgrade header.
+#[deriving(Clone, PartialEq)]
+pub enum Protocol {
+ /// The websocket protocol.
+ WebSocket,
+ /// Some other less common protocol.
+ ProtocolExt(String),
+}
+
+impl FromStr for Protocol {
+ fn from_str(s: &str) -> Option<Protocol> {
+ match s {
+ "websocket" => Some(WebSocket),
+ s => Some(ProtocolExt(s.to_string()))
+ }
+ }
+}
+
+impl fmt::Show for Protocol {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ WebSocket => "websocket",
+ ProtocolExt(ref s) => s.as_slice()
+ }.fmt(fmt)
+ }
+}
+
+impl Header for Upgrade {
+ fn header_name(_: Option<Upgrade>) -> &'static str {
+ "Upgrade"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<Upgrade> {
+ from_comma_delimited(raw).map(|vec| Upgrade(vec))
+ }
+
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ let Upgrade(ref parts) = *self;
+ fmt_comma_delimited(fmt, parts[])
+ }
+}
+
diff --git a/src/http.rs b/src/http.rs
--- a/src/http.rs
+++ b/src/http.rs
@@ -38,6 +38,18 @@ pub enum HttpReader<R> {
EofReader(R),
}
+impl<R: Reader> HttpReader<R> {
+
+ /// Unwraps this HttpReader and returns the underlying Reader.
+ pub fn unwrap(self) -> R {
+ match self {
+ SizedReader(r, _) => r,
+ ChunkedReader(r, _) => r,
+ EofReader(r) => r,
+ }
+ }
+}
+
impl<R: Reader> Reader for HttpReader<R> {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match *self {
diff --git /dev/null b/src/mock.rs
new file mode 100644
--- /dev/null
+++ b/src/mock.rs
@@ -0,0 +1,29 @@
+use std::io::IoResult;
+use std::io::net::ip::SocketAddr;
+
+use net::NetworkStream;
+
+#[deriving(Clone, PartialEq, Show)]
+pub struct MockStream;
+
+impl Reader for MockStream {
+ fn read(&mut self, _buf: &mut [u8]) -> IoResult<uint> {
+ unimplemented!()
+ }
+}
+
+impl Writer for MockStream {
+ fn write(&mut self, _msg: &[u8]) -> IoResult<()> {
+ unimplemented!()
+ }
+}
+
+impl NetworkStream for MockStream {
+ fn connect(_host: &str, _port: u16, _scheme: &str) -> IoResult<MockStream> {
+ Ok(MockStream)
+ }
+
+ fn peer_name(&mut self) -> IoResult<SocketAddr> {
+ Ok(from_str("127.0.0.1:1337").unwrap())
+ }
+}
diff --git a/src/net.rs b/src/net.rs
--- a/src/net.rs
+++ b/src/net.rs
@@ -1,10 +1,18 @@
//! A collection of traits abstracting over Listeners and Streams.
+use std::any::{Any, AnyRefExt};
+use std::boxed::BoxAny;
+use std::fmt;
+use std::intrinsics::TypeId;
use std::io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError,
Stream, Listener, Acceptor};
use std::io::net::ip::{SocketAddr, Port};
use std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor};
+use std::mem::{mod, transmute, transmute_copy};
+use std::raw::{mod, TraitObject};
use std::sync::{Arc, Mutex};
+use uany::UncheckedBoxAnyDowncast;
+use typeable::Typeable;
use openssl::ssl::{SslStream, SslContext, Sslv23};
use openssl::ssl::error::{SslError, StreamError, OpenSslErrors, SslSessionClosed};
diff --git a/src/net.rs b/src/net.rs
--- a/src/net.rs
+++ b/src/net.rs
@@ -15,7 +23,7 @@ pub struct Fresh;
pub struct Streaming;
/// An abstraction to listen for connections on a certain port.
-pub trait NetworkListener<S: NetworkStream, A: NetworkAcceptor<S>>: Listener<S, A> {
+pub trait NetworkListener<S: NetworkStream, A: NetworkAcceptor<S>>: Listener<S, A> + Typeable {
/// Bind to a socket.
///
/// Note: This does not start listening for connections. You must call
diff --git a/src/net.rs b/src/net.rs
--- a/src/net.rs
+++ b/src/net.rs
@@ -33,7 +41,7 @@ pub trait NetworkAcceptor<S: NetworkStream>: Acceptor<S> + Clone + Send {
}
/// An abstraction over streams that a Server can utilize.
-pub trait NetworkStream: Stream + Clone + Send {
+pub trait NetworkStream: Stream + Any + Clone + Send {
/// Get the remote address of the underlying connection.
fn peer_name(&mut self) -> IoResult<SocketAddr>;
diff --git a/src/net.rs b/src/net.rs
--- a/src/net.rs
+++ b/src/net.rs
@@ -52,6 +60,12 @@ pub trait NetworkStream: Stream + Clone + Send {
fn clone_box(&self) -> Box<NetworkStream + Send> { self.clone().dynamic() }
}
+impl fmt::Show for Box<NetworkStream + Send> {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ fmt.pad("Box<NetworkStream>")
+ }
+}
+
impl Clone for Box<NetworkStream + Send> {
#[inline]
fn clone(&self) -> Box<NetworkStream + Send> { self.clone_box() }
diff --git a/src/net.rs b/src/net.rs
--- a/src/net.rs
+++ b/src/net.rs
@@ -70,6 +84,46 @@ impl Writer for Box<NetworkStream + Send> {
fn flush(&mut self) -> IoResult<()> { (**self).flush() }
}
+impl UncheckedBoxAnyDowncast for Box<NetworkStream + Send> {
+ unsafe fn downcast_unchecked<T: 'static>(self) -> Box<T> {
+ let to = *mem::transmute::<&Box<NetworkStream + Send>, &raw::TraitObject>(&self);
+ // Prevent double-free.
+ mem::forget(self);
+ mem::transmute(to.data)
+ }
+}
+
+impl<'a> AnyRefExt<'a> for &'a NetworkStream + 'a {
+ #[inline]
+ fn is<T: 'static>(self) -> bool {
+ self.get_type_id() == TypeId::of::<T>()
+ }
+
+ #[inline]
+ fn downcast_ref<T: 'static>(self) -> Option<&'a T> {
+ if self.is::<T>() {
+ unsafe {
+ // Get the raw representation of the trait object
+ let to: TraitObject = transmute_copy(&self);
+ // Extract the data pointer
+ Some(transmute(to.data))
+ }
+ } else {
+ None
+ }
+ }
+}
+
+impl BoxAny for Box<NetworkStream + Send> {
+ fn downcast<T: 'static>(self) -> Result<Box<T>, Box<NetworkStream + Send>> {
+ if self.is::<T>() {
+ Ok(unsafe { self.downcast_unchecked() })
+ } else {
+ Err(self)
+ }
+ }
+}
+
/// A `NetworkListener` for `HttpStream`s.
pub struct HttpListener {
inner: TcpListener
|
diff --git a/src/client/response.rs b/src/client/response.rs
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -73,3 +78,33 @@ impl Reader for Response {
self.body.read(buf)
}
}
+
+#[cfg(test)]
+mod tests {
+ use std::boxed::BoxAny;
+ use std::io::BufferedReader;
+
+ use header::Headers;
+ use http::EofReader;
+ use mock::MockStream;
+ use net::NetworkStream;
+ use status;
+ use version;
+
+ use super::Response;
+
+
+ #[test]
+ fn test_unwrap() {
+ let res = Response {
+ status: status::Ok,
+ headers: Headers::new(),
+ version: version::Http11,
+ body: EofReader(BufferedReader::new(box MockStream as Box<NetworkStream + Send>))
+ };
+
+ let b = res.unwrap().downcast::<MockStream>().unwrap();
+ assert_eq!(b, box MockStream);
+
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -184,6 +184,7 @@ pub mod status;
pub mod uri;
pub mod version;
+#[cfg(test)] mod mock;
mod mimewrapper {
/// Re-exporting the mime crate, for convenience.
diff --git a/src/net.rs b/src/net.rs
--- a/src/net.rs
+++ b/src/net.rs
@@ -212,3 +266,30 @@ fn lift_ssl_error(ssl: SslError) -> IoError {
}
}
+#[cfg(test)]
+mod tests {
+ use std::boxed::BoxAny;
+ use uany::UncheckedBoxAnyDowncast;
+
+ use mock::MockStream;
+ use super::NetworkStream;
+
+ #[test]
+ fn test_downcast_box_stream() {
+ let stream = MockStream.dynamic();
+
+ let mock = stream.downcast::<MockStream>().unwrap();
+ assert_eq!(mock, box MockStream);
+
+ }
+
+ #[test]
+ fn test_downcast_unchecked_box_stream() {
+ let stream = MockStream.dynamic();
+
+ let mock = unsafe { stream.downcast_unchecked::<MockStream>() };
+ assert_eq!(mock, box MockStream);
+
+ }
+
+}
|
Enable raw, possibly unsafe, access to the original Socket
Needed by servo. Needed on the server for socket libraries.
Also includes handling the `Upgrade` value for `Connection`.
|
2014-09-25T00:33:50Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
|
hyperium/hyper
| 48
|
hyperium__hyper-48
|
[
"47",
"47"
] |
1b65d5e2e60c79bc0b033823e5f7712f073abfa6
|
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -111,7 +111,7 @@ impl Request<Fresh> {
let mut chunked = true;
let mut len = 0;
- match self.headers.get_ref::<common::ContentLength>() {
+ match self.headers.get::<common::ContentLength>() {
Some(cl) => {
chunked = false;
len = cl.len();
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -121,16 +121,19 @@ impl Request<Fresh> {
// cant do in match above, thanks borrowck
if chunked {
- //TODO: use CollectionViews (when implemented) to prevent double hash/lookup
- let encodings = match self.headers.get::<common::TransferEncoding>() {
- Some(common::TransferEncoding(mut encodings)) => {
+ let encodings = match self.headers.get_mut::<common::TransferEncoding>() {
+ Some(&common::TransferEncoding(ref mut encodings)) => {
//TODO: check if chunked is already in encodings. use HashSet?
encodings.push(common::transfer_encoding::Chunked);
- encodings
+ false
},
- None => vec![common::transfer_encoding::Chunked]
+ None => true
};
- self.headers.set(common::TransferEncoding(encodings));
+
+ if encodings {
+ self.headers.set::<common::TransferEncoding>(
+ common::TransferEncoding(vec![common::transfer_encoding::Chunked]))
+ }
}
for (name, header) in self.headers.iter() {
diff --git a/src/client/response.rs b/src/client/response.rs
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -27,13 +27,13 @@ impl Response {
pub fn new(stream: Box<NetworkStream + Send>) -> HttpResult<Response> {
let mut stream = BufferedReader::new(stream.abstract());
let (version, status) = try!(read_status_line(&mut stream));
- let mut headers = try!(header::Headers::from_raw(&mut stream));
+ let headers = try!(header::Headers::from_raw(&mut stream));
debug!("{} {}", version, status);
debug!("{}", headers);
let body = if headers.has::<TransferEncoding>() {
- match headers.get_ref::<TransferEncoding>() {
+ match headers.get::<TransferEncoding>() {
Some(&TransferEncoding(ref codings)) => {
if codings.len() > 1 {
debug!("TODO: #2 handle other codings: {}", codings);
diff --git a/src/client/response.rs b/src/client/response.rs
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -49,7 +49,7 @@ impl Response {
None => unreachable!()
}
} else if headers.has::<ContentLength>() {
- match headers.get_ref::<ContentLength>() {
+ match headers.get::<ContentLength>() {
Some(&ContentLength(len)) => SizedReader(stream, len),
None => unreachable!()
}
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -13,8 +13,9 @@ use std::raw::TraitObject;
use std::str::{from_utf8, SendStr, Slice, Owned};
use std::string::raw;
use std::collections::hashmap::{HashMap, Entries, Occupied, Vacant};
+use std::sync::RWLock;
-use uany::UncheckedAnyDowncast;
+use uany::{UncheckedAnyDowncast, UncheckedAnyMutDowncast};
use typeable::Typeable;
use http::read_header;
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -24,7 +25,7 @@ use {HttpResult};
pub mod common;
/// A trait for any object that will represent a header field and value.
-pub trait Header: Typeable {
+pub trait Header: Typeable + Send + Sync {
/// Returns the name of the header field this belongs to.
///
/// The market `Option` is to hint to the type system which implementation
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -61,6 +62,14 @@ impl<'a> UncheckedAnyDowncast<'a> for &'a Header {
}
}
+impl<'a> UncheckedAnyMutDowncast<'a> for &'a mut Header {
+ #[inline]
+ unsafe fn downcast_mut_unchecked<T: 'static>(self) -> &'a mut T {
+ let to: TraitObject = transmute_copy(&self);
+ transmute(to.data)
+ }
+}
+
fn header_name<T: Header>() -> &'static str {
let name = Header::header_name(None::<T>);
name
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -68,7 +77,7 @@ fn header_name<T: Header>() -> &'static str {
/// A map of header fields on requests and responses.
pub struct Headers {
- data: HashMap<CaseInsensitive, Item>
+ data: HashMap<CaseInsensitive, RWLock<Item>>
}
impl Headers {
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -92,13 +101,14 @@ impl Headers {
raw::from_utf8(name)
};
- let item = match headers.data.entry(CaseInsensitive(Owned(name))) {
- Vacant(entry) => entry.set(Raw(vec![])),
+ let name = CaseInsensitive(Owned(name));
+ let item = match headers.data.entry(name) {
+ Vacant(entry) => entry.set(RWLock::new(Raw(vec![]))),
Occupied(entry) => entry.into_mut()
};
- match *item {
- Raw(ref mut raw) => raw.push(value),
+ match &mut *item.write() {
+ &Raw(ref mut raw) => raw.push(value),
// Unreachable
_ => {}
};
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -113,21 +123,7 @@ impl Headers {
///
/// The field is determined by the type of the value being set.
pub fn set<H: Header>(&mut self, value: H) {
- self.data.insert(CaseInsensitive(Slice(header_name::<H>())), Typed(box value as Box<Header>));
- }
-
- /// Get a clone of the header field's value, if it exists.
- ///
- /// Example:
- ///
- /// ```
- /// # use hyper::header::Headers;
- /// # use hyper::header::common::ContentType;
- /// # let mut headers = Headers::new();
- /// let content_type = headers.get::<ContentType>();
- /// ```
- pub fn get<H: Header + Clone>(&mut self) -> Option<H> {
- self.get_ref().map(|v: &H| v.clone())
+ self.data.insert(CaseInsensitive(Slice(header_name::<H>())), RWLock::new(Typed(box value as Box<Header + Send + Sync>)));
}
/// Access the raw value of a header, if it exists and has not
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -136,56 +132,92 @@ impl Headers {
/// If the header field has already been parsed into a typed header,
/// then you *must* access it through that representation.
///
+ /// This operation is unsafe because the raw representation can be
+ /// invalidated by lasting too long or by the header being parsed
+ /// while you still have a reference to the data.
+ ///
/// Example:
/// ```
/// # use hyper::header::Headers;
/// # let mut headers = Headers::new();
/// let raw_content_type = unsafe { headers.get_raw("content-type") };
/// ```
- pub unsafe fn get_raw(&self, name: &'static str) -> Option<&[Vec<u8>]> {
+ pub unsafe fn get_raw(&self, name: &'static str) -> Option<*const [Vec<u8>]> {
self.data.find(&CaseInsensitive(Slice(name))).and_then(|item| {
- match *item {
- Raw(ref raw) => Some(raw.as_slice()),
+ match *item.read() {
+ Raw(ref raw) => Some(raw.as_slice() as *const [Vec<u8>]),
_ => None
}
})
}
/// Get a reference to the header field's value, if it exists.
- pub fn get_ref<H: Header>(&mut self) -> Option<&H> {
- self.data.find_mut(&CaseInsensitive(Slice(header_name::<H>()))).and_then(|item| {
- debug!("get_ref, name={}, val={}", header_name::<H>(), item);
- let header = match *item {
+ pub fn get<H: Header>(&self) -> Option<&H> {
+ self.get_or_parse::<H>().map(|item| {
+ let read = item.read();
+ debug!("downcasting {}", *read);
+ let ret = match *read {
+ Typed(ref val) => unsafe { val.downcast_ref_unchecked() },
+ _ => unreachable!()
+ };
+ unsafe { transmute::<&H, &H>(ret) }
+ })
+ }
+
+ /// Get a mutable reference to the header field's value, if it exists.
+ pub fn get_mut<H: Header>(&mut self) -> Option<&mut H> {
+ self.get_or_parse::<H>().map(|item| {
+ let mut write = item.write();
+ debug!("downcasting {}", *write);
+ let ret = match *&mut *write {
+ Typed(ref mut val) => unsafe { val.downcast_mut_unchecked() },
+ _ => unreachable!()
+ };
+ unsafe { transmute::<&mut H, &mut H>(ret) }
+ })
+ }
+
+ fn get_or_parse<H: Header>(&self) -> Option<&RWLock<Item>> {
+ self.data.find(&CaseInsensitive(Slice(header_name::<H>()))).and_then(|item| {
+ let done = match *item.read() {
// Huge borrowck hack here, should be refactored to just return here.
- Typed(ref typed) if typed.is::<H>() => None,
- // Typed, wrong type
+ Typed(ref typed) if typed.is::<H>() => true,
+
+ // Typed, wrong type.
Typed(_) => return None,
- Raw(ref raw) => match Header::parse_header(raw.as_slice()) {
- Some::<H>(h) => {
- Some(h)
- },
- None => return None
- },
+
+ // Raw, work to do.
+ Raw(_) => false,
};
- match header {
- Some(header) => {
- *item = Typed(box header as Box<Header>);
- Some(item)
- },
- None => {
- Some(item)
+ // borrowck hack continued
+ if done { return Some(item); }
+
+ // Take out a write lock to do the parsing and mutation.
+ let mut write = item.write();
+
+ let header = match *write {
+ // Since this lock can queue, it's possible another thread just
+ // did the work for us.
+ //
+ // Check they inserted the correct type and move on.
+ Typed(ref typed) if typed.is::<H>() => return Some(item),
+
+ // Wrong type, another thread got here before us and parsed
+ // as a different representation.
+ Typed(_) => return None,
+
+ // We are first in the queue or the only ones, so do the actual
+ // work of parsing and mutation.
+ Raw(ref raw) => match Header::parse_header(raw.as_slice()) {
+ Some::<H>(h) => h,
+ None => return None
}
- }
- }).and_then(|item| {
- debug!("downcasting {}", item);
- let ret = match *item {
- Typed(ref val) => {
- unsafe { Some(val.downcast_ref_unchecked()) }
- },
- _ => unreachable!()
};
- ret
+
+ // Mutate in the raw case.
+ *write = Typed(box header as Box<Header + Send + Sync>);
+ Some(item)
})
}
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -229,7 +261,7 @@ impl fmt::Show for Headers {
/// An `Iterator` over the fields in a `Headers` map.
pub struct HeadersItems<'a> {
- inner: Entries<'a, CaseInsensitive, Item>
+ inner: Entries<'a, CaseInsensitive, RWLock<Item>>
}
impl<'a> Iterator<(&'a str, HeaderView<'a>)> for HeadersItems<'a> {
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -242,12 +274,12 @@ impl<'a> Iterator<(&'a str, HeaderView<'a>)> for HeadersItems<'a> {
}
/// Returned with the `HeadersItems` iterator.
-pub struct HeaderView<'a>(&'a Item);
+pub struct HeaderView<'a>(&'a RWLock<Item>);
impl<'a> fmt::Show for HeaderView<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let HeaderView(item) = *self;
- item.fmt(fmt)
+ item.read().fmt(fmt)
}
}
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -265,7 +297,7 @@ impl Mutable for Headers {
enum Item {
Raw(Vec<Vec<u8>>),
- Typed(Box<Header>)
+ Typed(Box<Header + Send + Sync>)
}
impl fmt::Show for Item {
diff --git a/src/server/request.rs b/src/server/request.rs
--- a/src/server/request.rs
+++ b/src/server/request.rs
@@ -39,14 +39,14 @@ impl Request {
let remote_addr = try_io!(stream.peer_name());
let mut stream = BufferedReader::new(stream.abstract());
let (method, uri, version) = try!(read_request_line(&mut stream));
- let mut headers = try!(Headers::from_raw(&mut stream));
+ let headers = try!(Headers::from_raw(&mut stream));
debug!("{} {} {}", method, uri, version);
debug!("{}", headers);
let body = if headers.has::<ContentLength>() {
- match headers.get_ref::<ContentLength>() {
+ match headers.get::<ContentLength>() {
Some(&ContentLength(len)) => SizedReader(stream, len),
None => unreachable!()
}
diff --git a/src/server/response.rs b/src/server/response.rs
--- a/src/server/response.rs
+++ b/src/server/response.rs
@@ -72,7 +72,7 @@ impl Response<Fresh> {
let mut chunked = true;
let mut len = 0;
- match self.headers.get_ref::<common::ContentLength>() {
+ match self.headers.get::<common::ContentLength>() {
Some(cl) => {
chunked = false;
len = cl.len();
diff --git a/src/server/response.rs b/src/server/response.rs
--- a/src/server/response.rs
+++ b/src/server/response.rs
@@ -82,16 +82,19 @@ impl Response<Fresh> {
// cant do in match above, thanks borrowck
if chunked {
- //TODO: use CollectionViews (when implemented) to prevent double hash/lookup
- let encodings = match self.headers.get::<common::TransferEncoding>() {
- Some(common::TransferEncoding(mut encodings)) => {
+ let encodings = match self.headers.get_mut::<common::TransferEncoding>() {
+ Some(&common::TransferEncoding(ref mut encodings)) => {
//TODO: check if chunked is already in encodings. use HashSet?
encodings.push(common::transfer_encoding::Chunked);
- encodings
+ false
},
- None => vec![common::transfer_encoding::Chunked]
+ None => true
};
- self.headers.set(common::TransferEncoding(encodings));
+
+ if encodings {
+ self.headers.set::<common::TransferEncoding>(
+ common::TransferEncoding(vec![common::transfer_encoding::Chunked]))
+ }
}
for (name, header) in self.headers.iter() {
|
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -341,8 +373,8 @@ mod tests {
#[test]
fn test_from_raw() {
- let mut headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
- assert_eq!(headers.get_ref(), Some(&ContentLength(10)));
+ let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
+ assert_eq!(headers.get(), Some(&ContentLength(10)));
}
#[test]
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -380,8 +412,31 @@ mod tests {
#[test]
fn test_different_structs_for_same_header() {
- let mut headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
- let ContentLength(_) = headers.get::<ContentLength>().unwrap();
+ let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
+ let ContentLength(_) = *headers.get::<ContentLength>().unwrap();
assert!(headers.get::<CrazyLength>().is_none());
}
+
+ #[test]
+ fn test_multiple_reads() {
+ let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
+ let ContentLength(one) = *headers.get::<ContentLength>().unwrap();
+ let ContentLength(two) = *headers.get::<ContentLength>().unwrap();
+ assert_eq!(one, two);
+ }
+
+ #[test]
+ fn test_different_reads() {
+ let headers = Headers::from_raw(&mut mem("Content-Length: 10\r\nContent-Type: text/plain\r\n\r\n")).unwrap();
+ let ContentLength(_) = *headers.get::<ContentLength>().unwrap();
+ let ContentType(_) = *headers.get::<ContentType>().unwrap();
+ }
+
+ #[test]
+ fn test_get_mutable() {
+ let mut headers = Headers::from_raw(&mut mem("Content-Length: 10\r\nContent-Type: text/plain\r\n\r\n")).unwrap();
+ *headers.get_mut::<ContentLength>().unwrap() = ContentLength(20);
+ assert_eq!(*headers.get::<ContentLength>().unwrap(), ContentLength(20));
+ }
}
+
|
&'a Headers does not allow reading Headers
I've got a branch implementing a `HeadersView` that solves this problem, but right now that means you can't read the Headers of anything `Streaming`.
&'a Headers does not allow reading Headers
I've got a branch implementing a `HeadersView` that solves this problem, but right now that means you can't read the Headers of anything `Streaming`.
|
Oh right, because it needs to be mutable internally. Maybe Headers could
keep a RefCell of the HashMap. It's mutability is just an implementation
detail, and shouldn't concern users.
That would also improve fighting the borrowck in matches.
RefCell would not be a good solution here as it would be a leaky abstraction and lead to runtime failures when code tries to get two header references with overlapping lifetimes - this code would fail, for instance:
``` rust
let length = req.headers.get_ref::<ContentLength>();
let encoding = req.headers.get_ref::<TransferEncoding>();
```
Right now this is a compile-time failure, using RefCell would make it a runtime failure.
We would also have to return `cell::Ref` and `cell::RefMut` instead of `&` and `&mut`.
Oh right, because it needs to be mutable internally. Maybe Headers could
keep a RefCell of the HashMap. It's mutability is just an implementation
detail, and shouldn't concern users.
That would also improve fighting the borrowck in matches.
RefCell would not be a good solution here as it would be a leaky abstraction and lead to runtime failures when code tries to get two header references with overlapping lifetimes - this code would fail, for instance:
``` rust
let length = req.headers.get_ref::<ContentLength>();
let encoding = req.headers.get_ref::<TransferEncoding>();
```
Right now this is a compile-time failure, using RefCell would make it a runtime failure.
We would also have to return `cell::Ref` and `cell::RefMut` instead of `&` and `&mut`.
|
2014-09-20T11:17:10Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
hyperium/hyper
| 36
|
hyperium__hyper-36
|
[
"35"
] |
c40b5b0c53d21d88050af7c702346c5ef5c27e93
|
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -7,6 +7,7 @@
use std::ascii::OwnedAsciiExt;
use std::char::is_lowercase;
use std::fmt::{mod, Show};
+use std::intrinsics::TypeId;
use std::mem::{transmute, transmute_copy};
use std::raw::TraitObject;
use std::str::{from_utf8, SendStr, Slice, Owned};
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -80,11 +81,8 @@ impl Headers {
let name = unsafe {
raw::from_utf8(name)
}.into_ascii_lower();
- match headers.data.find_or_insert(Owned(name), Raw(vec![])) {
- &Raw(ref mut pieces) => pieces.push(value),
- // at this point, Raw is the only thing that has been inserted
- _ => unreachable!()
- }
+ let item = headers.data.find_or_insert(Owned(name), raw(vec![]));
+ item.raw.push(value);
},
None => break,
}
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -96,7 +94,11 @@ impl Headers {
///
/// The field is determined by the type of the value being set.
pub fn set<H: Header>(&mut self, value: H) {
- self.data.insert(Slice(header_name::<H>()), Typed(box value));
+ self.data.insert(Slice(header_name::<H>()), Item {
+ raw: vec![],
+ tid: Some(TypeId::of::<H>()),
+ typed: Some(box value as Box<Header>)
+ });
}
/// Get a clone of the header field's value, if it exists.
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -126,11 +128,8 @@ impl Headers {
/// let raw_content_type = unsafe { headers.get_raw("content-type") };
/// ```
pub unsafe fn get_raw(&self, name: &'static str) -> Option<&[Vec<u8>]> {
- self.data.find(&Slice(name)).and_then(|item| {
- match *item {
- Raw(ref raw) => Some(raw.as_slice()),
- _ => None
- }
+ self.data.find(&Slice(name)).map(|item| {
+ item.raw.as_slice()
})
}
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -138,28 +137,29 @@ impl Headers {
pub fn get_ref<H: Header>(&mut self) -> Option<&H> {
self.data.find_mut(&Slice(header_name::<H>())).and_then(|item| {
debug!("get_ref, name={}, val={}", header_name::<H>(), item);
- let header = match *item {
- Raw(ref raw) => match Header::parse_header(raw.as_slice()) {
+ let expected_tid = TypeId::of::<H>();
+ let header = match item.tid {
+ Some(tid) if tid == expected_tid => return Some(item),
+ _ => match Header::parse_header(item.raw.as_slice()) {
Some::<H>(h) => {
h
},
None => return None
},
- Typed(..) => return Some(item)
};
- *item = Typed(box header as Box<Header>);
+ item.typed = Some(box header as Box<Header>);
+ item.tid = Some(expected_tid);
Some(item)
}).and_then(|item| {
debug!("downcasting {}", item);
- let ret = match *item {
- Typed(ref val) => {
+ let ret = match item.typed {
+ Some(ref val) => {
unsafe {
Some(val.downcast_ref_unchecked())
}
},
- Raw(..) => unreachable!()
+ None => unreachable!()
};
- debug!("returning {}", ret.is_some());
ret
})
}
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -238,21 +238,30 @@ impl Mutable for Headers {
}
}
-enum Item {
- Raw(Vec<Vec<u8>>),
- Typed(Box<Header>)
+struct Item {
+ raw: Vec<Vec<u8>>,
+ tid: Option<TypeId>,
+ typed: Option<Box<Header>>,
+}
+
+fn raw(parts: Vec<Vec<u8>>) -> Item {
+ Item {
+ raw: parts,
+ tid: None,
+ typed: None,
+ }
}
impl fmt::Show for Item {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- match *self {
- Raw(ref v) => {
- for part in v.iter() {
+ match self.typed {
+ Some(ref h) => h.fmt_header(fmt),
+ None => {
+ for part in self.raw.iter() {
try!(fmt.write(part.as_slice()));
}
Ok(())
},
- Typed(ref h) => h.fmt_header(fmt)
}
}
}
|
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -260,6 +269,7 @@ impl fmt::Show for Item {
#[cfg(test)]
mod tests {
use std::io::MemReader;
+ use std::fmt;
use mime::{Mime, Text, Plain};
use super::{Headers, Header};
use super::common::{ContentLength, ContentType};
diff --git a/src/header/mod.rs b/src/header/mod.rs
--- a/src/header/mod.rs
+++ b/src/header/mod.rs
@@ -279,4 +289,39 @@ mod tests {
let content_type = Header::parse_header(["text/plain".as_bytes().to_vec()].as_slice());
assert_eq!(content_type, Some(ContentType(Mime(Text, Plain, vec![]))));
}
+
+ #[deriving(Clone)]
+ struct CrazyLength(Option<bool>, uint);
+
+ impl Header for CrazyLength {
+ fn header_name(_: Option<CrazyLength>) -> &'static str {
+ "content-length"
+ }
+ fn parse_header(raw: &[Vec<u8>]) -> Option<CrazyLength> {
+ use std::str::from_utf8;
+ use std::from_str::FromStr;
+
+ if raw.len() != 1 {
+ return None;
+ }
+ // we JUST checked that raw.len() == 1, so raw[0] WILL exist.
+ match from_utf8(unsafe { raw.as_slice().unsafe_get(0).as_slice() }) {
+ Some(s) => FromStr::from_str(s),
+ None => None
+ }.map(|u| CrazyLength(Some(false), u))
+ }
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ use std::fmt::Show;
+ let CrazyLength(_, ref value) = *self;
+ value.fmt(fmt)
+ }
+ }
+
+ #[test]
+ fn test_different_structs_for_same_header() {
+ let mut headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
+ let ContentLength(num) = headers.get::<ContentLength>().unwrap();
+ let CrazyLength(_, crazy_num) = headers.get::<CrazyLength>().unwrap();
+ assert_eq!(num, crazy_num);
+ }
}
|
Using a different Header representation can lead to an illegal transmute
|
The only way around this is to either store the raw representation or store only a single representation and to keep track of what type was used to generate that representation.
|
2014-09-14T17:27:29Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
hyperium/hyper
| 29
|
hyperium__hyper-29
|
[
"5"
] |
4eb48ab7999247f4c696afd2eb105cfa2c6b054b
|
diff --git a/examples/concurrent-server.rs b/examples/concurrent-server.rs
--- a/examples/concurrent-server.rs
+++ b/examples/concurrent-server.rs
@@ -1,4 +1,4 @@
-#![feature(macro_rules)]
+#![feature(macro_rules, default_type_params)]
extern crate hyper;
extern crate debug;
diff --git a/examples/concurrent-server.rs b/examples/concurrent-server.rs
--- a/examples/concurrent-server.rs
+++ b/examples/concurrent-server.rs
@@ -10,6 +10,7 @@ use std::sync::Arc;
use hyper::{Get, Post};
use hyper::server::{Server, Handler, Incoming, Request, Response, Fresh};
use hyper::header::common::ContentLength;
+use hyper::net::{HttpStream, HttpAcceptor};
trait ConcurrentHandler: Send + Sync {
fn handle(&self, req: Request, res: Response<Fresh>);
diff --git a/examples/concurrent-server.rs b/examples/concurrent-server.rs
--- a/examples/concurrent-server.rs
+++ b/examples/concurrent-server.rs
@@ -17,8 +18,8 @@ trait ConcurrentHandler: Send + Sync {
struct Concurrent<H: ConcurrentHandler> { handler: Arc<H> }
-impl<H: ConcurrentHandler> Handler for Concurrent<H> {
- fn handle(self, mut incoming: Incoming) {
+impl<H: ConcurrentHandler> Handler<HttpAcceptor, HttpStream> for Concurrent<H> {
+ fn handle(self, mut incoming: Incoming<HttpAcceptor>) {
for (mut req, mut res) in incoming {
let clone = self.handler.clone();
spawn(proc() { clone.handle(req, res) })
diff --git a/examples/server.rs b/examples/server.rs
--- a/examples/server.rs
+++ b/examples/server.rs
@@ -7,10 +7,8 @@ use std::io::util::copy;
use std::io::net::ip::Ipv4Addr;
use hyper::{Get, Post};
-use hyper::server::{Server, Handler, Incoming};
use hyper::header::common::ContentLength;
-
-struct Echo;
+use hyper::server::{Server, Incoming};
macro_rules! try_continue(
($e:expr) => {{
diff --git a/examples/server.rs b/examples/server.rs
--- a/examples/server.rs
+++ b/examples/server.rs
@@ -21,41 +19,39 @@ macro_rules! try_continue(
}}
)
-impl Handler for Echo {
- fn handle(self, mut incoming: Incoming) {
- for (mut req, mut res) in incoming {
- match req.uri {
- hyper::uri::AbsolutePath(ref path) => match (&req.method, path.as_slice()) {
- (&Get, "/") | (&Get, "/echo") => {
- let out = b"Try POST /echo";
-
- res.headers_mut().set(ContentLength(out.len()));
- let mut res = try_continue!(res.start());
- try_continue!(res.write(out));
- try_continue!(res.end());
- continue;
- },
- (&Post, "/echo") => (), // fall through, fighting mutable borrows
- _ => {
- *res.status_mut() = hyper::status::NotFound;
- try_continue!(res.start().and_then(|res| res.end()));
- continue;
- }
+fn echo(mut incoming: Incoming) {
+ for (mut req, mut res) in incoming {
+ match req.uri {
+ hyper::uri::AbsolutePath(ref path) => match (&req.method, path.as_slice()) {
+ (&Get, "/") | (&Get, "/echo") => {
+ let out = b"Try POST /echo";
+
+ res.headers_mut().set(ContentLength(out.len()));
+ let mut res = try_continue!(res.start());
+ try_continue!(res.write(out));
+ try_continue!(res.end());
+ continue;
},
+ (&Post, "/echo") => (), // fall through, fighting mutable borrows
_ => {
+ *res.status_mut() = hyper::status::NotFound;
try_continue!(res.start().and_then(|res| res.end()));
continue;
}
- };
-
- let mut res = try_continue!(res.start());
- try_continue!(copy(&mut req, &mut res));
- try_continue!(res.end());
- }
+ },
+ _ => {
+ try_continue!(res.start().and_then(|res| res.end()));
+ continue;
+ }
+ };
+
+ let mut res = try_continue!(res.start());
+ try_continue!(copy(&mut req, &mut res));
+ try_continue!(res.end());
}
}
fn main() {
let server = Server::http(Ipv4Addr(127, 0, 0, 1), 1337);
- server.listen(Echo).unwrap();
+ server.listen(echo).unwrap();
}
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -1,5 +1,4 @@
//! Client Requests
-use std::io::net::tcp::TcpStream;
use std::io::{BufferedWriter, IoResult};
use url::Url;
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -7,6 +6,7 @@ use url::Url;
use method;
use header::Headers;
use header::common::Host;
+use net::{NetworkStream, HttpStream};
use rfc7230::LINE_ENDING;
use version;
use {HttpResult, HttpUriError};
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -24,7 +24,7 @@ pub struct Request {
/// The HTTP version of this request.
pub version: version::HttpVersion,
headers_written: bool,
- body: BufferedWriter<TcpStream>,
+ body: BufferedWriter<Box<NetworkStream + Send>>,
}
impl Request {
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -43,8 +43,8 @@ impl Request {
};
debug!("port={}", port);
- let stream = try_io!(TcpStream::connect(host.as_slice(), port));
- let stream = BufferedWriter::new(stream);
+ let stream: HttpStream = try_io!(NetworkStream::connect(host.as_slice(), port));
+ let stream = BufferedWriter::new(stream.abstract());
let mut headers = Headers::new();
headers.set(Host(host));
Ok(Request {
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -84,8 +84,7 @@ impl Request {
/// Consumes the Request.
pub fn send(mut self) -> HttpResult<Response> {
try_io!(self.flush());
- let mut raw = self.body.unwrap();
- try_io!(raw.close_write());
+ let raw = self.body.unwrap();
Response::new(raw)
}
}
diff --git a/src/client/response.rs b/src/client/response.rs
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -1,33 +1,33 @@
//! Client Responses
use std::io::{BufferedReader, IoResult};
-use std::io::net::tcp::TcpStream;
use header;
use header::common::{ContentLength, TransferEncoding};
use header::common::transfer_encoding::Chunked;
+use net::{NetworkStream, HttpStream};
use rfc7230::{read_status_line, HttpReader, SizedReader, ChunkedReader, EofReader};
use status;
use version;
use {HttpResult};
/// A response for a client request to a remote server.
-pub struct Response {
+pub struct Response<S = HttpStream> {
/// The status from the server.
pub status: status::StatusCode,
/// The headers from the server.
pub headers: header::Headers,
/// The HTTP version of this response from the server.
pub version: version::HttpVersion,
- body: HttpReader<BufferedReader<TcpStream>>,
+ body: HttpReader<BufferedReader<Box<NetworkStream + Send>>>,
}
impl Response {
/// Creates a new response from a server.
- pub fn new(tcp: TcpStream) -> HttpResult<Response> {
- let mut tcp = BufferedReader::new(tcp);
- let (version, status) = try!(read_status_line(&mut tcp));
- let mut headers = try!(header::Headers::from_raw(&mut tcp));
+ pub fn new(stream: Box<NetworkStream + Send>) -> HttpResult<Response> {
+ let mut stream = BufferedReader::new(stream.abstract());
+ let (version, status) = try!(read_status_line(&mut stream));
+ let mut headers = try!(header::Headers::from_raw(&mut stream));
debug!("{} {}", version, status);
debug!("{}", headers);
diff --git a/src/client/response.rs b/src/client/response.rs
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -40,22 +40,22 @@ impl Response {
};
if codings.contains(&Chunked) {
- ChunkedReader(tcp, None)
+ ChunkedReader(stream, None)
} else {
- debug!("not chucked. read till eof");
- EofReader(tcp)
+ debug!("not chuncked. read till eof");
+ EofReader(stream)
}
}
None => unreachable!()
}
} else if headers.has::<ContentLength>() {
match headers.get_ref::<ContentLength>() {
- Some(&ContentLength(len)) => SizedReader(tcp, len),
+ Some(&ContentLength(len)) => SizedReader(stream, len),
None => unreachable!()
}
} else {
debug!("neither Transfer-Encoding nor Content-Length");
- EofReader(tcp)
+ EofReader(stream)
};
Ok(Response {
diff --git a/src/client/response.rs b/src/client/response.rs
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -68,6 +68,7 @@ impl Response {
}
impl Reader for Response {
+ #[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
self.body.read(buf)
}
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,6 +1,6 @@
//! # hyper
-#![feature(macro_rules, phase)]
-#![warn(missing_doc)]
+#![feature(macro_rules, phase, default_type_params)]
+#![deny(missing_doc)]
#![deny(warnings)]
#![experimental]
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -53,6 +53,7 @@ macro_rules! trace(
pub mod client;
pub mod method;
pub mod header;
+pub mod net;
pub mod server;
pub mod status;
pub mod uri;
diff --git /dev/null b/src/net.rs
new file mode 100644
--- /dev/null
+++ b/src/net.rs
@@ -0,0 +1,149 @@
+//! A collection of traits abstracting over Listeners and Streams.
+use std::io::{IoResult, Stream, Listener, Acceptor};
+use std::io::net::ip::{SocketAddr, Port};
+use std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor};
+
+/// An abstraction to listen for connections on a certain port.
+pub trait NetworkListener<S: NetworkStream, A: NetworkAcceptor<S>>: Listener<S, A> {
+ /// Bind to a socket.
+ ///
+ /// Note: This does not start listening for connections. You must call
+ /// `listen()` to do that.
+ fn bind(host: &str, port: Port) -> IoResult<Self>;
+
+ /// Get the address this Listener ended up listening on.
+ fn socket_name(&mut self) -> IoResult<SocketAddr>;
+}
+
+/// An abstraction to receive `HttpStream`s.
+pub trait NetworkAcceptor<S: NetworkStream>: Acceptor<S> + Clone + Send {
+ /// Closes the Acceptor, so no more incoming connections will be handled.
+ fn close(&mut self) -> IoResult<()>;
+}
+
+/// An abstraction over streams that a Server can utilize.
+pub trait NetworkStream: Stream + Clone + Send {
+ /// Get the remote address of the underlying connection.
+ fn peer_name(&mut self) -> IoResult<SocketAddr>;
+
+ /// Connect to a remote address.
+ fn connect(host: &str, port: Port) -> IoResult<Self>;
+
+ /// Turn this into an appropriately typed trait object.
+ #[inline]
+ fn abstract(self) -> Box<NetworkStream + Send> {
+ box self as Box<NetworkStream + Send>
+ }
+
+ #[doc(hidden)]
+ #[inline]
+ // Hack to work around lack of Clone impl for Box<Clone>
+ fn clone_box(&self) -> Box<NetworkStream + Send> { self.clone().abstract() }
+}
+
+impl Clone for Box<NetworkStream + Send> {
+ #[inline]
+ fn clone(&self) -> Box<NetworkStream + Send> { self.clone_box() }
+}
+
+impl Reader for Box<NetworkStream + Send> {
+ #[inline]
+ fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.read(buf) }
+}
+
+impl Writer for Box<NetworkStream + Send> {
+ #[inline]
+ fn write(&mut self, msg: &[u8]) -> IoResult<()> { self.write(msg) }
+
+ #[inline]
+ fn flush(&mut self) -> IoResult<()> { self.flush() }
+}
+
+/// A `NetworkListener` for `HttpStream`s.
+pub struct HttpListener {
+ inner: TcpListener
+}
+
+impl Listener<HttpStream, HttpAcceptor> for HttpListener {
+ #[inline]
+ fn listen(self) -> IoResult<HttpAcceptor> {
+ Ok(HttpAcceptor {
+ inner: try!(self.inner.listen())
+ })
+ }
+}
+
+impl NetworkListener<HttpStream, HttpAcceptor> for HttpListener {
+ #[inline]
+ fn bind(host: &str, port: Port) -> IoResult<HttpListener> {
+ Ok(HttpListener {
+ inner: try!(TcpListener::bind(host, port))
+ })
+ }
+
+ #[inline]
+ fn socket_name(&mut self) -> IoResult<SocketAddr> {
+ self.inner.socket_name()
+ }
+}
+
+/// A `NetworkAcceptor` for `HttpStream`s.
+#[deriving(Clone)]
+pub struct HttpAcceptor {
+ inner: TcpAcceptor
+}
+
+impl Acceptor<HttpStream> for HttpAcceptor {
+ #[inline]
+ fn accept(&mut self) -> IoResult<HttpStream> {
+ Ok(HttpStream {
+ inner: try!(self.inner.accept())
+ })
+ }
+}
+
+impl NetworkAcceptor<HttpStream> for HttpAcceptor {
+ #[inline]
+ fn close(&mut self) -> IoResult<()> {
+ self.inner.close_accept()
+ }
+}
+
+/// A wrapper around a TcpStream.
+#[deriving(Clone)]
+pub struct HttpStream {
+ inner: TcpStream
+}
+
+impl Reader for HttpStream {
+ #[inline]
+ fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
+ self.inner.read(buf)
+ }
+}
+
+impl Writer for HttpStream {
+ #[inline]
+ fn write(&mut self, msg: &[u8]) -> IoResult<()> {
+ self.inner.write(msg)
+ }
+ #[inline]
+ fn flush(&mut self) -> IoResult<()> {
+ self.inner.flush()
+ }
+}
+
+
+impl NetworkStream for HttpStream {
+ #[inline]
+ fn peer_name(&mut self) -> IoResult<SocketAddr> {
+ self.inner.peer_name()
+ }
+
+ #[inline]
+ fn connect(host: &str, port: Port) -> IoResult<HttpStream> {
+ Ok(HttpStream {
+ inner: try!(TcpStream::connect(host, port))
+ })
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -1,11 +1,12 @@
//! HTTP Server
-use std::io::net::tcp::{TcpListener, TcpAcceptor};
use std::io::{Acceptor, Listener, IoResult, EndOfFile, IncomingConnections};
use std::io::net::ip::{IpAddr, Port, SocketAddr};
pub use self::request::Request;
pub use self::response::{Response, Fresh, Streaming};
+use net::{NetworkListener, NetworkAcceptor, NetworkStream, HttpAcceptor, HttpListener};
+
pub mod request;
pub mod response;
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -13,32 +14,39 @@ pub mod response;
///
/// Once listening, it will create a `Request`/`Response` pair for each
/// incoming connection, and hand them to the provided handler.
-pub struct Server {
+pub struct Server<L = HttpListener> {
ip: IpAddr,
port: Port
}
-
-impl Server {
-
- /// Creates a server to be used for `http` conenctions.
+impl Server<HttpListener> {
+ /// Creates a new server that will handle `HttpStream`s.
pub fn http(ip: IpAddr, port: Port) -> Server {
Server {
ip: ip,
port: port
}
}
+}
+
+impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L> {
+ /// Creates a server that can listen for and handle `NetworkStreams`.
+ pub fn new(ip: IpAddr, port: Port) -> Server<L> {
+ Server {
+ ip: ip,
+ port: port
+ }
+ }
/// Binds to a socket, and starts handling connections.
- pub fn listen<H: Handler + 'static>(self, handler: H) -> IoResult<Listening> {
- let mut listener = try!(TcpListener::bind(self.ip.to_string().as_slice(), self.port));
+ pub fn listen<H: Handler<A, S>>(self, handler: H) -> IoResult<Listening<A>> {
+ let mut listener: L = try!(NetworkListener::bind(self.ip.to_string().as_slice(), self.port));
let socket = try!(listener.socket_name());
let acceptor = try!(listener.listen());
- let worker = acceptor.clone();
+ let mut worker = acceptor.clone();
spawn(proc() {
- let mut acceptor = worker;
- handler.handle(Incoming { from: acceptor.incoming() });
+ handler.handle(Incoming { from: worker.incoming() });
});
Ok(Listening {
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -51,11 +59,11 @@ impl Server {
/// An iterator over incoming connections, represented as pairs of
/// hyper Requests and Responses.
-pub struct Incoming<'a> {
- from: IncomingConnections<'a, TcpAcceptor>
+pub struct Incoming<'a, A: 'a = HttpAcceptor> {
+ from: IncomingConnections<'a, A>
}
-impl<'a> Iterator<(Request, Response<Fresh>)> for Incoming<'a> {
+impl<'a, S: NetworkStream, A: NetworkAcceptor<S>> Iterator<(Request, Response<Fresh>)> for Incoming<'a, A> {
fn next(&mut self) -> Option<(Request, Response<Fresh>)> {
for conn in self.from {
match conn {
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -85,30 +93,30 @@ impl<'a> Iterator<(Request, Response<Fresh>)> for Incoming<'a> {
}
/// A listening server, which can later be closed.
-pub struct Listening {
- acceptor: TcpAcceptor,
+pub struct Listening<A> {
+ acceptor: A,
/// The socket address that the server is bound to.
pub socket_addr: SocketAddr,
}
-impl Listening {
- /// Stop the server from listening to its socket address.
+impl<A: NetworkAcceptor<S>, S: NetworkStream> Listening<A> {
+ /// Stop the server from listening to it's socket address.
pub fn close(mut self) -> IoResult<()> {
debug!("closing server");
- self.acceptor.close_accept()
+ self.acceptor.close()
}
}
/// A handler that can handle incoming requests for a server.
-pub trait Handler: Send {
+pub trait Handler<A: NetworkAcceptor<S>, S: NetworkStream>: Send {
/// Receives a `Request`/`Response` pair, and should perform some action on them.
///
/// This could reading from the request, and writing to the response.
- fn handle(self, Incoming);
+ fn handle(self, Incoming<A>);
}
-impl Handler for fn(Incoming) {
- fn handle(self, incoming: Incoming) {
+impl<A: NetworkAcceptor<S>, S: NetworkStream> Handler<A, S> for fn(Incoming<A>) {
+ fn handle(self, incoming: Incoming<A>) {
(self)(incoming)
}
}
diff --git a/src/server/request.rs b/src/server/request.rs
--- a/src/server/request.rs
+++ b/src/server/request.rs
@@ -4,7 +4,6 @@
//! target URI, headers, and message body.
use std::io::{Reader, BufferedReader, IoResult};
use std::io::net::ip::SocketAddr;
-use std::io::net::tcp::TcpStream;
use {HttpResult};
use version::{HttpVersion};
diff --git a/src/server/request.rs b/src/server/request.rs
--- a/src/server/request.rs
+++ b/src/server/request.rs
@@ -13,9 +12,10 @@ use header::Headers;
use header::common::ContentLength;
use rfc7230::{read_request_line};
use rfc7230::{HttpReader, SizedReader, ChunkedReader};
+use net::NetworkStream;
use uri::RequestUri;
-/// A request bundles several parts of an incoming TCP stream, given to a `Handler`.
+/// A request bundles several parts of an incoming `NetworkStream`, given to a `Handler`.
pub struct Request {
/// The IP address of the remote connection.
pub remote_addr: SocketAddr,
diff --git a/src/server/request.rs b/src/server/request.rs
--- a/src/server/request.rs
+++ b/src/server/request.rs
@@ -27,7 +27,7 @@ pub struct Request {
pub uri: RequestUri,
/// The version of HTTP for this request.
pub version: HttpVersion,
- body: HttpReader<BufferedReader<TcpStream>>
+ body: HttpReader<BufferedReader<Box<NetworkStream + Send>>>
}
diff --git a/src/server/request.rs b/src/server/request.rs
--- a/src/server/request.rs
+++ b/src/server/request.rs
@@ -35,11 +35,11 @@ impl Request {
/// Create a new Request, reading the StartLine and Headers so they are
/// immediately useful.
- pub fn new(mut tcp: TcpStream) -> HttpResult<Request> {
- let remote_addr = try_io!(tcp.peer_name());
- let mut tcp = BufferedReader::new(tcp);
- let (method, uri, version) = try!(read_request_line(&mut tcp));
- let mut headers = try!(Headers::from_raw(&mut tcp));
+ pub fn new<S: NetworkStream>(mut stream: S) -> HttpResult<Request> {
+ let remote_addr = try_io!(stream.peer_name());
+ let mut stream = BufferedReader::new(stream.abstract());
+ let (method, uri, version) = try!(read_request_line(&mut stream));
+ let mut headers = try!(Headers::from_raw(&mut stream));
debug!("{} {} {}", method, uri, version);
debug!("{}", headers);
diff --git a/src/server/request.rs b/src/server/request.rs
--- a/src/server/request.rs
+++ b/src/server/request.rs
@@ -47,12 +47,12 @@ impl Request {
let body = if headers.has::<ContentLength>() {
match headers.get_ref::<ContentLength>() {
- Some(&ContentLength(len)) => SizedReader(tcp, len),
+ Some(&ContentLength(len)) => SizedReader(stream, len),
None => unreachable!()
}
} else {
todo!("check for Transfer-Encoding: chunked");
- ChunkedReader(tcp, None)
+ ChunkedReader(stream, None)
};
Ok(Request {
diff --git a/src/server/request.rs b/src/server/request.rs
--- a/src/server/request.rs
+++ b/src/server/request.rs
@@ -61,7 +61,7 @@ impl Request {
uri: uri,
headers: headers,
version: version,
- body: body,
+ body: body
})
}
}
diff --git a/src/server/response.rs b/src/server/response.rs
--- a/src/server/response.rs
+++ b/src/server/response.rs
@@ -3,15 +3,15 @@
//! These are responses sent by a `hyper::Server` to clients, after
//! receiving a request.
use std::io::{BufferedWriter, IoResult};
-use std::io::net::tcp::TcpStream;
use time::now_utc;
use header;
use header::common;
+use rfc7230::{CR, LF, LINE_ENDING};
use status;
+use net::NetworkStream;
use version;
-use rfc7230::{CR, LF, LINE_ENDING};
/// Phantom type indicating Headers and StatusCode have not been written.
pub struct Fresh;
diff --git a/src/server/response.rs b/src/server/response.rs
--- a/src/server/response.rs
+++ b/src/server/response.rs
@@ -30,7 +30,7 @@ pub struct Response<W: WriteStatus> {
/// The HTTP version of this response.
pub version: version::HttpVersion,
// Stream the Response is writing to, not accessible through UnwrittenResponse
- body: BufferedWriter<TcpStream>, // TODO: use a HttpWriter from rfc7230
+ body: BufferedWriter<Box<NetworkStream + Send>>, // TODO: use a HttpWriter from rfc7230
// The status code for the request.
status: status::StatusCode,
// The outgoing headers on this response.
diff --git a/src/server/response.rs b/src/server/response.rs
--- a/src/server/response.rs
+++ b/src/server/response.rs
@@ -47,7 +47,7 @@ impl<W: WriteStatus> Response<W> {
/// Construct a Response from its constituent parts.
pub fn construct(version: version::HttpVersion,
- body: BufferedWriter<TcpStream>,
+ body: BufferedWriter<Box<NetworkStream + Send>>,
status: status::StatusCode,
headers: header::Headers) -> Response<Fresh> {
Response {
diff --git a/src/server/response.rs b/src/server/response.rs
--- a/src/server/response.rs
+++ b/src/server/response.rs
@@ -61,12 +61,12 @@ impl<W: WriteStatus> Response<W> {
impl Response<Fresh> {
/// Creates a new Response that can be used to write to a network stream.
- pub fn new(tcp: TcpStream) -> Response<Fresh> {
+ pub fn new<S: NetworkStream>(stream: S) -> Response<Fresh> {
Response {
status: status::Ok,
version: version::Http11,
headers: header::Headers::new(),
- body: BufferedWriter::new(tcp)
+ body: BufferedWriter::new(stream.abstract())
}
}
diff --git a/src/server/response.rs b/src/server/response.rs
--- a/src/server/response.rs
+++ b/src/server/response.rs
@@ -104,7 +104,8 @@ impl Response<Fresh> {
pub fn headers_mut(&mut self) -> &mut header::Headers { &mut self.headers }
/// Deconstruct this Response into its constituent parts.
- pub fn deconstruct(self) -> (version::HttpVersion, BufferedWriter<TcpStream>, status::StatusCode, header::Headers) {
+ pub fn deconstruct(self) -> (version::HttpVersion, BufferedWriter<Box<NetworkStream + Send>>,
+ status::StatusCode, header::Headers) {
(self.version, self.body, self.status, self.headers)
}
}
|
diff --git a/benches/client.rs b/benches/client.rs
--- a/benches/client.rs
+++ b/benches/client.rs
@@ -8,8 +8,9 @@ extern crate test;
use std::fmt::{mod, Show};
use std::io::net::ip::Ipv4Addr;
use hyper::server::{Incoming, Server};
+use hyper::net::HttpAcceptor;
-fn listen() -> hyper::server::Listening {
+fn listen() -> hyper::server::Listening<HttpAcceptor> {
let server = Server::http(Ipv4Addr(127, 0, 0, 1), 0);
server.listen(handle).unwrap()
}
|
Mocking Request and Response
There should be some way to mock Request and Response for testing. Right now, since they contain explicit references to TcpStreams, this is very difficult. This is solvable by creating a trait that abstracts the functionality you need from TCPStream, but this may mean incurring the cost of dynamic dispatch.
|
2014-09-09T21:32:22Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
|
hyperium/hyper
| 25
|
hyperium__hyper-25
|
[
"7"
] |
8e95d4bc42e47ff40df8221bdc4f121f6c1f6084
|
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,6 +13,12 @@ git = "https://github.com/seanmonstar/mime.rs"
[dependencies.unsafe-any]
git = "https://github.com/reem/rust-unsafe-any"
+[dependencies.intertwine]
+git = "https://github.com/reem/rust-intertwine"
+
+[dependencies.move-acceptor]
+git = "https://github.com/reem/rust-move-acceptor"
+
[dev-dependencies.curl]
git = "https://github.com/carllerche/curl-rust"
diff --git a/benches/server.rs b/benches/server.rs
--- a/benches/server.rs
+++ b/benches/server.rs
@@ -28,9 +28,9 @@ fn hyper_handle(mut incoming: hyper::server::Incoming) {
#[bench]
fn bench_hyper(b: &mut Bencher) {
let server = hyper::Server::http(Ipv4Addr(127, 0, 0, 1), 0);
- let listener = server.listen(hyper_handle).unwrap();
+ let mut listener = server.listen(hyper_handle).unwrap();
- let url = hyper::Url::parse(format!("http://{}", listener.socket_addr).as_slice()).unwrap();
+ let url = hyper::Url::parse(format!("http://{}", listener.sockets[0]).as_slice()).unwrap();
b.iter(|| request(url.clone()));
listener.close().unwrap();
}
diff --git a/examples/concurrent-server.rs b/examples/concurrent-server.rs
--- a/examples/concurrent-server.rs
+++ b/examples/concurrent-server.rs
@@ -19,7 +19,7 @@ trait ConcurrentHandler: Send + Sync {
struct Concurrent<H: ConcurrentHandler> { handler: Arc<H> }
impl<H: ConcurrentHandler> Handler<HttpAcceptor, HttpStream> for Concurrent<H> {
- fn handle(self, mut incoming: Incoming<HttpAcceptor>) {
+ fn handle(self, mut incoming: Incoming) {
for (mut req, mut res) in incoming {
let clone = self.handler.clone();
spawn(proc() { clone.handle(req, res) })
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -1,11 +1,16 @@
//! HTTP Server
-use std::io::{Acceptor, Listener, IoResult, EndOfFile, IncomingConnections};
+use std::io::{Listener, IoResult, EndOfFile};
use std::io::net::ip::{IpAddr, Port, SocketAddr};
+use intertwine::{Intertwine, Intertwined};
+use macceptor::MoveAcceptor;
+
pub use self::request::Request;
pub use self::response::{Response, Fresh, Streaming};
-use net::{NetworkListener, NetworkAcceptor, NetworkStream, HttpAcceptor, HttpListener};
+use net::{NetworkListener, NetworkAcceptor, NetworkStream, HttpAcceptor, HttpListener, HttpStream};
+
+use {HttpResult};
pub mod request;
pub mod response;
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -15,55 +20,79 @@ pub mod response;
/// Once listening, it will create a `Request`/`Response` pair for each
/// incoming connection, and hand them to the provided handler.
pub struct Server<L = HttpListener> {
- ip: IpAddr,
- port: Port
+ pairs: Vec<(IpAddr, Port)>
}
+macro_rules! try_option(
+ ($e:expr) => {{
+ match $e {
+ Some(v) => v,
+ None => return None
+ }
+ }}
+)
+
impl Server<HttpListener> {
/// Creates a new server that will handle `HttpStream`s.
pub fn http(ip: IpAddr, port: Port) -> Server {
- Server {
- ip: ip,
- port: port
- }
+ Server { pairs: vec![(ip, port)] }
+ }
+
+ /// Creates a server that can listen to many (ip, port) pairs.
+ pub fn many(pairs: Vec<(IpAddr, Port)>) -> Server {
+ Server { pairs: pairs }
}
}
impl<L: NetworkListener<S, A>, S: NetworkStream, A: NetworkAcceptor<S>> Server<L> {
- /// Creates a server that can listen for and handle `NetworkStreams`.
- pub fn new(ip: IpAddr, port: Port) -> Server<L> {
- Server {
- ip: ip,
- port: port
+ /// Binds to a socket, and starts handling connections.
+ ///
+ /// 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<H, S, A, L>(self, handler: H) -> HttpResult<Listening<A>>
+ where H: Handler<A, S>,
+ S: NetworkStream,
+ A: NetworkAcceptor<S>,
+ L: NetworkListener<S, A>, {
+ let mut acceptors = Vec::new();
+ let mut sockets = Vec::new();
+ for (ip, port) in self.pairs.move_iter() {
+ let mut listener: L = try_io!(NetworkListener::<S, A>::bind(ip.to_string().as_slice(), port));
+
+ sockets.push(try_io!(listener.socket_name()));
+
+ let acceptor = try_io!(listener.listen());
+ acceptors.push(acceptor.clone());
}
- }
- /// Binds to a socket, and starts handling connections.
- pub fn listen<H: Handler<A, S>>(self, handler: H) -> IoResult<Listening<A>> {
- let mut listener: L = try!(NetworkListener::bind(self.ip.to_string().as_slice(), self.port));
- let socket = try!(listener.socket_name());
- let acceptor = try!(listener.listen());
- let mut worker = acceptor.clone();
+ let connections = acceptors.clone()
+ .move_iter()
+ .map(|acceptor| acceptor.move_incoming())
+ .intertwine();
spawn(proc() {
- handler.handle(Incoming { from: worker.incoming() });
+ handler.handle(Incoming { from: connections });
});
Ok(Listening {
- acceptor: acceptor,
- socket_addr: socket,
+ acceptors: acceptors,
+ sockets: sockets,
})
}
+ /// Binds to a socket and starts handling connections.
+ pub fn listen<H: Handler<HttpAcceptor, HttpStream>>(self, handler: H) -> HttpResult<Listening<HttpAcceptor>> {
+ self.listen_network::<H, HttpStream, HttpAcceptor, HttpListener>(handler)
+ }
}
/// An iterator over incoming connections, represented as pairs of
/// hyper Requests and Responses.
-pub struct Incoming<'a, A: 'a = HttpAcceptor> {
- from: IncomingConnections<'a, A>
+pub struct Incoming<S: Send = HttpStream> {
+ from: Intertwined<IoResult<S>>
}
-impl<'a, S: NetworkStream, A: NetworkAcceptor<S>> Iterator<(Request, Response<Fresh>)> for Incoming<'a, A> {
+impl<S: NetworkStream + 'static> Iterator<(Request, Response<Fresh>)> for Incoming<S> {
fn next(&mut self) -> Option<(Request, Response<Fresh>)> {
for conn in self.from {
match conn {
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -93,17 +122,23 @@ impl<'a, S: NetworkStream, A: NetworkAcceptor<S>> Iterator<(Request, Response<Fr
}
/// A listening server, which can later be closed.
-pub struct Listening<A> {
- acceptor: A,
- /// The socket address that the server is bound to.
- pub socket_addr: SocketAddr,
+pub struct Listening<A = HttpAcceptor> {
+ acceptors: Vec<A>,
+ /// The socket addresses that the server is bound to.
+ pub sockets: Vec<SocketAddr>,
}
impl<A: NetworkAcceptor<S>, S: NetworkStream> Listening<A> {
- /// Stop the server from listening to it's socket address.
- pub fn close(mut self) -> IoResult<()> {
+ /// Stop the server from listening to all of its socket addresses.
+ ///
+ /// If closing any of the servers acceptors fails, this function returns Err
+ /// and does not close the rest of the acceptors.
+ pub fn close(&mut self) -> HttpResult<()> {
debug!("closing server");
- self.acceptor.close()
+ for acceptor in self.acceptors.mut_iter() {
+ try_io!(acceptor.close());
+ }
+ Ok(())
}
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -112,11 +147,11 @@ pub trait Handler<A: NetworkAcceptor<S>, S: NetworkStream>: Send {
/// Receives a `Request`/`Response` pair, and should perform some action on them.
///
/// This could reading from the request, and writing to the response.
- fn handle(self, Incoming<A>);
+ fn handle(self, Incoming<S>);
}
-impl<A: NetworkAcceptor<S>, S: NetworkStream> Handler<A, S> for fn(Incoming<A>) {
- fn handle(self, incoming: Incoming<A>) {
+impl<A: NetworkAcceptor<S>, S: NetworkStream> Handler<A, S> for fn(Incoming<S>) {
+ fn handle(self, incoming: Incoming<S>) {
(self)(incoming)
}
}
|
diff --git a/benches/client.rs b/benches/client.rs
--- a/benches/client.rs
+++ b/benches/client.rs
@@ -8,9 +8,8 @@ extern crate test;
use std::fmt::{mod, Show};
use std::io::net::ip::Ipv4Addr;
use hyper::server::{Incoming, Server};
-use hyper::net::HttpAcceptor;
-fn listen() -> hyper::server::Listening<HttpAcceptor> {
+fn listen() -> hyper::server::Listening {
let server = Server::http(Ipv4Addr(127, 0, 0, 1), 0);
server.listen(handle).unwrap()
}
diff --git a/benches/client.rs b/benches/client.rs
--- a/benches/client.rs
+++ b/benches/client.rs
@@ -34,8 +33,8 @@ fn handle(mut incoming: Incoming) {
#[bench]
fn bench_curl(b: &mut test::Bencher) {
- let listening = listen();
- let s = format!("http://{}/", listening.socket_addr);
+ let mut listening = listen();
+ let s = format!("http://{}/", listening.sockets[0]);
let url = s.as_slice();
b.iter(|| {
curl::http::handle()
diff --git a/benches/client.rs b/benches/client.rs
--- a/benches/client.rs
+++ b/benches/client.rs
@@ -63,24 +62,24 @@ impl hyper::header::Header for Foo {
#[bench]
fn bench_hyper(b: &mut test::Bencher) {
- let listening = listen();
- let s = format!("http://{}/", listening.socket_addr);
+ let mut listening = listen();
+ let s = format!("http://{}/", listening.sockets[0]);
let url = s.as_slice();
b.iter(|| {
let mut req = hyper::get(hyper::Url::parse(url).unwrap()).unwrap();
req.headers.set(Foo);
- req
- .send().unwrap()
- .read_to_string().unwrap()
+ req
+ .send().unwrap()
+ .read_to_string().unwrap()
});
- listening.close().unwrap()
+listening.close().unwrap()
}
#[bench]
fn bench_http(b: &mut test::Bencher) {
- let listening = listen();
- let s = format!("http://{}/", listening.socket_addr);
+ let mut listening = listen();
+ let s = format!("http://{}/", listening.sockets[0]);
let url = s.as_slice();
b.iter(|| {
let mut req: http::client::RequestWriter = http::client::RequestWriter::new(
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -9,6 +9,8 @@ extern crate url;
#[phase(plugin,link)] extern crate log;
#[cfg(test)] extern crate test;
extern crate "unsafe-any" as uany;
+extern crate "move-acceptor" as macceptor;
+extern crate intertwine;
pub use std::io::net::ip::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr, Port};
pub use mimewrapper::mime;
|
Change Server to allow multiple listens from the same Handler
Related to #4, as this will necessitate a slightly different handling of Handler.
I should be able to instantiate a Server with a single handler, then make that server listen on multiple ports, all without reconstructing the handler multiple times.
|
2014-09-09T03:36:52Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
|
hyperium/hyper
| 20
|
hyperium__hyper-20
|
[
"8"
] |
fd6b014e7e40d686121b5cdf63818878d4bf2ce2
|
diff --git a/examples/server.rs b/examples/server.rs
--- a/examples/server.rs
+++ b/examples/server.rs
@@ -8,7 +8,7 @@ use std::io::net::ip::Ipv4Addr;
use hyper::{Get, Post};
use hyper::server::{Server, Handler, Incoming};
-use hyper::header::ContentLength;
+use hyper::header::common::ContentLength;
struct Echo;
diff --git a/src/client/request.rs b/src/client/request.rs
--- a/src/client/request.rs
+++ b/src/client/request.rs
@@ -5,7 +5,8 @@ use std::io::{BufferedWriter, IoResult};
use url::Url;
use method;
-use header::{Headers, Host};
+use header::Headers;
+use header::common::Host;
use rfc7230::LINE_ENDING;
use version;
use {HttpResult, HttpUriError};
diff --git a/src/client/response.rs b/src/client/response.rs
--- a/src/client/response.rs
+++ b/src/client/response.rs
@@ -2,7 +2,9 @@
use std::io::{BufferedReader, IoResult};
use std::io::net::tcp::TcpStream;
-use header::{mod, ContentLength, TransferEncoding, Chunked};
+use header;
+use header::common::{ContentLength, TransferEncoding};
+use header::common::transfer_encoding::Chunked;
use rfc7230::{read_status_line, HttpReader, SizedReader, ChunkedReader, EofReader};
use status;
use version;
diff --git /dev/null b/src/header/common/accept.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/accept.rs
@@ -0,0 +1,44 @@
+use header::Header;
+use std::fmt::{mod, Show};
+use mime::Mime;
+
+/// The `Accept` header.
+///
+/// The `Accept` header is used to tell a server which content-types the client
+/// is capable of using. It can be a comma-separated list of `Mime`s, and the
+/// priority can be indicated with a `q` parameter.
+///
+/// Example:
+///
+/// ```
+/// # use hyper::header::Headers;
+/// # use hyper::header::common::Accept;
+/// use hyper::mime::{Mime, Text, Html, Xml};
+/// # let mut headers = Headers::new();
+/// headers.set(Accept(vec![ Mime(Text, Html, vec![]), Mime(Text, Xml, vec![]) ]));
+/// ```
+#[deriving(Clone, PartialEq, Show)]
+pub struct Accept(pub Vec<Mime>);
+
+impl Header for Accept {
+ fn header_name(_: Option<Accept>) -> &'static str {
+ "accept"
+ }
+
+ fn parse_header(_raw: &[Vec<u8>]) -> Option<Accept> {
+ unimplemented!()
+ }
+
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ let Accept(ref value) = *self;
+ let last = value.len() - 1;
+ for (i, mime) in value.iter().enumerate() {
+ try!(mime.fmt(fmt));
+ if i < last {
+ try!(", ".fmt(fmt));
+ }
+ }
+ Ok(())
+ }
+}
+
diff --git /dev/null b/src/header/common/connection.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/connection.rs
@@ -0,0 +1,45 @@
+use header::Header;
+use std::fmt::{mod, Show};
+use super::from_one_raw_str;
+use std::from_str::FromStr;
+
+/// The `Connection` header.
+///
+/// Describes whether the socket connection should be closed or reused after
+/// this request/response is completed.
+#[deriving(Clone, PartialEq, Show)]
+pub enum Connection {
+ /// The `keep-alive` connection value.
+ KeepAlive,
+ /// The `close` connection value.
+ Close
+}
+
+impl FromStr for Connection {
+ fn from_str(s: &str) -> Option<Connection> {
+ debug!("Connection::from_str =? {}", s);
+ match s {
+ "keep-alive" => Some(KeepAlive),
+ "close" => Some(Close),
+ _ => None
+ }
+ }
+}
+
+impl Header for Connection {
+ fn header_name(_: Option<Connection>) -> &'static str {
+ "connection"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<Connection> {
+ from_one_raw_str(raw)
+ }
+
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ KeepAlive => "keep-alive",
+ Close => "close",
+ }.fmt(fmt)
+ }
+}
+
diff --git /dev/null b/src/header/common/content_length.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/content_length.rs
@@ -0,0 +1,25 @@
+use header::Header;
+use std::fmt::{mod, Show};
+use super::from_one_raw_str;
+
+/// The `Content-Length` header.
+///
+/// Simply a wrapper around a `uint`.
+#[deriving(Clone, PartialEq, Show)]
+pub struct ContentLength(pub uint);
+
+impl Header for ContentLength {
+ fn header_name(_: Option<ContentLength>) -> &'static str {
+ "content-length"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<ContentLength> {
+ from_one_raw_str(raw).map(|u| ContentLength(u))
+ }
+
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ let ContentLength(ref value) = *self;
+ value.fmt(fmt)
+ }
+}
+
diff --git /dev/null b/src/header/common/content_type.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/content_type.rs
@@ -0,0 +1,27 @@
+use header::Header;
+use std::fmt::{mod, Show};
+use super::from_one_raw_str;
+use mime::Mime;
+
+/// The `Content-Type` header.
+///
+/// Used to describe the MIME type of message body. Can be used with both
+/// requests and responses.
+#[deriving(Clone, PartialEq, Show)]
+pub struct ContentType(pub Mime);
+
+impl Header for ContentType {
+ fn header_name(_: Option<ContentType>) -> &'static str {
+ "content-type"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<ContentType> {
+ from_one_raw_str(raw).map(|mime| ContentType(mime))
+ }
+
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ let ContentType(ref value) = *self;
+ value.fmt(fmt)
+ }
+}
+
diff --git /dev/null b/src/header/common/date.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/date.rs
@@ -0,0 +1,66 @@
+use header::Header;
+use std::fmt::{mod, Show};
+use super::from_one_raw_str;
+use std::from_str::FromStr;
+use time::{Tm, strptime};
+
+// Egh, replace as soon as something better than time::Tm exists.
+/// The `Date` header field.
+#[deriving(PartialEq, Clone)]
+pub struct Date(pub Tm);
+
+impl Header for Date {
+ fn header_name(_: Option<Date>) -> &'static str {
+ "date"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<Date> {
+ from_one_raw_str(raw)
+ }
+
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ self.fmt(fmt)
+ }
+}
+
+impl fmt::Show for Date {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ let Date(ref tm) = *self;
+ // bummer that tm.strftime allocates a string. It would nice if it
+ // returned a Show instead, since I don't need the String here
+ write!(fmt, "{}", tm.to_utc().rfc822())
+ }
+}
+
+impl FromStr for Date {
+ // Prior to 1995, there were three different formats commonly used by
+ // servers to communicate timestamps. For compatibility with old
+ // implementations, all three are defined here. The preferred format is
+ // a fixed-length and single-zone subset of the date and time
+ // specification used by the Internet Message Format [RFC5322].
+ //
+ // HTTP-date = IMF-fixdate / obs-date
+ //
+ // An example of the preferred format is
+ //
+ // Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate
+ //
+ // Examples of the two obsolete formats are
+ //
+ // Sunday, 06-Nov-94 08:49:37 GMT ; obsolete RFC 850 format
+ // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
+ //
+ // A recipient that parses a timestamp value in an HTTP header field
+ // MUST accept all three HTTP-date formats. When a sender generates a
+ // header field that contains one or more timestamps defined as
+ // HTTP-date, the sender MUST generate those timestamps in the
+ // IMF-fixdate format.
+ fn from_str(s: &str) -> Option<Date> {
+ strptime(s, "%a, %d %b %Y %T %Z").or_else(|_| {
+ strptime(s, "%A, %d-%b-%y %T %Z")
+ }).or_else(|_| {
+ strptime(s, "%c")
+ }).ok().map(|tm| Date(tm))
+ }
+}
+
diff --git /dev/null b/src/header/common/host.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/host.rs
@@ -0,0 +1,29 @@
+use header::Header;
+use std::fmt::{mod, Show};
+use super::from_one_raw_str;
+
+/// The `Host` header.
+///
+/// HTTP/1.1 requires that all requests include a `Host` header, and so hyper
+/// client requests add one automatically.
+///
+/// Currently is just a String, but it should probably become a better type,
+/// like url::Host or something.
+#[deriving(Clone, PartialEq, Show)]
+pub struct Host(pub String);
+
+impl Header for Host {
+ fn header_name(_: Option<Host>) -> &'static str {
+ "host"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<Host> {
+ from_one_raw_str(raw).map(|s| Host(s))
+ }
+
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ let Host(ref value) = *self;
+ value.fmt(fmt)
+ }
+}
+
diff --git /dev/null b/src/header/common/mod.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/mod.rs
@@ -0,0 +1,59 @@
+//! A Collection of Header implementations for common HTTP Headers.
+//!
+//! ## Mime
+//!
+//! Several header fields use MIME values for their contents. Keeping with the
+//! strongly-typed theme, the [mime](http://seanmonstar.github.io/mime.rs) crate
+//! is used, such as `ContentType(pub Mime)`.
+
+pub use self::host::Host;
+pub use self::content_length::ContentLength;
+pub use self::content_type::ContentType;
+pub use self::accept::Accept;
+pub use self::connection::Connection;
+pub use self::transfer_encoding::TransferEncoding;
+pub use self::user_agent::UserAgent;
+pub use self::server::Server;
+pub use self::date::Date;
+
+use std::from_str::FromStr;
+use std::str::from_utf8;
+
+/// Exposes the Host header.
+pub mod host;
+
+/// Exposes the ContentLength header.
+pub mod content_length;
+
+/// Exposes the ContentType header.
+pub mod content_type;
+
+/// Exposes the Accept header.
+pub mod accept;
+
+/// Exposes the Connection header.
+pub mod connection;
+
+/// Exposes the TransferEncoding header.
+pub mod transfer_encoding;
+
+/// Exposes the UserAgent header.
+pub mod user_agent;
+
+/// Exposes the Server header.
+pub mod server;
+
+/// Exposes the Date header.
+pub mod date;
+
+fn from_one_raw_str<T: FromStr>(raw: &[Vec<u8>]) -> Option<T> {
+ if raw.len() != 1 {
+ return None;
+ }
+ // we JUST checked that raw.len() == 1, so raw[0] WILL exist.
+ match from_utf8(unsafe { raw.as_slice().unsafe_get(0).as_slice() }) {
+ Some(s) => FromStr::from_str(s),
+ None => None
+ }
+}
+
diff --git /dev/null b/src/header/common/server.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/server.rs
@@ -0,0 +1,25 @@
+use header::Header;
+use std::fmt::{mod, Show};
+use super::from_one_raw_str;
+
+/// The `Server` header field.
+///
+/// They can contain any value, so it just wraps a `String`.
+#[deriving(Clone, PartialEq, Show)]
+pub struct Server(pub String);
+
+impl Header for Server {
+ fn header_name(_: Option<Server>) -> &'static str {
+ "server"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<Server> {
+ from_one_raw_str(raw).map(|s| Server(s))
+ }
+
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ let Server(ref value) = *self;
+ value.fmt(fmt)
+ }
+}
+
diff --git /dev/null b/src/header/common/transfer_encoding.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/transfer_encoding.rs
@@ -0,0 +1,89 @@
+use header::Header;
+use std::fmt::{mod, Show};
+use std::from_str::FromStr;
+use std::str::from_utf8;
+
+/// The `Transfer-Encoding` header.
+///
+/// This header describes the encoding of the message body. It can be
+/// comma-separated, including multiple encodings.
+///
+/// ```notrust
+/// Transfer-Encoding: gzip, chunked
+/// ```
+///
+/// According to the spec, if a `Content-Length` header is not included,
+/// this header should include `chunked` as the last encoding.
+///
+/// The implementation uses a vector of `Encoding` values.
+#[deriving(Clone, PartialEq, Show)]
+pub struct TransferEncoding(pub Vec<Encoding>);
+
+/// A value to be used with the `Transfer-Encoding` header.
+///
+/// Example:
+///
+/// ```
+/// # use hyper::header::common::transfer_encoding::{TransferEncoding, Gzip, Chunked};
+/// # use hyper::header::Headers;
+/// # let mut headers = Headers::new();
+/// headers.set(TransferEncoding(vec![Gzip, Chunked]));
+#[deriving(Clone, PartialEq, Show)]
+pub enum Encoding {
+ /// The `chunked` encoding.
+ Chunked,
+
+ // TODO: #2 implement this in `HttpReader`.
+ /// The `gzip` encoding.
+ Gzip,
+ /// The `deflate` encoding.
+ Deflate,
+ /// The `compress` encoding.
+ Compress,
+ /// Some other encoding that is less common, can be any String.
+ EncodingExt(String)
+}
+
+impl FromStr for Encoding {
+ fn from_str(s: &str) -> Option<Encoding> {
+ match s {
+ "chunked" => Some(Chunked),
+ _ => None
+ }
+ }
+}
+
+impl Header for TransferEncoding {
+ fn header_name(_: Option<TransferEncoding>) -> &'static str {
+ "transfer-encoding"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<TransferEncoding> {
+ if raw.len() != 1 {
+ return None;
+ }
+ // we JUST checked that raw.len() == 1, so raw[0] WILL exist.
+ match from_utf8(unsafe { raw.as_slice().unsafe_get(0).as_slice() }) {
+ Some(s) => {
+ Some(TransferEncoding(s.as_slice()
+ .split([',', ' '].as_slice())
+ .filter_map(from_str)
+ .collect()))
+ }
+ None => None
+ }
+ }
+
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ let TransferEncoding(ref parts) = *self;
+ let last = parts.len() - 1;
+ for (i, part) in parts.iter().enumerate() {
+ try!(part.fmt(fmt));
+ if i < last {
+ try!(", ".fmt(fmt));
+ }
+ }
+ Ok(())
+ }
+}
+
diff --git /dev/null b/src/header/common/user_agent.rs
new file mode 100644
--- /dev/null
+++ b/src/header/common/user_agent.rs
@@ -0,0 +1,25 @@
+use header::Header;
+use std::fmt::{mod, Show};
+use super::from_one_raw_str;
+
+/// The `User-Agent` header field.
+///
+/// They can contain any value, so it just wraps a `String`.
+#[deriving(Clone, PartialEq, Show)]
+pub struct UserAgent(pub String);
+
+impl Header for UserAgent {
+ fn header_name(_: Option<UserAgent>) -> &'static str {
+ "user-agent"
+ }
+
+ fn parse_header(raw: &[Vec<u8>]) -> Option<UserAgent> {
+ from_one_raw_str(raw).map(|s| UserAgent(s))
+ }
+
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ let UserAgent(ref value) = *self;
+ value.fmt(fmt)
+ }
+}
+
diff --git a/src/server/request.rs b/src/server/request.rs
--- a/src/server/request.rs
+++ b/src/server/request.rs
@@ -9,7 +9,8 @@ use std::io::net::tcp::TcpStream;
use {HttpResult};
use version::{HttpVersion};
use method;
-use header::{Headers, ContentLength};
+use header::Headers;
+use header::common::ContentLength;
use rfc7230::{read_request_line};
use rfc7230::{HttpReader, SizedReader, ChunkedReader};
use uri::RequestUri;
diff --git a/src/server/response.rs b/src/server/response.rs
--- a/src/server/response.rs
+++ b/src/server/response.rs
@@ -8,6 +8,7 @@ use std::io::net::tcp::TcpStream;
use time::now_utc;
use header;
+use header::common;
use status;
use version;
use rfc7230::{CR, LF, LINE_ENDING};
diff --git a/src/server/response.rs b/src/server/response.rs
--- a/src/server/response.rs
+++ b/src/server/response.rs
@@ -48,8 +49,8 @@ impl Response {
debug!("writing head: {} {}", self.version, self.status);
try!(write!(self.body, "{} {}{}{}", self.version, self.status, CR as char, LF as char));
- if !self.headers.has::<header::Date>() {
- self.headers.set(header::Date(now_utc()));
+ if !self.headers.has::<common::Date>() {
+ self.headers.set(common::Date(now_utc()));
}
for (name, header) in self.headers.iter() {
|
diff --git a/src/header.rs /dev/null
--- a/src/header.rs
+++ /dev/null
@@ -1,631 +0,0 @@
-//! Headers container, and common header fields.
-//!
-//! hyper has the opinion that Headers should be strongly-typed, because that's
-//! why we're using Rust in the first place. To set or get any header, an object
-//! must implement the `Header` trait from this module. Several common headers
-//! are already provided, such as `Host`, `ContentType`, `UserAgent`, and others.
-//!
-//! ## Mime
-//!
-//! Several header fields use MIME values for their contents. Keeping with the
-//! strongly-typed theme, the [mime](http://seanmonstar.github.io/mime.rs) crate
-//! is used, such as `ContentType(pub Mime)`.
-use std::ascii::OwnedAsciiExt;
-use std::char::is_lowercase;
-use std::fmt::{mod, Show};
-use std::from_str::{FromStr, from_str};
-use std::mem::{transmute, transmute_copy};
-use std::raw::TraitObject;
-use std::str::{from_utf8, SendStr, Slice, Owned};
-use std::string::raw;
-use std::collections::hashmap::{HashMap, Entries};
-
-use mime::Mime;
-use time::{Tm, strptime};
-use uany::UncheckedAnyDowncast;
-
-use rfc7230::read_header;
-use {HttpResult};
-
-/// A trait for any object that will represent a header field and value.
-pub trait Header: 'static {
- /// Returns the name of the header field this belongs to.
- ///
- /// The market `Option` is to hint to the type system which implementation
- /// to call. This can be done away with once UFCS arrives.
- fn header_name(marker: Option<Self>) -> &'static str;
- /// Parse a header from a raw stream of bytes.
- ///
- /// It's possible that a request can include a header field more than once,
- /// and in that case, the slice will have a length greater than 1. However,
- /// it's not necessarily the case that a Header is *allowed* to have more
- /// than one field value. If that's the case, you **should** return `None`
- /// if `raw.len() > 1`.
- fn parse_header(raw: &[Vec<u8>]) -> Option<Self>;
- /// Format a header to be output into a TcpStream.
- fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result;
-}
-
-impl<'a> UncheckedAnyDowncast<'a> for &'a Header + 'a {
- #[inline]
- unsafe fn downcast_ref_unchecked<T: 'static>(self) -> &'a T {
- let to: TraitObject = transmute_copy(&self);
- transmute(to.data)
- }
-}
-
-fn header_name<T: Header>() -> &'static str {
- let name = Header::header_name(None::<T>);
- debug_assert!(name.as_slice().chars().all(|c| c == '-' || is_lowercase(c)),
- "Header names should be lowercase: {}", name);
- name
-}
-
-/// A map of header fields on requests and responses.
-pub struct Headers {
- data: HashMap<SendStr, Item>
-}
-
-impl Headers {
-
- /// Creates a new, empty headers map.
- pub fn new() -> Headers {
- Headers {
- data: HashMap::new()
- }
- }
-
- #[doc(hidden)]
- pub fn from_raw<R: Reader>(rdr: &mut R) -> HttpResult<Headers> {
- let mut headers = Headers::new();
- loop {
- match try!(read_header(rdr)) {
- Some((name, value)) => {
- // read_header already checks that name is a token, which
- // means its safe utf8
- let name = unsafe {
- raw::from_utf8(name)
- }.into_ascii_lower();
- match headers.data.find_or_insert(Owned(name), Raw(vec![])) {
- &Raw(ref mut pieces) => pieces.push(value),
- // at this point, Raw is the only thing that has been inserted
- _ => unreachable!()
- }
- },
- None => break,
- }
- }
- Ok(headers)
- }
-
- /// Set a header field to the corresponding value.
- ///
- /// The field is determined by the type of the value being set.
- pub fn set<H: Header>(&mut self, value: H) {
- self.data.insert(Slice(header_name::<H>()), Typed(box value));
- }
-
- /// Get a clone of the header field's value, if it exists.
- ///
- /// Example:
- ///
- /// ```
- /// # use hyper::header::{Headers, ContentType};
- /// # let mut headers = Headers::new();
- /// let content_type = headers.get::<ContentType>();
- /// ```
- pub fn get<H: Header + Clone>(&mut self) -> Option<H> {
- self.get_ref().map(|v: &H| v.clone())
- }
-
- /// Access the raw value of a header, if it exists and has not
- /// been already parsed.
- ///
- /// If the header field has already been parsed into a typed header,
- /// then you *must* access it through that representation.
- ///
- /// Example:
- /// ```
- /// # use hyper::header::{Headers, ContentType};
- /// # let mut headers = Headers::new();
- /// let raw_content_type = unsafe { headers.get_raw("content-type") };
- /// ```
- pub unsafe fn get_raw(&self, name: &'static str) -> Option<&[Vec<u8>]> {
- self.data.find(&Slice(name)).and_then(|item| {
- match *item {
- Raw(ref raw) => Some(raw.as_slice()),
- _ => None
- }
- })
- }
-
- /// Get a reference to the header field's value, if it exists.
- pub fn get_ref<H: Header>(&mut self) -> Option<&H> {
- self.data.find_mut(&Slice(header_name::<H>())).and_then(|item| {
- debug!("get_ref, name={}, val={}", header_name::<H>(), item);
- let header = match *item {
- Raw(ref raw) => match Header::parse_header(raw.as_slice()) {
- Some::<H>(h) => {
- h
- },
- None => return None
- },
- Typed(..) => return Some(item)
- };
- *item = Typed(box header as Box<Header>);
- Some(item)
- }).and_then(|item| {
- debug!("downcasting {}", item);
- let ret = match *item {
- Typed(ref val) => {
- unsafe {
- Some(val.downcast_ref_unchecked())
- }
- },
- Raw(..) => unreachable!()
- };
- debug!("returning {}", ret.is_some());
- ret
- })
- }
-
- /// Returns a boolean of whether a certain header is in the map.
- ///
- /// Example:
- ///
- /// ```
- /// # use hyper::header::{Headers, ContentType};
- /// # let mut headers = Headers::new();
- /// let has_type = headers.has::<ContentType>();
- /// ```
- pub fn has<H: Header>(&self) -> bool {
- self.data.contains_key(&Slice(header_name::<H>()))
- }
-
- /// Removes a header from the map, if one existed.
- /// Returns true if a header has been removed.
- pub fn remove<H: Header>(&mut self) -> bool {
- self.data.pop_equiv(&Header::header_name(None::<H>)).is_some()
- }
-
- /// Returns an iterator over the header fields.
- pub fn iter<'a>(&'a self) -> HeadersItems<'a> {
- HeadersItems {
- inner: self.data.iter()
- }
- }
-}
-
-impl fmt::Show for Headers {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- try!("Headers {\n".fmt(fmt));
- for (k, v) in self.iter() {
- try!(write!(fmt, "\t{}: {}\n", k, v));
- }
- "}".fmt(fmt)
- }
-}
-
-/// An `Iterator` over the fields in a `Headers` map.
-pub struct HeadersItems<'a> {
- inner: Entries<'a, SendStr, Item>
-}
-
-impl<'a> Iterator<(&'a str, HeaderView<'a>)> for HeadersItems<'a> {
- fn next(&mut self) -> Option<(&'a str, HeaderView<'a>)> {
- match self.inner.next() {
- Some((k, v)) => Some((k.as_slice(), HeaderView(v))),
- None => None
- }
- }
-}
-
-/// Returned with the `HeadersItems` iterator.
-pub struct HeaderView<'a>(&'a Item);
-
-impl<'a> fmt::Show for HeaderView<'a> {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- let HeaderView(item) = *self;
- item.fmt(fmt)
- }
-}
-
-impl Collection for Headers {
- fn len(&self) -> uint {
- self.data.len()
- }
-}
-
-impl Mutable for Headers {
- fn clear(&mut self) {
- self.data.clear()
- }
-}
-
-enum Item {
- Raw(Vec<Vec<u8>>),
- Typed(Box<Header>)
-}
-
-impl fmt::Show for Item {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- match *self {
- Raw(ref v) => {
- for part in v.iter() {
- try!(fmt.write(part.as_slice()));
- }
- Ok(())
- },
- Typed(ref h) => h.fmt_header(fmt)
- }
- }
-}
-
-
-// common headers
-
-/// The `Host` header.
-///
-/// HTTP/1.1 requires that all requests include a `Host` header, and so hyper
-/// client requests add one automatically.
-///
-/// Currently is just a String, but it should probably become a better type,
-/// like url::Host or something.
-#[deriving(Clone, PartialEq, Show)]
-pub struct Host(pub String);
-
-impl Header for Host {
- fn header_name(_: Option<Host>) -> &'static str {
- "host"
- }
-
- fn parse_header(raw: &[Vec<u8>]) -> Option<Host> {
- from_one_raw_str(raw).map(|s| Host(s))
- }
-
- fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- let Host(ref value) = *self;
- value.fmt(fmt)
- }
-}
-
-/// The `Content-Length` header.
-///
-/// Simply a wrapper around a `uint`.
-#[deriving(Clone, PartialEq, Show)]
-pub struct ContentLength(pub uint);
-
-impl Header for ContentLength {
- fn header_name(_: Option<ContentLength>) -> &'static str {
- "content-length"
- }
-
- fn parse_header(raw: &[Vec<u8>]) -> Option<ContentLength> {
- from_one_raw_str(raw).map(|u| ContentLength(u))
- }
-
- fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- let ContentLength(ref value) = *self;
- value.fmt(fmt)
- }
-}
-
-/// The `Content-Type` header.
-///
-/// Used to describe the MIME type of message body. Can be used with both
-/// requests and responses.
-#[deriving(Clone, PartialEq, Show)]
-pub struct ContentType(pub Mime);
-
-impl Header for ContentType {
- fn header_name(_: Option<ContentType>) -> &'static str {
- "content-type"
- }
-
- fn parse_header(raw: &[Vec<u8>]) -> Option<ContentType> {
- from_one_raw_str(raw).map(|mime| ContentType(mime))
- }
-
- fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- let ContentType(ref value) = *self;
- value.fmt(fmt)
- }
-}
-
-/// The `Accept` header.
-///
-/// The `Accept` header is used to tell a server which content-types the client
-/// is capable of using. It can be a comma-separated list of `Mime`s, and the
-/// priority can be indicated with a `q` parameter.
-///
-/// Example:
-///
-/// ```
-/// # use hyper::header::{Headers, Accept};
-/// use hyper::mime::{Mime, Text, Html, Xml};
-/// # let mut headers = Headers::new();
-/// headers.set(Accept(vec![ Mime(Text, Html, vec![]), Mime(Text, Xml, vec![]) ]));
-/// ```
-#[deriving(Clone, PartialEq, Show)]
-pub struct Accept(pub Vec<Mime>);
-
-impl Header for Accept {
- fn header_name(_: Option<Accept>) -> &'static str {
- "accept"
- }
-
- fn parse_header(_raw: &[Vec<u8>]) -> Option<Accept> {
- unimplemented!()
- }
-
- fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- let Accept(ref value) = *self;
- let last = value.len() - 1;
- for (i, mime) in value.iter().enumerate() {
- try!(mime.fmt(fmt));
- if i < last {
- try!(", ".fmt(fmt));
- }
- }
- Ok(())
- }
-}
-
-/// The `Connection` header.
-///
-/// Describes whether the socket connection should be closed or reused after
-/// this request/response is completed.
-#[deriving(Clone, PartialEq, Show)]
-pub enum Connection {
- /// The `keep-alive` connection value.
- KeepAlive,
- /// The `close` connection value.
- Close
-}
-
-impl FromStr for Connection {
- fn from_str(s: &str) -> Option<Connection> {
- debug!("Connection::from_str =? {}", s);
- match s {
- "keep-alive" => Some(KeepAlive),
- "close" => Some(Close),
- _ => None
- }
- }
-}
-
-impl Header for Connection {
- fn header_name(_: Option<Connection>) -> &'static str {
- "connection"
- }
-
- fn parse_header(raw: &[Vec<u8>]) -> Option<Connection> {
- from_one_raw_str(raw)
- }
-
- fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- match *self {
- KeepAlive => "keep-alive",
- Close => "close",
- }.fmt(fmt)
- }
-}
-
-/// The `Transfer-Encoding` header.
-///
-/// This header describes the encoding of the message body. It can be
-/// comma-separated, including multiple encodings.
-///
-/// ```notrust
-/// Transfer-Encoding: gzip, chunked
-/// ```
-///
-/// According to the spec, if a `Content-Length` header is not included,
-/// this header should include `chunked` as the last encoding.
-///
-/// The implementation uses a vector of `Encoding` values.
-#[deriving(Clone, PartialEq, Show)]
-pub struct TransferEncoding(pub Vec<Encoding>);
-
-/// A value to be used with the `Transfer-Encoding` header.
-///
-/// Example:
-///
-/// ```
-/// # use hyper::header::{Headers, TransferEncoding, Gzip, Chunked};
-/// # let mut headers = Headers::new();
-/// headers.set(TransferEncoding(vec![Gzip, Chunked]));
-#[deriving(Clone, PartialEq, Show)]
-pub enum Encoding {
- /// The `chunked` encoding.
- Chunked,
-
- // TODO: #2 implement this in `HttpReader`.
- /// The `gzip` encoding.
- Gzip,
- /// The `deflate` encoding.
- Deflate,
- /// The `compress` encoding.
- Compress,
- /// Some other encoding that is less common, can be any String.
- EncodingExt(String)
-}
-
-impl FromStr for Encoding {
- fn from_str(s: &str) -> Option<Encoding> {
- match s {
- "chunked" => Some(Chunked),
- _ => None
- }
- }
-}
-
-impl Header for TransferEncoding {
- fn header_name(_: Option<TransferEncoding>) -> &'static str {
- "transfer-encoding"
- }
-
- fn parse_header(raw: &[Vec<u8>]) -> Option<TransferEncoding> {
- if raw.len() != 1 {
- return None;
- }
- // we JUST checked that raw.len() == 1, so raw[0] WILL exist.
- match from_utf8(unsafe { raw.as_slice().unsafe_get(0).as_slice() }) {
- Some(s) => {
- Some(TransferEncoding(s.as_slice()
- .split([',', ' '].as_slice())
- .filter_map(from_str)
- .collect()))
- }
- None => None
- }
- }
-
- fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- let TransferEncoding(ref parts) = *self;
- let last = parts.len() - 1;
- for (i, part) in parts.iter().enumerate() {
- try!(part.fmt(fmt));
- if i < last {
- try!(", ".fmt(fmt));
- }
- }
- Ok(())
- }
-}
-
-/// The `User-Agent` header field.
-///
-/// They can contain any value, so it just wraps a `String`.
-#[deriving(Clone, PartialEq, Show)]
-pub struct UserAgent(pub String);
-
-impl Header for UserAgent {
- fn header_name(_: Option<UserAgent>) -> &'static str {
- "user-agent"
- }
-
- fn parse_header(raw: &[Vec<u8>]) -> Option<UserAgent> {
- from_one_raw_str(raw).map(|s| UserAgent(s))
- }
-
- fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- let UserAgent(ref value) = *self;
- value.fmt(fmt)
- }
-}
-
-/// The `Server` header field.
-///
-/// They can contain any value, so it just wraps a `String`.
-#[deriving(Clone, PartialEq, Show)]
-pub struct Server(pub String);
-
-impl Header for Server {
- fn header_name(_: Option<Server>) -> &'static str {
- "server"
- }
-
- fn parse_header(raw: &[Vec<u8>]) -> Option<Server> {
- from_one_raw_str(raw).map(|s| Server(s))
- }
-
- fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- let Server(ref value) = *self;
- value.fmt(fmt)
- }
-}
-
-// Egh, replace as soon as something better than time::Tm exists.
-/// The `Date` header field.
-#[deriving(PartialEq, Clone)]
-pub struct Date(pub Tm);
-
-impl Header for Date {
- fn header_name(_: Option<Date>) -> &'static str {
- "date"
- }
-
- fn parse_header(raw: &[Vec<u8>]) -> Option<Date> {
- from_one_raw_str(raw)
- }
-
- fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- self.fmt(fmt)
- }
-}
-
-impl fmt::Show for Date {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- let Date(ref tm) = *self;
- // bummer that tm.strftime allocates a string. It would nice if it
- // returned a Show instead, since I don't need the String here
- write!(fmt, "{}", tm.to_utc().rfc822())
- }
-}
-
-impl FromStr for Date {
- // Prior to 1995, there were three different formats commonly used by
- // servers to communicate timestamps. For compatibility with old
- // implementations, all three are defined here. The preferred format is
- // a fixed-length and single-zone subset of the date and time
- // specification used by the Internet Message Format [RFC5322].
- //
- // HTTP-date = IMF-fixdate / obs-date
- //
- // An example of the preferred format is
- //
- // Sun, 06 Nov 1994 08:49:37 GMT ; IMF-fixdate
- //
- // Examples of the two obsolete formats are
- //
- // Sunday, 06-Nov-94 08:49:37 GMT ; obsolete RFC 850 format
- // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
- //
- // A recipient that parses a timestamp value in an HTTP header field
- // MUST accept all three HTTP-date formats. When a sender generates a
- // header field that contains one or more timestamps defined as
- // HTTP-date, the sender MUST generate those timestamps in the
- // IMF-fixdate format.
- fn from_str(s: &str) -> Option<Date> {
- strptime(s, "%a, %d %b %Y %T %Z").or_else(|_| {
- strptime(s, "%A, %d-%b-%y %T %Z")
- }).or_else(|_| {
- strptime(s, "%c")
- }).ok().map(|tm| Date(tm))
- }
-}
-
-fn from_one_raw_str<T: FromStr>(raw: &[Vec<u8>]) -> Option<T> {
- if raw.len() != 1 {
- return None;
- }
- // we JUST checked that raw.len() == 1, so raw[0] WILL exist.
- match from_utf8(unsafe { raw.as_slice().unsafe_get(0).as_slice() }) {
- Some(s) => FromStr::from_str(s),
- None => None
- }
-}
-
-#[cfg(test)]
-mod tests {
- use std::io::MemReader;
- use mime::{Mime, Text, Plain};
- use super::{Headers, Header, ContentLength, ContentType};
-
- fn mem(s: &str) -> MemReader {
- MemReader::new(s.as_bytes().to_vec())
- }
-
- #[test]
- fn test_from_raw() {
- let mut headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
- assert_eq!(headers.get_ref(), Some(&ContentLength(10)));
- }
-
- #[test]
- fn test_content_type() {
- let content_type = Header::parse_header(["text/plain".as_bytes().to_vec()].as_slice());
- assert_eq!(content_type, Some(ContentType(Mime(Text, Plain, vec![]))));
- }
-}
diff --git /dev/null b/src/header/mod.rs
new file mode 100644
--- /dev/null
+++ b/src/header/mod.rs
@@ -0,0 +1,282 @@
+//! Headers container, and common header fields.
+//!
+//! hyper has the opinion that Headers should be strongly-typed, because that's
+//! why we're using Rust in the first place. To set or get any header, an object
+//! must implement the `Header` trait from this module. Several common headers
+//! are already provided, such as `Host`, `ContentType`, `UserAgent`, and others.
+use std::ascii::OwnedAsciiExt;
+use std::char::is_lowercase;
+use std::fmt::{mod, Show};
+use std::mem::{transmute, transmute_copy};
+use std::raw::TraitObject;
+use std::str::{from_utf8, SendStr, Slice, Owned};
+use std::string::raw;
+use std::collections::hashmap::{HashMap, Entries};
+
+use uany::UncheckedAnyDowncast;
+
+use rfc7230::read_header;
+use {HttpResult};
+
+/// Common Headers
+pub mod common;
+
+/// A trait for any object that will represent a header field and value.
+pub trait Header: 'static {
+ /// Returns the name of the header field this belongs to.
+ ///
+ /// The market `Option` is to hint to the type system which implementation
+ /// to call. This can be done away with once UFCS arrives.
+ fn header_name(marker: Option<Self>) -> &'static str;
+ /// Parse a header from a raw stream of bytes.
+ ///
+ /// It's possible that a request can include a header field more than once,
+ /// and in that case, the slice will have a length greater than 1. However,
+ /// it's not necessarily the case that a Header is *allowed* to have more
+ /// than one field value. If that's the case, you **should** return `None`
+ /// if `raw.len() > 1`.
+ fn parse_header(raw: &[Vec<u8>]) -> Option<Self>;
+ /// Format a header to be output into a TcpStream.
+ fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result;
+}
+
+impl<'a> UncheckedAnyDowncast<'a> for &'a Header + 'a {
+ #[inline]
+ unsafe fn downcast_ref_unchecked<T: 'static>(self) -> &'a T {
+ let to: TraitObject = transmute_copy(&self);
+ transmute(to.data)
+ }
+}
+
+fn header_name<T: Header>() -> &'static str {
+ let name = Header::header_name(None::<T>);
+ debug_assert!(name.as_slice().chars().all(|c| c == '-' || is_lowercase(c)),
+ "Header names should be lowercase: {}", name);
+ name
+}
+
+/// A map of header fields on requests and responses.
+pub struct Headers {
+ data: HashMap<SendStr, Item>
+}
+
+impl Headers {
+
+ /// Creates a new, empty headers map.
+ pub fn new() -> Headers {
+ Headers {
+ data: HashMap::new()
+ }
+ }
+
+ #[doc(hidden)]
+ pub fn from_raw<R: Reader>(rdr: &mut R) -> HttpResult<Headers> {
+ let mut headers = Headers::new();
+ loop {
+ match try!(read_header(rdr)) {
+ Some((name, value)) => {
+ // read_header already checks that name is a token, which
+ // means its safe utf8
+ let name = unsafe {
+ raw::from_utf8(name)
+ }.into_ascii_lower();
+ match headers.data.find_or_insert(Owned(name), Raw(vec![])) {
+ &Raw(ref mut pieces) => pieces.push(value),
+ // at this point, Raw is the only thing that has been inserted
+ _ => unreachable!()
+ }
+ },
+ None => break,
+ }
+ }
+ Ok(headers)
+ }
+
+ /// Set a header field to the corresponding value.
+ ///
+ /// The field is determined by the type of the value being set.
+ pub fn set<H: Header>(&mut self, value: H) {
+ self.data.insert(Slice(header_name::<H>()), Typed(box value));
+ }
+
+ /// Get a clone of the header field's value, if it exists.
+ ///
+ /// Example:
+ ///
+ /// ```
+ /// # use hyper::header::Headers;
+ /// # use hyper::header::common::ContentType;
+ /// # let mut headers = Headers::new();
+ /// let content_type = headers.get::<ContentType>();
+ /// ```
+ pub fn get<H: Header + Clone>(&mut self) -> Option<H> {
+ self.get_ref().map(|v: &H| v.clone())
+ }
+
+ /// Access the raw value of a header, if it exists and has not
+ /// been already parsed.
+ ///
+ /// If the header field has already been parsed into a typed header,
+ /// then you *must* access it through that representation.
+ ///
+ /// Example:
+ /// ```
+ /// # use hyper::header::Headers;
+ /// # let mut headers = Headers::new();
+ /// let raw_content_type = unsafe { headers.get_raw("content-type") };
+ /// ```
+ pub unsafe fn get_raw(&self, name: &'static str) -> Option<&[Vec<u8>]> {
+ self.data.find(&Slice(name)).and_then(|item| {
+ match *item {
+ Raw(ref raw) => Some(raw.as_slice()),
+ _ => None
+ }
+ })
+ }
+
+ /// Get a reference to the header field's value, if it exists.
+ pub fn get_ref<H: Header>(&mut self) -> Option<&H> {
+ self.data.find_mut(&Slice(header_name::<H>())).and_then(|item| {
+ debug!("get_ref, name={}, val={}", header_name::<H>(), item);
+ let header = match *item {
+ Raw(ref raw) => match Header::parse_header(raw.as_slice()) {
+ Some::<H>(h) => {
+ h
+ },
+ None => return None
+ },
+ Typed(..) => return Some(item)
+ };
+ *item = Typed(box header as Box<Header>);
+ Some(item)
+ }).and_then(|item| {
+ debug!("downcasting {}", item);
+ let ret = match *item {
+ Typed(ref val) => {
+ unsafe {
+ Some(val.downcast_ref_unchecked())
+ }
+ },
+ Raw(..) => unreachable!()
+ };
+ debug!("returning {}", ret.is_some());
+ ret
+ })
+ }
+
+ /// Returns a boolean of whether a certain header is in the map.
+ ///
+ /// Example:
+ ///
+ /// ```
+ /// # use hyper::header::Headers;
+ /// # use hyper::header::common::ContentType;
+ /// # let mut headers = Headers::new();
+ /// let has_type = headers.has::<ContentType>();
+ /// ```
+ pub fn has<H: Header>(&self) -> bool {
+ self.data.contains_key(&Slice(header_name::<H>()))
+ }
+
+ /// Removes a header from the map, if one existed.
+ /// Returns true if a header has been removed.
+ pub fn remove<H: Header>(&mut self) -> bool {
+ self.data.pop_equiv(&Header::header_name(None::<H>)).is_some()
+ }
+
+ /// Returns an iterator over the header fields.
+ pub fn iter<'a>(&'a self) -> HeadersItems<'a> {
+ HeadersItems {
+ inner: self.data.iter()
+ }
+ }
+}
+
+impl fmt::Show for Headers {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ try!("Headers {\n".fmt(fmt));
+ for (k, v) in self.iter() {
+ try!(write!(fmt, "\t{}: {}\n", k, v));
+ }
+ "}".fmt(fmt)
+ }
+}
+
+/// An `Iterator` over the fields in a `Headers` map.
+pub struct HeadersItems<'a> {
+ inner: Entries<'a, SendStr, Item>
+}
+
+impl<'a> Iterator<(&'a str, HeaderView<'a>)> for HeadersItems<'a> {
+ fn next(&mut self) -> Option<(&'a str, HeaderView<'a>)> {
+ match self.inner.next() {
+ Some((k, v)) => Some((k.as_slice(), HeaderView(v))),
+ None => None
+ }
+ }
+}
+
+/// Returned with the `HeadersItems` iterator.
+pub struct HeaderView<'a>(&'a Item);
+
+impl<'a> fmt::Show for HeaderView<'a> {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ let HeaderView(item) = *self;
+ item.fmt(fmt)
+ }
+}
+
+impl Collection for Headers {
+ fn len(&self) -> uint {
+ self.data.len()
+ }
+}
+
+impl Mutable for Headers {
+ fn clear(&mut self) {
+ self.data.clear()
+ }
+}
+
+enum Item {
+ Raw(Vec<Vec<u8>>),
+ Typed(Box<Header>)
+}
+
+impl fmt::Show for Item {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ Raw(ref v) => {
+ for part in v.iter() {
+ try!(fmt.write(part.as_slice()));
+ }
+ Ok(())
+ },
+ Typed(ref h) => h.fmt_header(fmt)
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::io::MemReader;
+ use mime::{Mime, Text, Plain};
+ use super::{Headers, Header};
+ use super::common::{ContentLength, ContentType};
+
+ fn mem(s: &str) -> MemReader {
+ MemReader::new(s.as_bytes().to_vec())
+ }
+
+ #[test]
+ fn test_from_raw() {
+ let mut headers = Headers::from_raw(&mut mem("Content-Length: 10\r\n\r\n")).unwrap();
+ assert_eq!(headers.get_ref(), Some(&ContentLength(10)));
+ }
+
+ #[test]
+ fn test_content_type() {
+ let content_type = Header::parse_header(["text/plain".as_bytes().to_vec()].as_slice());
+ assert_eq!(content_type, Some(ContentType(Mime(Text, Plain, vec![]))));
+ }
+}
|
Common headers should go in their own submodules
Instead of being inlined in hyper/header.rs
Since it is very unergonomic to use a Header if it is not implemented, it's also important that basically all common headers have to be implemented here.
|
2014-09-08T23:20:46Z
|
0.0
|
27b262c22678ed785ed269da4f4a4ddc154526d1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.