Skip to content

Commit

Permalink
Now using use along with enums, as per rust-lang/rust#18973.
Browse files Browse the repository at this point in the history
  • Loading branch information
kyledewey authored and jgillich committed Nov 19, 2014
1 parent 7e55506 commit d7e8b8b
Show file tree
Hide file tree
Showing 13 changed files with 90 additions and 56 deletions.
17 changes: 10 additions & 7 deletions src/client/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ use std::io::{BufferedWriter, IoResult};

use url::Url;

use method::{mod, Get, Post, Delete, Put, Patch, Head, Options};
use method;
use method::Method::{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, EmptyWriter, LINE_ENDING};
use HttpError::HttpUriError;
use http::{HttpWriter, LINE_ENDING};
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
use version;
use {HttpResult, HttpUriError};
use HttpResult;
use client::Response;


Expand Down Expand Up @@ -69,7 +72,7 @@ impl Request<Fresh> {
method: method,
headers: headers,
url: url,
version: version::Http11,
version: version::HttpVersion::Http11,
body: stream
})
}
Expand Down Expand Up @@ -141,15 +144,15 @@ impl Request<Fresh> {
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.push(common::transfer_encoding::Encoding::Chunked);
false
},
None => true
};

if encodings {
self.headers.set::<common::TransferEncoding>(
common::TransferEncoding(vec![common::transfer_encoding::Chunked]))
common::TransferEncoding(vec![common::transfer_encoding::Encoding::Chunked]))
}
}

