Reform top-level libs mostly according to Rustfmt.

This commit is contained in:
Sergio Benitez 2016-09-30 15:20:11 -07:00
parent 008605bec7
commit a29d56c52e
23 changed files with 132 additions and 128 deletions

View File

@ -11,6 +11,5 @@ pub struct StaticRouteInfo {
pub struct StaticCatchInfo {
pub code: u16,
pub handler: ErrorHandler
pub handler: ErrorHandler,
}

View File

@ -1,5 +1,5 @@
pub use response::mime::{Mime, TopLevel, SubLevel};
use response::mime::{Param};
use response::mime::Param;
use std::default::Default;
use std::str::FromStr;
@ -105,7 +105,7 @@ impl From<Mime> for ContentType {
fn from(mime: Mime) -> ContentType {
let params = match mime.2.len() {
0 => None,
_ => Some(mime.2)
_ => Some(mime.2),
};
ContentType(mime.0, mime.1, params)
@ -115,14 +115,14 @@ impl From<Mime> for ContentType {
fn is_valid_first_char(c: char) -> bool {
match c {
'a'...'z' | 'A'...'Z' | '0'...'9' | '*' => true,
_ => false
_ => false,
}
}
fn is_valid_char(c: char) -> bool {
is_valid_first_char(c) || match c {
'!' | '#' | '$' | '&' | '-' | '^' | '.' | '+' | '_' => true,
_ => false
_ => false,
}
}
@ -132,33 +132,34 @@ impl FromStr for ContentType {
fn from_str(raw: &str) -> Result<ContentType, &'static str> {
let slash = match raw.find('/') {
Some(i) => i,
None => return Err("Missing / in MIME type.")
None => return Err("Missing / in MIME type."),
};
let top_str = &raw[..slash];
let (sub_str, _rest) = match raw.find(';') {
Some(j) => (&raw[(slash + 1)..j], Some(&raw[(j + 1)..])),
None => (&raw[(slash + 1)..], None)
};
let top_s = &raw[..slash];
let (sub_s, _rest) = match raw.find(';') {
Some(j) => (&raw[(slash + 1)..j], Some(&raw[(j + 1)..])),
None => (&raw[(slash + 1)..], None),
};
if top_str.len() < 1 || sub_str.len() < 1 {
return Err("Empty string.")
if top_s.len() < 1 || sub_s.len() < 1 {
return Err("Empty string.");
}
if !is_valid_first_char(top_str.chars().next().unwrap())
|| !is_valid_first_char(sub_str.chars().next().unwrap()) {
return Err("Invalid first char.")
if !is_valid_first_char(top_s.chars().next().unwrap())
|| !is_valid_first_char(sub_s.chars().next().unwrap()) {
return Err("Invalid first char.");
}
if top_str.contains(|c| !is_valid_char(c))
|| sub_str.contains(|c| !is_valid_char(c)) {
return Err("Invalid character in string.")
if top_s.contains(|c| !is_valid_char(c))
|| sub_s.contains(|c| !is_valid_char(c)) {
return Err("Invalid character in string.");
}
let (top_str, sub_str) = (&*top_str.to_lowercase(), &*sub_str.to_lowercase());
let top_level = TopLevel::from_str(top_str).map_err(|_| "Bad TopLevel")?;
let sub_level = SubLevel::from_str(sub_str).map_err(|_| "Bad SubLevel")?;
// FIXME: Use `rest` to find params.
let (top_s, sub_s) = (&*top_s.to_lowercase(), &*sub_s.to_lowercase());
let top_level = TopLevel::from_str(top_s).map_err(|_| "Bad TopLevel")?;
let sub_level = SubLevel::from_str(sub_s).map_err(|_| "Bad SubLevel")?;
// FIXME: Use `rest` to find params.
Ok(ContentType::new(top_level, sub_level, None))
}
}
@ -186,17 +187,13 @@ impl Collider for ContentType {
impl Collider for TopLevel {
fn collides_with(&self, other: &TopLevel) -> bool {
*self == TopLevel::Star
|| *other == TopLevel::Star
|| *self == *other
*self == TopLevel::Star || *other == TopLevel::Star || *self == *other
}
}
impl Collider for SubLevel {
fn collides_with(&self, other: &SubLevel) -> bool {
*self == SubLevel::Star
|| *other == SubLevel::Star
|| *self == *other
*self == SubLevel::Star || *other == SubLevel::Star || *self == *other
}
}

View File

@ -4,5 +4,5 @@ pub enum Error {
BadParse,
NoRoute, // FIXME: Add a chain of routes attempted.
Internal,
NoKey
NoKey,
}

View File

@ -118,6 +118,7 @@ pub trait FromFormValue<'v>: Sized {
impl<'v> FromFormValue<'v> for &'v str {
type Error = Error;
// This just gives the raw string.
fn from_form_value(v: &'v str) -> Result<Self, Self::Error> {
Ok(v)
}
@ -154,7 +155,7 @@ impl<'v> FromFormValue<'v> for bool {
match v {
"on" | "true" => Ok(true),
"off" | "false" => Ok(false),
_ => Err(v)
_ => Err(v),
}
}
}
@ -179,7 +180,7 @@ impl<'v, T: FromFormValue<'v>> FromFormValue<'v> for Option<T> {
fn from_form_value(v: &'v str) -> Result<Self, Self::Error> {
match T::from_form_value(v) {
Ok(v) => Ok(Some(v)),
Err(_) => Ok(None)
Err(_) => Ok(None),
}
}
@ -195,7 +196,7 @@ impl<'v, T: FromFormValue<'v>> FromFormValue<'v> for Result<T, T::Error> {
fn from_form_value(v: &'v str) -> Result<Self, Self::Error> {
match T::from_form_value(v) {
ok@Ok(_) => Ok(ok),
e@Err(_) => Ok(e)
e@Err(_) => Ok(e),
}
}
}
@ -238,12 +239,12 @@ impl<'f> Iterator for FormItems<'f> {
let string = self.0;
let (key, rest) = match string.find('=') {
Some(index) => (&string[..index], &string[(index + 1)..]),
None => return None
None => return None,
};
let (value, remainder) = match rest.find('&') {
Some(index) => (&rest[..index], &rest[(index + 1)..]),
None => (rest, "")
None => (rest, ""),
};
self.0 = remainder;

View File

@ -22,14 +22,11 @@ extern crate url;
extern crate mime;
#[macro_use] extern crate log;
#[doc(hidden)]
#[macro_use]
pub mod logger;
#[doc(hidden)] #[macro_use] pub mod logger;
#[doc(hidden)] pub mod content_type;
pub mod form;
pub mod request;
pub mod response;
#[doc(hidden)]
pub mod content_type;
mod method;
mod error;
@ -49,17 +46,14 @@ pub mod handler {
pub type ErrorHandler = for<'r> fn(error: Error, &'r Request<'r>) -> Response<'r>;
}
#[doc(inline)] pub use response::{Response, Responder};
#[doc(inline)] pub use handler::{Handler, ErrorHandler};
#[doc(inline)] pub use logger::LoggingLevel;
pub use content_type::ContentType;
pub use codegen::{StaticRouteInfo, StaticCatchInfo};
pub use request::Request;
pub use method::Method;
#[doc(inline)]
pub use response::{Response, Responder};
pub use error::Error;
pub use router::{Router, Route};
pub use catcher::Catcher;
pub use rocket::Rocket;
#[doc(inline)]
pub use handler::{Handler, ErrorHandler};
#[doc(inline)]
pub use logger::LoggingLevel;

View File

@ -23,7 +23,7 @@ impl LoggingLevel {
match *self {
LoggingLevel::Critical => LogLevel::Warn,
LoggingLevel::Normal => LogLevel::Info,
LoggingLevel::Debug => LogLevel::Trace
LoggingLevel::Debug => LogLevel::Trace,
}
}
}

View File

@ -31,7 +31,7 @@ impl Method {
HyperMethod::Trace => Some(Trace),
HyperMethod::Connect => Some(Connect),
HyperMethod::Patch => Some(Patch),
HyperMethod::Extension(_) => None
HyperMethod::Extension(_) => None,
}
}

View File

@ -46,7 +46,7 @@ impl<'r, 'c, T: FromRequest<'r, 'c>> FromRequest<'r, 'c> for Option<T> {
fn from_request(request: &'r Request<'c>) -> Result<Self, Self::Error> {
let opt = match T::from_request(request) {
Ok(v) => Some(v),
Err(_) => None
Err(_) => None,
};
Ok(opt)

View File

@ -1,4 +1,4 @@
use std::io::{Read};
use std::io::Read;
use std::cell::RefCell;
use std::fmt;
@ -45,8 +45,9 @@ impl<'a> Request<'a> {
}
/// i is the index of the first segment to consider
pub fn get_segments<'r: 'a, T: FromSegments<'a>>(&'r self, i: usize)
-> Result<T, Error> {
pub fn get_segments<'r: 'a, T: FromSegments<'a>>(&'r self,
i: usize)
-> Result<T, Error> {
if i >= self.uri().segment_count() {
debug!("{} is >= segment count {}", i, self.uri().segment_count());
Err(Error::NoKey)
@ -55,6 +56,7 @@ impl<'a> Request<'a> {
// but the std lib doesn't implement it for Skip.
let mut segments = self.uri.segments();
for _ in segments.by_ref().take(i) { /* do nothing */ }
T::from_segments(segments).map_err(|_| Error::BadParse)
}
}
@ -66,7 +68,7 @@ impl<'a> Request<'a> {
cookies: Cookies::new(&[]),
uri: URIBuf::from(uri),
data: vec![],
headers: HyperHeaders::new()
headers: HyperHeaders::new(),
}
}
@ -90,7 +92,7 @@ impl<'a> Request<'a> {
if items.len() < 1 {
return ContentType::any();
} else {
return ContentType::from(items[0].item.clone())
return ContentType::from(items[0].item.clone());
}
})
}
@ -111,23 +113,23 @@ impl<'a> Request<'a> {
}
pub fn from_hyp<'h, 'k>(hyper_req: HyperRequest<'h, 'k>)
-> Result<Request<'a>, String> {
-> Result<Request<'a>, String> {
let (_, h_method, h_headers, h_uri, _, mut h_body) = hyper_req.deconstruct();
let uri = match h_uri {
HyperRequestUri::AbsolutePath(s) => URIBuf::from(s),
_ => return Err(format!("Bad URI: {}", h_uri))
_ => return Err(format!("Bad URI: {}", h_uri)),
};
let method = match Method::from_hyp(&h_method) {
Some(m) => m,
_ => return Err(format!("Bad method: {}", h_method))
_ => return Err(format!("Bad method: {}", h_method)),
};
let cookies = match h_headers.get::<HyperCookie>() {
// TODO: What to do about key?
Some(cookie) => cookie.to_cookie_jar(&[]),
None => Cookies::new(&[])
// TODO: What to do about key?
Some(cookie) => cookie.to_cookie_jar(&[]),
None => Cookies::new(&[]),
};
// FIXME: GRRR.

View File

@ -8,7 +8,7 @@ const FLASH_COOKIE_NAME: &'static str = "_flash";
pub struct Flash<R> {
name: String,
message: String,
responder: R
responder: R,
}
impl<R: Responder> Flash<R> {
@ -89,7 +89,7 @@ impl<'r, 'c> FromRequest<'r, 'c> for Flash<()> {
let content = cookie.pair().1;
let (len_str, rest) = match content.find(|c: char| !c.is_digit(10)) {
Some(i) => (&content[..i], &content[i..]),
None => (content, "")
None => (content, ""),
};
let name_len: usize = len_str.parse().map_err(|_| ())?;
@ -98,4 +98,3 @@ impl<'r, 'c> FromRequest<'r, 'c> for Flash<()> {
})
}
}

View File

@ -35,8 +35,9 @@ impl<'a> Response<'a> {
Response(Box::new(body))
}
pub fn with_status<T: Responder + 'a>(status: StatusCode, body: T)
-> Response<'a> {
pub fn with_status<T: Responder + 'a>(status: StatusCode,
body: T)
-> Response<'a> {
Response(Box::new(StatusResponse::new(status, body)))
}
@ -44,8 +45,7 @@ impl<'a> Response<'a> {
Response(Box::new(Forward))
}
pub fn with_raw_status<T: Responder + 'a>(status: u16, body: T)
-> Response<'a> {
pub fn with_raw_status<T: Responder + 'a>(status: u16, body: T) -> Response<'a> {
let status_code = StatusCode::from_u16(status);
Response(Box::new(StatusResponse::new(status_code, body)))
}

