#![unstable]
use std::str::FromStr;
use std::fmt::{Show, Formatter, Result};
use tools::remove_trailing_crlf;
#[deriving(PartialEq,Eq,Clone)]
pub struct Response {
pub code: u16,
pub message: Option<String>
}
impl Show for Response {
fn fmt(&self, f: &mut Formatter) -> Result {
f.write(
match self.clone().message {
Some(message) => format!("{} {}", self.code, message),
None => format!("{}", self.code),
}.as_bytes()
)
}
}
impl FromStr for Response {
fn from_str(s: &str) -> Option<Response> {
if s.len() < 3 {
None
} else if s.len() == 3 || (s.len() == 4 && s.slice(3,4) == " ") {
match from_str::<u16>(s.slice_to(3)) {
Some(code) => Some(Response{
code: code,
message: None
}),
None => None,
}
} else {
match (
from_str::<u16>(s.slice_to(3)),
vec![" ", "-"].contains(&s.slice(3,4)),
(remove_trailing_crlf(s.slice_from(4)))
) {
(Some(code), true, message) => Some(Response{
code: code,
message: Some(message.to_string())
}),
_ => None,
}
}
}
}
#[cfg(test)]
mod test {
use super::Response;
#[test]
fn test_fmt() {
assert_eq!(format!("{}", Response{code: 200, message: Some("message".to_string())}),
"200 message".to_string());
}
#[test]
fn test_from_str() {
assert_eq!(from_str::<Response>("200 response message"),
Some(Response{
code: 200,
message: Some("response message".to_string())
})
);
assert_eq!(from_str::<Response>("200-response message"),
Some(Response{
code: 200,
message: Some("response message".to_string())
})
);
assert_eq!(from_str::<Response>("200"),
Some(Response{
code: 200,
message: None
})
);
assert_eq!(from_str::<Response>("200 "),
Some(Response{
code: 200,
message: None
})
);
assert_eq!(from_str::<Response>("200-response\r\nmessage"),
Some(Response{
code: 200,
message: Some("response\r\nmessage".to_string())
})
);
assert_eq!(from_str::<Response>("2000response message"), None);
assert_eq!(from_str::<Response>("20a response message"), None);
assert_eq!(from_str::<Response>("20 "), None);
assert_eq!(from_str::<Response>("20"), None);
assert_eq!(from_str::<Response>("2"), None);
assert_eq!(from_str::<Response>(""), None);
}
}