Skip to content

Commit e32845c

Browse files
committed
Merge pull request #19 from reem/static-response-states
Statically track the status of a Response by using a Phantom Type
2 parents 5a98d16 + 13bb07e commit e32845c

File tree

4 files changed

+72
-36
lines changed

4 files changed

+72
-36
lines changed

benches/client.rs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![feature(macro_rules)]
12
extern crate curl;
23
extern crate http;
34
extern crate hyper;
@@ -13,10 +14,19 @@ fn listen() -> hyper::server::Listening {
1314
server.listen(handle).unwrap()
1415
}
1516

17+
macro_rules! try_continue(
18+
($e:expr) => {{
19+
match $e {
20+
Ok(v) => v,
21+
Err(..) => continue
22+
}
23+
}})
24+
1625
fn handle(mut incoming: Incoming) {
17-
for (_, mut res) in incoming {
18-
res.write(b"Benchmarking hyper vs others!").unwrap();
19-
res.end().unwrap();
26+
for (_, res) in incoming {
27+
let mut res = try_continue!(res.start());
28+
try_continue!(res.write(b"Benchmarking hyper vs others!"))
29+
try_continue!(res.end());
2030
}
2131
}
2232

examples/server.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,24 +29,26 @@ impl Handler for Echo {
2929
(&Get, "/") | (&Get, "/echo") => {
3030
let out = b"Try POST /echo";
3131

32-
res.headers.set(ContentLength(out.len()));
32+
res.headers_mut().set(ContentLength(out.len()));
33+
let mut res = try_continue!(res.start());
3334
try_continue!(res.write(out));
3435
try_continue!(res.end());
3536
continue;
3637
},
3738
(&Post, "/echo") => (), // fall through, fighting mutable borrows
3839
_ => {
39-
res.status = hyper::status::NotFound;
40-
try_continue!(res.end());
40+
*res.status_mut() = hyper::status::NotFound;
41+
try_continue!(res.start().and_then(|res| res.end()));
4142
continue;
4243
}
4344
},
4445
_ => {
45-
try_continue!(res.end());
46-
continue;
46+
try_continue!(res.start().and_then(|res| res.end()));
47+
continue;
4748
}
4849
};
4950

51+
let mut res = try_continue!(res.start());
5052
try_continue!(copy(&mut req, &mut res));
5153
try_continue!(res.end());
5254
}

src/server/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::io::{Acceptor, Listener, IoResult, EndOfFile, IncomingConnections};
44
use std::io::net::ip::{IpAddr, Port, SocketAddr};
55

66
pub use self::request::Request;
7-
pub use self::response::Response;
7+
pub use self::response::{Response, Fresh, Streaming};
88

99
pub mod request;
1010
pub mod response;
@@ -55,8 +55,8 @@ pub struct Incoming<'a> {
5555
from: IncomingConnections<'a, TcpAcceptor>
5656
}
5757

58-
impl<'a> Iterator<(Request, Response)> for Incoming<'a> {
59-
fn next(&mut self) -> Option<(Request, Response)> {
58+
impl<'a> Iterator<(Request, Response<Fresh>)> for Incoming<'a> {
59+
fn next(&mut self) -> Option<(Request, Response<Fresh>)> {
6060
for conn in self.from {
6161
match conn {
6262
Ok(stream) => {

src/server/response.rs

Lines changed: 49 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -13,39 +13,52 @@ use status;
1313
use version;
1414
use rfc7230::{CR, LF, LINE_ENDING};
1515

16+
/// Phantom type indicating Headers and StatusCode have not been written.
17+
pub struct Fresh;
18+
19+
/// Phantom type indicating Headers and StatusCode have been written.
20+
pub struct Streaming;
21+
22+
/// The status of a Response, indicating if the headers and status have been written.
23+
pub trait WriteStatus {}
24+
25+
impl WriteStatus for Streaming {}
26+
impl WriteStatus for Fresh {}
1627

1728
/// The outgoing half for a Tcp connection, created by a `Server` and given to a `Handler`.
18-
pub struct Response {
19-
/// The status code for the request.
20-
pub status: status::StatusCode,
21-
/// The outgoing headers on this response.
22-
pub headers: header::Headers,
29+
pub struct Response<W: WriteStatus> {
2330
/// The HTTP version of this response.
2431
pub version: version::HttpVersion,
25-
26-
headers_written: bool, // TODO: can this check be moved to compile time?
32+
// Stream the Response is writing to, not accessible through UnwrittenResponse
2733
body: BufferedWriter<TcpStream>, // TODO: use a HttpWriter from rfc7230
34+
// The status code for the request.
35+
status: status::StatusCode,
36+
// The outgoing headers on this response.
37+
headers: header::Headers
2838
}
2939

30-
impl Response {
40+
impl<W: WriteStatus> Response<W> {
41+
/// The status of this response.
42+
#[inline]
43+
pub fn status(&self) -> status::StatusCode { self.status }
3144

45+
/// The headers of this response.
46+
pub fn headers(&self) -> &header::Headers { &self.headers }
47+
}
48+
49+
impl Response<Fresh> {
3250
/// Creates a new Response that can be used to write to a network stream.
33-
pub fn new(tcp: TcpStream) -> Response {
51+
pub fn new(tcp: TcpStream) -> Response<Fresh> {
3452
Response {
3553
status: status::Ok,
3654
version: version::Http11,
3755
headers: header::Headers::new(),
38-
headers_written: false,
3956
body: BufferedWriter::new(tcp)
4057
}
4158
}
4259

43-
fn write_head(&mut self) -> IoResult<()> {
44-
if self.headers_written {
45-
debug!("headers previously written, nooping");
46-
return Ok(());
47-
}
48-
self.headers_written = true;
60+
/// Consume this Response<Fresh>, writing the Headers and Status and creating a Response<Streaming>
61+
pub fn start(mut self) -> IoResult<Response<Streaming>> {
4962
debug!("writing head: {} {}", self.version, self.status);
5063
try!(write!(self.body, "{} {}{}{}", self.version, self.status, CR as char, LF as char));
5164

@@ -59,30 +72,41 @@ impl Response {
5972
try!(self.body.write(LINE_ENDING));
6073
}
6174

62-
self.body.write(LINE_ENDING)
75+
try!(self.body.write(LINE_ENDING));
76+
77+
// "copy" to change the phantom type
78+
Ok(Response {
79+
version: self.version,
80+
body: self.body,
81+
status: self.status,
82+
headers: self.headers
83+
})
6384
}
6485

86+
/// Get a mutable reference to the status.
87+
#[inline]
88+
pub fn status_mut(&mut self) -> &mut status::StatusCode { &mut self.status }
89+
90+
/// Get a mutable reference to the Headers.
91+
pub fn headers_mut(&mut self) -> &mut header::Headers { &mut self.headers }
92+
}
93+
94+
impl Response<Streaming> {
6595
/// Flushes all writing of a response to the client.
6696
pub fn end(mut self) -> IoResult<()> {
6797
debug!("ending");
6898
self.flush()
6999
}
70100
}
71101

72-
73-
impl Writer for Response {
102+
impl Writer for Response<Streaming> {
74103
fn write(&mut self, msg: &[u8]) -> IoResult<()> {
75-
if !self.headers_written {
76-
try!(self.write_head());
77-
}
78104
debug!("write {:u} bytes", msg.len());
79105
self.body.write(msg)
80106
}
81107

82108
fn flush(&mut self) -> IoResult<()> {
83-
if !self.headers_written {
84-
try!(self.write_head());
85-
}
86109
self.body.flush()
87110
}
88111
}
112+

0 commit comments

Comments
 (0)