View File

@ -73,7 +73,9 @@ impl io::Write for NamedFile {
self.file().write(buf)
}
fn flush(&mut self) -> io::Result<()> { self.file().flush() }
fn flush(&mut self) -> io::Result<()> {
self.file().flush()
}
}
impl io::Seek for NamedFile {
@ -97,7 +99,9 @@ impl<'a> io::Write for &'a NamedFile {
self.file().write(buf)
}
fn flush(&mut self) -> io::Result<()> { self.file().flush() }
fn flush(&mut self) -> io::Result<()> {
self.file().flush()
}
}
impl<'a> io::Seek for &'a NamedFile {

View File

@ -50,18 +50,10 @@ impl<'h> fmt::Debug for Outcome<'h> {
impl<'h> fmt::Display for Outcome<'h> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Outcome::Complete => {
write!(f, "{}", Green.paint("Complete"))
},
Outcome::Bad(..) => {
write!(f, "{}", Yellow.paint("Bad Completion"))
},
Outcome::FailStop => {
write!(f, "{}", Red.paint("Failed"))
},
Outcome::FailForward(..) => {
write!(f, "{}", Cyan.paint("Forwarding"))
},
Outcome::Complete => write!(f, "{}", Green.paint("Complete")),
Outcome::Bad(..) => write!(f, "{}", Yellow.paint("Bad Completion")),
Outcome::FailStop => write!(f, "{}", Red.paint("Failed")),
Outcome::FailForward(..) => write!(f, "{}", Cyan.paint("Forwarding")),
}
}
}