Expand Down Expand Up @@ -206,7 +209,7 @@ mod tests {
use std::boxed::BoxAny;
use std::str::from_utf8;
use url::Url;
use method::{Get, Head};
use method::Method::{Get, Head};
use mock::MockStream;
use super::Request;

Expand Down
13 changes: 7 additions & 6 deletions src/client/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ use std::io::{BufferedReader, IoResult};

use header;
use header::common::{ContentLength, TransferEncoding};
use header::common::transfer_encoding::Chunked;
use header::common::transfer_encoding::Encoding::Chunked;
use net::{NetworkStream, HttpStream};
use http::{read_status_line, HttpReader, SizedReader, ChunkedReader, EofReader};
use http::{read_status_line, HttpReader};
use http::HttpReader::{SizedReader, ChunkedReader, EofReader};
use status;
use version;
use {HttpResult};
use HttpResult;

/// A response for a client request to a remote server.
pub struct Response<S = HttpStream> {
Expand Down Expand Up @@ -85,7 +86,7 @@ mod tests {
use std::io::BufferedReader;

use header::Headers;
use http::EofReader;
use http::HttpReader::EofReader;
use mock::MockStream;
use net::NetworkStream;
use status;
Expand All @@ -97,9 +98,9 @@ mod tests {
#[test]
fn test_unwrap() {
let res = Response {
status: status::Ok,
status: status::StatusCode::Ok,
headers: Headers::new(),
version: version::Http11,
version: version::HttpVersion::Http11,
body: EofReader(BufferedReader::new(box MockStream::new() as Box<NetworkStream + Send>))
};

Expand Down
2 changes: 2 additions & 0 deletions src/header/common/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use std::fmt::{mod, Show};
use std::str::FromStr;
use super::util::{from_comma_delimited, fmt_comma_delimited};

use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader};

/// The `Connection` header.
#[deriving(Clone, PartialEq, Show)]
pub struct Connection(pub Vec<ConnectionOption>);
Expand Down
3 changes: 2 additions & 1 deletion src/header/common/transfer_encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use std::fmt;
use std::str::FromStr;
use super::util::{from_comma_delimited, fmt_comma_delimited};

use self::Encoding::{Chunked, Gzip, Deflate, Compress, EncodingExt};

/// The `Transfer-Encoding` header.
///
/// This header describes the encoding of the message body. It can be
Expand Down Expand Up @@ -32,7 +34,6 @@ pub struct TransferEncoding(pub Vec<Encoding>);
pub enum Encoding {
/// The `chunked` encoding.
Chunked,

/// The `gzip` encoding.
Gzip,
/// The `deflate` encoding.
Expand Down
2 changes: 2 additions & 0 deletions src/header/common/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use std::fmt::{mod, Show};
use std::str::FromStr;
use super::util::{from_comma_delimited, fmt_comma_delimited};

use self::Protocol::{WebSocket, ProtocolExt};

/// The `Upgrade` header.
#[deriving(Clone, PartialEq, Show)]
pub struct Upgrade(Vec<Protocol>);
Expand Down
75 changes: 42 additions & 33 deletions src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,15 @@ use url::Url;
use method;
use status;
use uri;
use version::{HttpVersion, Http09, Http10, Http11, Http20};
use {HttpResult, HttpMethodError, HttpVersionError, HttpIoError, HttpUriError};
use {HttpHeaderError, HttpStatusError};
use uri::RequestUri::{AbsolutePath, AbsoluteUri, Authority, Star};
use version::HttpVersion;
use version::HttpVersion::{Http09, Http10, Http11, Http20};
use HttpError::{HttpHeaderError, HttpIoError, HttpMethodError, HttpStatusError,
HttpUriError, HttpVersionError};
use HttpResult;

use self::HttpReader::{SizedReader, ChunkedReader, EofReader};
use self::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};

/// Readers to handle different Transfer-Encodings.
///
Expand Down Expand Up @@ -327,15 +333,15 @@ pub fn read_method<R: Reader>(stream: &mut R) -> HttpResult<method::Method> {
debug!("method buf = {}", buf[].to_ascii());

let maybe_method = match buf[0..7] {
b"GET " => Some(method::Get),
b"PUT " => Some(method::Put),
b"POST " => Some(method::Post),
b"HEAD " => Some(method::Head),
b"PATCH " => Some(method::Patch),
b"TRACE " => Some(method::Trace),
b"DELETE " => Some(method::Delete),
b"CONNECT" => Some(method::Connect),
b"OPTIONS" => Some(method::Options),
b"GET " => Some(method::Method::Get),
b"PUT " => Some(method::Method::Put),
b"POST " => Some(method::Method::Post),
b"HEAD " => Some(method::Method::Head),
b"PATCH " => Some(method::Method::Patch),
b"TRACE " => Some(method::Method::Trace),
b"DELETE " => Some(method::Method::Delete),
b"CONNECT" => Some(method::Method::Connect),
b"OPTIONS" => Some(method::Method::Options),
_ => None,
};

Expand All @@ -346,7 +352,7 @@ pub fn read_method<R: Reader>(stream: &mut R) -> HttpResult<method::Method> {
(None, ext) if is_valid_method(buf) => {
use std::str::raw;
// We already checked that the buffer is ASCII
Ok(method::Extension(unsafe { raw::from_utf8(ext) }.trim().into_string()))
Ok(method::Method::Extension(unsafe { raw::from_utf8(ext) }.trim().into_string()))
},
_ => Err(HttpMethodError)
}
Expand All @@ -367,7 +373,7 @@ pub fn read_uri<R: Reader>(stream: &mut R) -> HttpResult<uri::RequestUri> {
let mut s = String::new();
if b == STAR {
try!(expect(stream.read_byte(), SP));
return Ok(uri::Star)
return Ok(Star)
} else {
s.push(b as char);
loop {
Expand All @@ -386,10 +392,10 @@ pub fn read_uri<R: Reader>(stream: &mut R) -> HttpResult<uri::RequestUri> {
debug!("uri buf = {}", s);

if s.as_slice().starts_with("/") {
Ok(uri::AbsolutePath(s))
Ok(AbsolutePath(s))
} else if s.as_slice().contains("/") {
match Url::parse(s.as_slice()) {
Ok(u) => Ok(uri::AbsoluteUri(u)),
Ok(u) => Ok(AbsoluteUri(u)),
Err(_e) => {
debug!("URL err {}", _e);
Err(HttpUriError)
Expand All @@ -401,7 +407,7 @@ pub fn read_uri<R: Reader>(stream: &mut R) -> HttpResult<uri::RequestUri> {
match Url::parse(temp.as_slice()) {
Ok(_u) => {
todo!("compare vs u.authority()");
Ok(uri::Authority(s))
Ok(Authority(s))
}
Err(_e) => {
debug!("URL err {}", _e);
Expand Down Expand Up @@ -608,11 +614,14 @@ fn expect(r: IoResult<u8>, expected: u8) -> HttpResult<()> {
mod tests {
use std::io::{mod, MemReader, MemWriter};
use test::Bencher;
use uri::{RequestUri, Star, AbsoluteUri, AbsolutePath, Authority};
use uri::RequestUri;
use uri::RequestUri::{Star, AbsoluteUri, AbsolutePath, Authority};
use method;
use status;
use version::{HttpVersion, Http10, Http11, Http20};
use {HttpResult, HttpVersionError};
use version::HttpVersion;
use version::HttpVersion::{Http10, Http11, Http20};
use HttpError::HttpVersionError;
use HttpResult;
use url::Url;

use super::{read_method, read_uri, read_http_version, read_header, RawHeaderLine, read_status};
Expand All @@ -627,15 +636,15 @@ mod tests {
assert_eq!(read_method(&mut mem(s)), Ok(m));
}

read("GET /", method::Get);
read("POST /", method::Post);
read("PUT /", method::Put);
read("HEAD /", method::Head);
read("OPTIONS /", method::Options);
read("CONNECT /", method::Connect);
read("TRACE /", method::Trace);
read("PATCH /", method::Patch);
read("FOO /", method::Extension("FOO".to_string()));
read("GET /", method::Method::Get);
read("POST /", method::Method::Post);
read("PUT /", method::Method::Put);
read("HEAD /", method::Method::Head);
read("OPTIONS /", method::Method::Options);
read("CONNECT /", method::Method::Connect);
read("TRACE /", method::Method::Trace);
read("PATCH /", method::Method::Patch);
read("FOO /", method::Method::Extension("FOO".to_string()));
}

#[test]
Expand Down Expand Up @@ -671,7 +680,7 @@ mod tests {
assert_eq!(read_status(&mut mem(s)), result);
}

read("200 OK\r\n", Ok(status::Ok));
read("200 OK\r\n", Ok(status::StatusCode::Ok));
}

#[test]
Expand All @@ -687,7 +696,7 @@ mod tests {
#[test]
fn test_write_chunked() {
use std::str::from_utf8;
let mut w = super::ChunkedWriter(MemWriter::new());
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();
Expand All @@ -698,7 +707,7 @@ mod tests {
#[test]
fn test_write_sized() {
use std::str::from_utf8;
let mut w = super::SizedWriter(MemWriter::new(), 8);
let mut w = super::HttpWriter::SizedWriter(MemWriter::new(), 8);
w.write(b"foo bar").unwrap();
assert_eq!(w.write(b"baz"), Err(io::standard_error(io::ShortWrite(1))));

Expand All @@ -710,7 +719,7 @@ mod tests {
#[bench]
fn bench_read_method(b: &mut Bencher) {
b.bytes = b"CONNECT ".len() as u64;
b.iter(|| assert_eq!(read_method(&mut mem("CONNECT ")), Ok(method::Connect)));
b.iter(|| assert_eq!(read_method(&mut mem("CONNECT ")), Ok(method::Method::Connect)));
}

}
8 changes: 5 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![feature(macro_rules, phase, default_type_params, if_let, slicing_syntax,
tuple_indexing)]
tuple_indexing, globs)]
#![deny(missing_docs)]
#![deny(warnings)]
#![experimental]
Expand Down Expand Up @@ -140,8 +140,8 @@ extern crate cookie;
pub use std::io::net::ip::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr, Port};
pub use mimewrapper::mime;
pub use url::Url;
pub use method::{Get, Head, Post, Delete};
pub use status::{Ok, BadRequest, NotFound};
pub use method::Method::{Get, Head, Post, Delete};
pub use status::StatusCode::{Ok, BadRequest, NotFound};
pub use server::Server;

use std::fmt;
Expand All @@ -150,6 +150,8 @@ use std::io::IoError;

use std::rt::backtrace;

use self::HttpError::{HttpMethodError, HttpUriError, HttpVersionError,
HttpHeaderError, HttpStatusError, HttpIoError};

macro_rules! todo(
($($arg:tt)*) => (if cfg!(not(ndebug)) {
Expand Down
3 changes: 3 additions & 0 deletions src/method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
use std::fmt;
use std::str::FromStr;

use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch,
Extension};

/// The Request Method (VERB)
///
/// Currently includes 8 variants representing the 8 methods defined in
Expand Down
2 changes: 2 additions & 0 deletions src/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ use typeable::Typeable;
use openssl::ssl::{SslStream, SslContext, Sslv23};
use openssl::ssl::error::{SslError, StreamError, OpenSslErrors, SslSessionClosed};

use self::HttpStream::{Http, Https};

/// The write-status indicating headers have not been written.
pub struct Fresh;

Expand Down
3 changes: 2 additions & 1 deletion src/server/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ use method;
use header::Headers;
use header::common::ContentLength;
use http::{read_request_line};
use http::{HttpReader, SizedReader, ChunkedReader};
use http::HttpReader;
use http::HttpReader::{SizedReader, ChunkedReader};
use net::NetworkStream;
use uri::RequestUri;

Expand Down
11 changes: 6 additions & 5 deletions src/server/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use time::now_utc;

use header;
use header::common;
use http::{CR, LF, LINE_ENDING, HttpWriter, ThroughWriter, ChunkedWriter, SizedWriter};
use http::{CR, LF, LINE_ENDING, HttpWriter};
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter};
use status;
use net::{NetworkStream, Fresh, Streaming};
use version;
Expand Down Expand Up @@ -52,8 +53,8 @@ impl Response<Fresh> {
/// Creates a new Response that can be used to write to a network stream.
pub fn new<S: NetworkStream>(stream: S) -> Response<Fresh> {
Response {
status: status::Ok,
version: version::Http11,
status: status::StatusCode::Ok,
version: version::HttpVersion::Http11,
headers: header::Headers::new(),
body: ThroughWriter(BufferedWriter::new(box stream as Box<NetworkStream + Send>))
}
Expand Down Expand Up @@ -85,15 +86,15 @@ impl Response<Fresh> {
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.push(common::transfer_encoding::Encoding::Chunked);
false
},
None => true
};

if encodings {
self.headers.set::<common::TransferEncoding>(
common::TransferEncoding(vec![common::transfer_encoding::Chunked]))
common::TransferEncoding(vec![common::transfer_encoding::Encoding::Chunked]))
}
}

Expand Down
5 changes: 5 additions & 0 deletions src/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
use std::fmt;
use std::mem::transmute;

use self::StatusClass::{Informational, Success, Redirection, ClientError,
ServerError};

use self::StatusCode::*;

// shamelessly lifted from Teepee. I tried a few schemes, this really
// does seem like the best.

Expand Down
Loading

0 comments on commit d7e8b8b

Please sign in to comment.