Minor code improvements via clippy.

This commit is contained in:
Sergio Benitez 2016-12-17 09:18:30 -08:00
parent d39c47aaf2
commit f1c7d3e27c
21 changed files with 47 additions and 43 deletions

View File

@ -11,7 +11,7 @@ fn test_login(username: &str, password: &str, age: isize, status: Status,
.body(&format!("username={}&password={}&age={}", username, password, age));
let mut response = req.dispatch_with(&rocket);
let body_str = response.body().and_then(|body| body.to_string());
let body_str = response.body().and_then(|body| body.into_string());
println!("Checking: {:?}/{:?}", username, password);
assert_eq!(response.status(), status);

View File

@ -50,7 +50,7 @@ mod test {
let mut response = req.dispatch_with(&rocket);
let expect = format!("Your request contained {} headers!", num_headers);
assert_eq!(response.body().and_then(|b| b.to_string()), Some(expect));
assert_eq!(response.body().and_then(|b| b.into_string()), Some(expect));
}
#[test]

View File

@ -8,7 +8,7 @@ fn test(uri: &str, expected: String) {
let mut req = MockRequest::new(Get, uri);
let mut response = req.dispatch_with(&rocket);
assert_eq!(response.body().and_then(|b| b.to_string()), Some(expected));
assert_eq!(response.body().and_then(|b| b.into_string()), Some(expected));
}
fn test_404(uri: &str) {

View File

@ -7,7 +7,7 @@ fn test(uri: &str, expected: String) {
let mut req = MockRequest::new(Get, uri);
let mut response = req.dispatch_with(&rocket);
let body_str = response.body().and_then(|body| body.to_string());
let body_str = response.body().and_then(|body| body.into_string());
assert_eq!(body_str, Some(expected));
}

View File

@ -8,6 +8,6 @@ fn hello_world() {
let mut req = MockRequest::new(Get, "/");
let mut response = req.dispatch_with(&rocket);
let body_str = response.body().and_then(|body| body.to_string());
let body_str = response.body().and_then(|body| body.into_string());
assert_eq!(body_str, Some("Hello, world!".to_string()));
}

View File

@ -24,7 +24,7 @@ mod test {
let mut req = MockRequest::new(Get, "/");
let mut response = req.dispatch_with(&rocket);
let body_string = response.body().and_then(|b| b.to_string());
let body_string = response.body().and_then(|b| b.into_string());
assert_eq!(body_string, Some("Hello, world!".to_string()));
}
}

View File

@ -87,7 +87,7 @@ impl Config {
pub fn set(&mut self, name: &str, val: &Value) -> config::Result<()> {
if name == "address" {
let address_str = parse!(self, name, val, as_str, "a string")?;
if address_str.contains(":") {
if address_str.contains(':') {
return Err(self.bad_type(name, val, "an IP address with no port"));
} else if format!("{}:{}", address_str, 80).to_socket_addrs().is_err() {
return Err(self.bad_type(name, val, "a valid IP address"));
@ -138,24 +138,24 @@ impl Config {
parse!(self, name, value, as_str, "a string")
}
pub fn get_int<'a>(&'a self, name: &str) -> config::Result<i64> {
pub fn get_int(&self, name: &str) -> config::Result<i64> {
let value = self.extras.get(name).ok_or_else(|| ConfigError::NotFound)?;
parse!(self, name, value, as_integer, "an integer")
}
pub fn get_bool<'a>(&'a self, name: &str) -> config::Result<bool> {
pub fn get_bool(&self, name: &str) -> config::Result<bool> {
let value = self.extras.get(name).ok_or_else(|| ConfigError::NotFound)?;
parse!(self, name, value, as_bool, "a boolean")
}
pub fn get_float<'a>(&'a self, name: &str) -> config::Result<f64> {
pub fn get_float(&self, name: &str) -> config::Result<f64> {
let value = self.extras.get(name).ok_or_else(|| ConfigError::NotFound)?;
parse!(self, name, value, as_float, "a float")
}
pub fn root(&self) -> &Path {
match Path::new(self.filename.as_str()).parent() {
Some(parent) => &parent,
Some(parent) => parent,
None => panic!("root(): filename {} has no parent", self.filename)
}
}

View File

@ -53,7 +53,7 @@ impl ConfigError {
BadCWD => error!("couldn't get current working directory"),
NotFound => error!("config file was not found"),
IOError => error!("failed reading the config file: IO error"),
BadFilePath(ref path, ref reason) => {
BadFilePath(ref path, reason) => {
error!("configuration file path '{}' is invalid", path);
info_!("{}", reason);
}
@ -67,7 +67,7 @@ impl ConfigError {
error!("'{}' is not a valid ROCKET_ENV value", name);
info_!("valid environments are: {}", White.paint(valid_envs));
}
BadType(ref name, ref expected, ref actual, ref filename) => {
BadType(ref name, expected, actual, ref filename) => {
error!("'{}' key could not be parsed", name);
info_!("in {}", White.paint(filename));
info_!("expected value to be {}, but found {}",

View File

@ -208,7 +208,7 @@ impl RocketConfig {
fn parse(src: String, filename: &str) -> Result<RocketConfig> {
// Parse the source as TOML, if possible.
let mut parser = toml::Parser::new(&src);
let toml = parser.parse().ok_or(ConfigError::ParseError(
let toml = parser.parse().ok_or_else(|| ConfigError::ParseError(
src.clone(), filename.into(),
parser.errors.iter().map(|error| ParsingError {
byte_range: (error.lo, error.hi),
@ -243,7 +243,7 @@ impl RocketConfig {
})?;
// Set the environment configuration from the kv pairs.
config.set(env, &kv_pairs)?;
config.set(env, kv_pairs)?;
}
}

View File

@ -90,8 +90,7 @@ impl<T: FromData> FromData for Option<T> {
fn from_data(request: &Request, data: Data) -> Outcome<Self, Self::Error> {
match T::from_data(request, data) {
Success(val) => Success(Some(val)),
Failure(_) => Success(None),
Forward(_) => Success(None)
Failure(_) | Forward(_) => Success(None),
}
}
}

View File

@ -12,7 +12,7 @@ pub trait ReadExt: io::Read {
}
}
return Ok(start_len - buf.len())
Ok(start_len - buf.len())
}
}

View File

@ -273,9 +273,9 @@ impl FromStr for ContentType {
}
let mut trimmed_params = vec![];
for param in params.into_iter().flat_map(|p| p.split(";")) {
for param in params.into_iter().flat_map(|p| p.split(';')) {
let param = param.trim_left();
for (i, split) in param.split("=").enumerate() {
for (i, split) in param.split('=').enumerate() {
if split.trim() != split {
return Err("Whitespace not allowed around = character.");
}

View File

@ -36,7 +36,7 @@ impl<T> From<T> for Header<'static> where T: hyper::Header + hyper::HeaderFormat
}
}
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, Default)]
pub struct HeaderMap<'h> {
headers: HashMap<Cow<'h, str>, Vec<Cow<'h, str>>>
}
@ -57,6 +57,11 @@ impl<'h> HeaderMap<'h> {
self.headers.iter().flat_map(|(_, values)| values.iter()).count()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.headers.is_empty()
}
#[inline]
pub fn get<'a>(&'a self, name: &str) -> impl Iterator<Item=&'a str> {
self.headers.get(name).into_iter().flat_map(|values| {
@ -131,6 +136,7 @@ impl<'h> HeaderMap<'h> {
})
}
// TODO: Figure out what the return type is to implement IntoIterator.
#[inline(always)]
pub fn into_iter(self) -> impl Iterator<Item=Header<'h>> {
self.headers.into_iter().flat_map(|(name, value)| {
@ -145,7 +151,7 @@ impl<'h> HeaderMap<'h> {
#[doc(hidden)]
#[inline(always)]
pub fn into_iter_raw<'s>(self)
pub fn into_iter_raw(self)
-> impl Iterator<Item=(Cow<'h, str>, Vec<Cow<'h, str>>)> {
self.headers.into_iter()
}

View File

@ -214,7 +214,7 @@ impl<'a> URI<'a> {
/// let decoded_path = URI::percent_decode(uri.path().as_bytes()).expect("decoded");
/// assert_eq!(decoded_path, "/Hello, world!");
/// ```
pub fn percent_decode<'s>(string: &'s [u8]) -> Result<Cow<'s, str>, Utf8Error> {
pub fn percent_decode(string: &[u8]) -> Result<Cow<str>, Utf8Error> {
let decoder = url::percent_encoding::percent_decode(string);
decoder.decode_utf8()
}
@ -232,7 +232,7 @@ impl<'a> URI<'a> {
/// let decoded_path = URI::percent_decode_lossy(uri.path().as_bytes());
/// assert_eq!(decoded_path, "/Hello, world!");
/// ```
pub fn percent_decode_lossy<'s>(string: &'s [u8]) -> Cow<'s, str> {
pub fn percent_decode_lossy(string: &[u8]) -> Cow<str> {
let decoder = url::percent_encoding::percent_decode(string);
decoder.decode_utf8_lossy()
}
@ -266,7 +266,7 @@ impl<'a> From<&'a str> for URI<'a> {
impl<'a> fmt::Display for URI<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// If this is the root path, then there are "zero" segments.
if self.as_str().starts_with("/") && self.segment_count() == 0 {
if self.as_str().starts_with('/') && self.segment_count() == 0 {
return write!(f, "/");
}
@ -389,7 +389,7 @@ impl URIBuf {
/// assert_eq!(uri.as_str(), "/a/b///c/d/e//f?name=Mike#end");
/// ```
#[inline(always)]
pub fn as_str<'a>(&'a self) -> &'a str {
pub fn as_str(&self) -> &str {
self.uri.as_str()
}
}

View File

@ -179,8 +179,7 @@ impl<'a, 'r, T: FromRequest<'a, 'r>> FromRequest<'a, 'r> for Option<T> {
fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> {
match T::from_request(request) {
Success(val) => Success(Some(val)),
Failure(_) => Success(None),
Forward(_) => Success(None),
Failure(_) | Forward(_) => Success(None),
}
}
}

View File

@ -284,7 +284,7 @@ impl<'a> FromSegments<'a> for PathBuf {
let decoded = URI::percent_decode(segment.as_bytes())?;
if decoded == ".." {
buf.pop();
} else if !(decoded.starts_with(".") || decoded.starts_with("*")) {
} else if !(decoded.starts_with('.') || decoded.starts_with('*')) {
buf.push(&*decoded)
}
}

View File

@ -163,8 +163,8 @@ pub trait Responder<'r> {
///
/// let mut response = "Hello".respond().unwrap();
///
/// let body_string = response.body().unwrap().to_string().unwrap();
/// assert_eq!(body_string, "Hello".to_string());
/// let body_string = response.body().and_then(|b| b.into_string());
/// assert_eq!(body_string, Some("Hello".to_string()));
///
/// let content_type: Vec<_> = response.get_header_values("Content-Type").collect();
/// assert_eq!(content_type.len(), 1);

View File

@ -29,7 +29,7 @@ impl<T> Body<T> {
}
impl<T: io::Read> Body<T> {
pub fn to_string(self) -> Option<String> {
pub fn into_string(self) -> Option<String> {
let (mut body, mut string) = match self {
Body::Sized(b, size) => (b, String::with_capacity(size as usize)),
Body::Chunked(b, _) => (b, String::new())
@ -163,6 +163,7 @@ impl<'r> ResponseBuilder<'r> {
// replaces, `join` adds. One more thing that could be done: we could make it
// some that _some_ headers default to replacing, and other to joining.
/// Return type of a thing.
#[derive(Default)]
pub struct Response<'r> {
status: Option<Status>,
headers: HeaderMap<'r>,

View File

@ -68,7 +68,7 @@ impl hyper::Handler for Rocket {
// Dispatch the request to get a response, then write that response out.
let response = self.dispatch(&mut request, data);
return self.issue_response(response, res);
self.issue_response(response, res)
}
}
@ -164,7 +164,7 @@ impl Rocket {
match self.route(request, data) {
Outcome::Success(mut response) => {
let cookie_delta = request.cookies().delta();
if cookie_delta.len() > 0 {
if !cookie_delta.is_empty() {
response.adjoin_header(header::SetCookie(cookie_delta));
}
@ -204,7 +204,7 @@ impl Rocket {
-> handler::Outcome<'r> {
// Go through the list of matching routes until we fail or succeed.
info!("{}:", request);
let matches = self.router.route(&request);
let matches = self.router.route(request);
for route in matches {
// Retrieve and set the requests parameters.
info_!("Matched: {}", route);
@ -212,14 +212,13 @@ impl Rocket {
request.set_params(route);
// Dispatch the request to the handler.
let outcome = (route.handler)(&request, data);
let outcome = (route.handler)(request, data);
// Check if the request processing completed or if the request needs
// to be forwarded. If it does, continue the loop to try again.
info_!("{} {}", White.paint("Outcome:"), outcome);
match outcome {
o@Outcome::Success(_) => return o,
o@Outcome::Failure(_) => return o,
o@Outcome::Success(_) | o @Outcome::Failure(_) => return o,
Outcome::Forward(unused_data) => data = unused_data,
};
}

View File

@ -97,10 +97,10 @@
//! let mut response = req.dispatch_with(&rocket);
//!
//! // Write the body out as a string.
//! let body_str = response.body().unwrap().to_string().unwrap();
//! let body_str = response.body().and_then(|b| b.into_string());
//!
//! // Check that the body contains what we expect.
//! assert_eq!(body_str, "Hello, world!".to_string());
//! assert_eq!(body_str, Some("Hello, world!".to_string()));
//! }
//! }
//! ```
@ -216,8 +216,8 @@ impl MockRequest {
/// let mut req = MockRequest::new(Get, "/");
/// let mut response = req.dispatch_with(&rocket);
///
/// let body_str = response.body().unwrap().to_string().unwrap();
/// assert_eq!(body_str, "Hello, world!".to_string());
/// let body_str = response.body().and_then(|b| b.into_string());
/// assert_eq!(body_str, Some("Hello, world!".to_string()));
/// # }
/// ```
pub fn dispatch_with<'r>(&'r mut self, rocket: &Rocket) -> Response<'r> {

View File

@ -45,7 +45,7 @@ fn auto_head() {
_ => panic!("Expected a sized body!")
}
assert_eq!(body.to_string(), Some("".to_string()));
assert_eq!(body.into_string(), Some("".to_string()));
} else {
panic!("Expected an empty body!")
}