View File

@ -34,4 +34,3 @@ impl<'a> Responder for Redirect {
Outcome::Complete
}
}

View File

@ -69,8 +69,7 @@ impl<T: Responder> Responder for Option<T> {
impl<T: Responder, E: fmt::Debug> Responder for Result<T, E> {
// prepend with `default` when using impl specialization
default fn respond<'a>(&mut self, res: FreshHyperResponse<'a>)
-> Outcome<'a> {
default fn respond<'a>(&mut self, res: FreshHyperResponse<'a>) -> Outcome<'a> {
if self.is_err() {
error_!("{:?}", self.as_ref().err().unwrap());
// TODO: Should this be a 404 or 500?
@ -85,7 +84,7 @@ impl<T: Responder, E: Responder + fmt::Debug> Responder for Result<T, E> {
fn respond<'a>(&mut self, res: FreshHyperResponse<'a>) -> Outcome<'a> {
match *self {
Ok(ref mut responder) => responder.respond(res),
Err(ref mut responder) => responder.respond(res)
Err(ref mut responder) => responder.respond(res),
}
}
}

View File

@ -12,15 +12,15 @@ impl<T: Read> Stream<T> {
Stream(Box::new(reader))
}
// pub fn chunked(mut self, size: usize) -> Self {
// self.1 = size;
// self
// }
// pub fn chunked(mut self, size: usize) -> Self {
// self.1 = size;
// self
// }
// #[inline(always)]
// pub fn chunk_size(&self) -> usize {
// self.1
// }
// #[inline(always)]
// pub fn chunk_size(&self) -> usize {
// self.1
// }
}
impl<T: Read> Responder for Stream<T> {

View File

@ -2,14 +2,14 @@ use response::*;
pub struct StatusResponse<R: Responder> {
status: StatusCode,
responder: R
responder: R,
}
impl<R: Responder> StatusResponse<R> {
pub fn new(status: StatusCode, responder: R) -> StatusResponse<R> {
StatusResponse {
status: status,
responder: responder
responder: responder,
}
}
}
@ -20,4 +20,3 @@ impl<R: Responder> Responder for StatusResponse<R> {
self.responder.respond(res)
}
}

