hyper_sync/http/
message.rs1use std::any::{Any, TypeId};
5use std::fmt::Debug;
6use std::io::{Read, Write};
7use std::mem;
8
9use std::io;
10use std::time::Duration;
11
12use header::Headers;
13use http::RawStatus;
14use url::Url;
15
16use method;
17use version;
18
19pub trait Protocol {
22 fn new_message(&self, host: &str, port: u16, scheme: &str) -> ::Result<Box<HttpMessage>>;
24}
25
26#[derive(Clone, Debug)]
28pub struct RequestHead {
29 pub headers: Headers,
31 pub method: method::Method,
33 pub url: Url,
35}
36
37#[derive(Clone, Debug)]
39pub struct ResponseHead {
40 pub headers: Headers,
42 pub raw_status: RawStatus,
44 pub version: version::HttpVersion,
46}
47
48pub trait HttpMessage: Write + Read + Send + Any + ::GetType + Debug {
50 fn set_outgoing(&mut self, head: RequestHead) -> ::Result<RequestHead>;
57 fn get_incoming(&mut self) -> ::Result<ResponseHead>;
62 fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()>;
64 fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()>;
66 fn close_connection(&mut self) -> ::Result<()>;
68 fn has_body(&self) -> bool;
70 fn set_proxied(&mut self, val: bool) {
72 warn!("default set_proxied({:?})", val);
74 }
75}
76
77impl HttpMessage {
78 unsafe fn downcast_ref_unchecked<T: 'static>(&self) -> &T {
79 &*(mem::transmute::<*const _, (*const (), *const ())>(self).0 as *const T)
80 }
81
82 unsafe fn downcast_mut_unchecked<T: 'static>(&mut self) -> &mut T {
83 &mut *(mem::transmute::<*mut _, (*mut (), *mut ())>(self).0 as *mut T)
84 }
85
86 unsafe fn downcast_unchecked<T: 'static>(self: Box<HttpMessage>) -> Box<T> {
87 Box::from_raw(mem::transmute::<*mut _, (*mut (), *mut ())>(Box::into_raw(self)).0 as *mut T)
88 }
89}
90
91impl HttpMessage {
92 #[inline]
94 pub fn is<T: Any>(&self) -> bool {
95 (*self).get_type() == TypeId::of::<T>()
96 }
97
98 #[inline]
100 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
101 if self.is::<T>() {
102 Some(unsafe { self.downcast_ref_unchecked() })
103 } else {
104 None
105 }
106 }
107
108 #[inline]
111 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
112 if self.is::<T>() {
113 Some(unsafe { self.downcast_mut_unchecked() })
114 } else {
115 None
116 }
117 }
118
119 #[inline]
121 pub fn downcast<T: Any>(self: Box<HttpMessage>)
122 -> Result<Box<T>, Box<HttpMessage>> {
123 if self.is::<T>() {
124 Ok(unsafe { self.downcast_unchecked() })
125 } else {
126 Err(self)
127 }
128 }
129}