View File

@ -23,15 +23,17 @@ pub struct Rocket {
}
impl HyperHandler for Rocket {
fn handle<'h, 'k>(&self, req: HyperRequest<'h, 'k>,
mut res: FreshHyperResponse<'h>) {
fn handle<'h, 'k>(&self,
req: HyperRequest<'h, 'k>,
mut res: FreshHyperResponse<'h>) {
res.headers_mut().set(response::header::Server("rocket".to_string()));
self.dispatch(req, res)
}
}
impl Rocket {
fn dispatch<'h, 'k>(&self, hyp_req: HyperRequest<'h, 'k>,
fn dispatch<'h, 'k>(&self,
hyp_req: HyperRequest<'h, 'k>,
mut res: FreshHyperResponse<'h>) {
// Get a copy of the URI for later use.
let uri = hyp_req.uri.to_string();
@ -41,7 +43,7 @@ impl Rocket {
Ok(mut req) => {
self.preprocess_request(&mut req);
req
},
}
Err(ref reason) => {
let mock_request = Request::mock(Method::Get, uri.as_str());
debug_!("Bad request: {}", reason);
@ -71,7 +73,7 @@ impl Rocket {
res = match outcome {
Outcome::Complete | Outcome::FailStop => return,
Outcome::FailForward(r) => r,
Outcome::Bad(r) => return self.handle_internal_error(&request, r)
Outcome::Bad(r) => return self.handle_internal_error(&request, r),
};
}
@ -101,15 +103,17 @@ impl Rocket {
}
// Call on internal server error.
fn handle_internal_error<'r>(&self, request: &'r Request<'r>,
response: FreshHyperResponse) {
fn handle_internal_error<'r>(&self,
request: &'r Request<'r>,
response: FreshHyperResponse) {
error_!("Internal server error.");
let catcher = self.catchers.get(&500).unwrap();
catcher.handle(Error::Internal, request).respond(response);
}
// Call when no route was found.
fn handle_not_found<'r>(&self, request: &'r Request<'r>,
fn handle_not_found<'r>(&self,
request: &'r Request<'r>,
response: FreshHyperResponse) {
error_!("{} dispatch failed: 404.", request);
let catcher = self.catchers.get(&404).unwrap();
@ -126,8 +130,7 @@ impl Rocket {
}
}
pub fn mount(&mut self, base: &'static str, routes: Vec<Route>)
-> &mut Self {
pub fn mount(&mut self, base: &'static str, routes: Vec<Route>) -> &mut Self {
self.enable_normal_logging_if_disabled();
info!("🛰 {} '{}':", Magenta.paint("Mounting"), base);
for mut route in routes {
@ -190,8 +193,9 @@ impl Rocket {
}
let full_addr = format!("{}:{}", self.address, self.port);
info!("🚀 {} {}...", White.paint("Rocket has launched from"),
White.bold().paint(&full_addr));
info!("🚀 {} {}...",
White.paint("Rocket has launched from"),
White.bold().paint(&full_addr));
let _ = HyperServer::http(full_addr.as_str()).unwrap().handle(self);
}

View File

@ -5,8 +5,11 @@ pub trait Collider<T: ?Sized = Self> {
fn collides_with(&self, other: &T) -> bool;
}
pub fn index_match_until(break_c: char, a: &str, b: &str, dir: bool)
-> Option<(isize, isize)> {
pub fn index_match_until(break_c: char,
a: &str,
b: &str,
dir: bool)
-> Option<(isize, isize)> {
let (a_len, b_len) = (a.len() as isize, b.len() as isize);
let (mut i, mut j, delta) = if dir {
(0, 0, 1)

View File

@ -15,7 +15,7 @@ type Selector = Method;
#[derive(Default)]
pub struct Router {
routes: HashMap<Selector, Vec<Route>> // using 'selector' for now
routes: HashMap<Selector, Vec<Route>>, // using 'selector' for now
}
impl Router {
@ -39,9 +39,9 @@ impl Router {
// let num_segments = req.uri.segment_count();
// self.routes.get(&(req.method, num_segments)).map_or(vec![], |routes| {
self.routes.get(&req.method).map_or(vec![], |routes| {
let mut matches: Vec<_> = routes.iter().filter(|r| {
r.collides_with(req)
}).collect();
let mut matches: Vec<_> = routes.iter()
.filter(|r| r.collides_with(req))
.collect();
matches.sort_by(|a, b| a.rank.cmp(&b.rank));
trace_!("All matches: {:?}", matches);
@ -149,7 +149,10 @@ mod test {
assert!(!default_rank_route_collisions(&["/a/b", "/a/b/<c..>"]));
}
fn route<'a>(router: &'a Router, method: Method, uri: &str) -> Option<&'a Route> {
fn route<'a>(router: &'a Router,
method: Method,
uri: &str)
-> Option<&'a Route> {
let request = Request::mock(method, uri);
let matches = router.route(&request);
if matches.len() > 0 {

View File

@ -24,8 +24,9 @@ fn default_rank(path: &str) -> isize {
}
impl Route {
pub fn ranked<S>(rank: isize, m: Method, path: S, handler: Handler)
-> Route where S: AsRef<str> {
pub fn ranked<S>(rank: isize, m: Method, path: S, handler: Handler) -> Route
where S: AsRef<str>
{
Route {
method: m,
path: URIBuf::from(path.as_ref()),
@ -35,7 +36,9 @@ impl Route {
}
}
pub fn new<S>(m: Method, path: S, handler: Handler) -> Route where S: AsRef<str> {
pub fn new<S>(m: Method, path: S, handler: Handler) -> Route
where S: AsRef<str>
{
Route {
method: m,
handler: handler,
@ -45,7 +48,9 @@ impl Route {
}
}
pub fn set_path<S>(&mut self, path: S) where S: AsRef<str> {
pub fn set_path<S>(&mut self, path: S)
where S: AsRef<str>
{
self.path = URIBuf::from(path.as_ref());
}
@ -58,9 +63,11 @@ impl Route {
let mut result = Vec::with_capacity(self.path.segment_count());
for (route_seg, uri_seg) in route_segs.zip(uri_segs) {
if route_seg.ends_with("..>") { // FIXME: Here.
if route_seg.ends_with("..>") {
// FIXME: Here.
break;
} else if route_seg.ends_with('>') { // FIXME: Here.
} else if route_seg.ends_with('>') {
// FIXME: Here.
result.push(uri_seg);
}
}

View File

@ -8,7 +8,7 @@ pub struct URI<'a> {
uri: &'a str,
path: &'a str,
query: Option<&'a str>,
segment_count: Cell<Option<usize>>
segment_count: Cell<Option<usize>>,
}
impl<'a> URI<'a> {
@ -17,7 +17,7 @@ impl<'a> URI<'a> {
let (path, query) = match uri.find('?') {
Some(index) => (&uri[..index], Some(&uri[(index + 1)..])),
None => (uri, None)
None => (uri, None),
};
URI {
@ -53,7 +53,10 @@ impl<'a> fmt::Display for URI<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut last = '\0';
for c in self.uri.chars() {
if !(c == '/' && last == '/') { f.write_char(c)?; }
if !(c == '/' && last == '/') {
f.write_char(c)?;
}
last = c;
}
@ -66,7 +69,7 @@ unsafe impl<'a> Sync for URI<'a> { /* It's safe! */ }
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct URIBuf {
uri: String,
segment_count: Cell<Option<usize>>
segment_count: Cell<Option<usize>>,
}
// I don't like repeating all of this stuff. Is there a better way?
@ -160,7 +163,7 @@ impl<'a> Iterator for Segments<'a> {
// Find the start of the next segment (first that's not '/').
let i = match self.0.find(|c| c != '/') {
Some(index) => index,
None => return None
None => return None,
};
// Get the index of the first character that _is_ a '/' after start.

View File

@ -1,3 +1,2 @@
enum_trailing_comma = false
max_width = 85
fn_call_width = 80