Rocket

A web framework for Rust. https://rocket.rs (mirror)
git clone git://git.thc420.xyz/Rocket
Log | Files | Refs | README

commit 34cb1c14b865ec4a682fd60455cf13be96decf98
parent 90e37beb2f9ad704944df2f9b83547d6a3244df3
Author: Jeb Rosen <jeb@jebrosen.com>
Date:   Wed, 12 Jun 2019 18:48:02 -0700

Migrate core to Rust 2018.

Diffstat:
Mcore/lib/Cargo.toml | 1+
Mcore/lib/build.rs | 3---
Mcore/lib/src/catcher.rs | 22+++++++++++-----------
Mcore/lib/src/codegen.rs | 8++++----
Mcore/lib/src/config/builder.rs | 2+-
Mcore/lib/src/config/config.rs | 26+++++++++++++-------------
Mcore/lib/src/config/custom_values.rs | 15+++++++--------
Mcore/lib/src/config/environment.rs | 2+-
Mcore/lib/src/config/error.rs | 2+-
Mcore/lib/src/config/mod.rs | 16++++++++--------
Mcore/lib/src/config/toml_ext.rs | 10+++++-----
Mcore/lib/src/data/data.rs | 28++++++++++++++--------------
Mcore/lib/src/data/data_stream.rs | 6+++---
Mcore/lib/src/data/from_data.rs | 46+++++++++++++++++++++++-----------------------
Mcore/lib/src/data/net_stream.rs | 4++--
Mcore/lib/src/error.rs | 26+++++++++++++-------------
Mcore/lib/src/fairing/ad_hoc.rs | 16++++++++--------
Mcore/lib/src/fairing/fairings.rs | 14+++++++-------
Mcore/lib/src/fairing/info_kind.rs | 4++--
Mcore/lib/src/fairing/mod.rs | 26+++++++++++++-------------
Mcore/lib/src/handler.rs | 28++++++++++++++--------------
Mcore/lib/src/lib.rs | 33++++++++++++---------------------
Mcore/lib/src/local/client.rs | 10+++++-----
Mcore/lib/src/local/request.rs | 32++++++++++++++++----------------
Mcore/lib/src/logger.rs | 8++++----
Mcore/lib/src/outcome.rs | 13+++++++------
Mcore/lib/src/request/form/error.rs | 14+++++++-------
Mcore/lib/src/request/form/form.rs | 16++++++++--------
Mcore/lib/src/request/form/form_items.rs | 8++++----
Mcore/lib/src/request/form/from_form.rs | 6+++---
Mcore/lib/src/request/form/from_form_value.rs | 4++--
Mcore/lib/src/request/form/lenient.rs | 10+++++-----
Mcore/lib/src/request/from_request.rs | 68++++++++++++++++++++++++++++++++++----------------------------------
Mcore/lib/src/request/mod.rs | 2+-
Mcore/lib/src/request/param.rs | 6+++---
Mcore/lib/src/request/query.rs | 6+++---
Mcore/lib/src/request/request.rs | 40++++++++++++++++++++--------------------
Mcore/lib/src/request/state.rs | 20++++++++++----------
Mcore/lib/src/request/tests.rs | 4++--
Mcore/lib/src/response/content.rs | 10+++++-----
Mcore/lib/src/response/flash.rs | 12++++++------
Mcore/lib/src/response/mod.rs | 4++--
Mcore/lib/src/response/named_file.rs | 16++++++++--------
Mcore/lib/src/response/redirect.rs | 22+++++++++++-----------
Mcore/lib/src/response/responder.rs | 44++++++++++++++++++++++----------------------
Mcore/lib/src/response/response.rs | 46+++++++++++++++++++++++-----------------------
Mcore/lib/src/response/status.rs | 20++++++++++----------
Mcore/lib/src/response/stream.rs | 10+++++-----
Mcore/lib/src/rocket.rs | 48++++++++++++++++++++++++------------------------
Mcore/lib/src/router/collider.rs | 28++++++++++++++--------------
Mcore/lib/src/router/mod.rs | 26+++++++++++++-------------
Mcore/lib/src/router/route.rs | 32++++++++++++++++----------------
Mcore/lib/tests/derive-reexports.rs | 4++--
Mcore/lib/tests/flash-lazy-removes-issue-466.rs | 4++--
Mcore/lib/tests/mount_point.rs | 2--
Mcore/lib/tests/nested-fairing-attaches.rs | 4++--
Mcore/lib/tests/segments-issues-41-86.rs | 10+++++-----
57 files changed, 467 insertions(+), 480 deletions(-)

diff --git a/core/lib/Cargo.toml b/core/lib/Cargo.toml @@ -13,6 +13,7 @@ keywords = ["rocket", "web", "framework", "server"] license = "MIT/Apache-2.0" build = "build.rs" categories = ["web-programming::http-server"] +edition = "2018" [package.metadata.docs.rs] all-features = true diff --git a/core/lib/build.rs b/core/lib/build.rs @@ -1,8 +1,5 @@ //! Ensures Rocket isn't compiled with an incompatible version of Rust. -extern crate yansi; -extern crate version_check; - use yansi::{Paint, Color::{Red, Yellow, Blue}}; // Specifies the minimum nightly version needed to compile Rocket. diff --git a/core/lib/src/catcher.rs b/core/lib/src/catcher.rs @@ -1,7 +1,7 @@ -use response; -use handler::ErrorHandler; -use codegen::StaticCatchInfo; -use request::Request; +use crate::response; +use crate::handler::ErrorHandler; +use crate::codegen::StaticCatchInfo; +use crate::request::Request; use std::fmt; use yansi::Color::*; @@ -10,7 +10,7 @@ use yansi::Color::*; /// /// Catchers are routes that run when errors occur. They correspond directly /// with the HTTP error status code they will be handling and are registered -/// with Rocket via [`Rocket::register()`](::Rocket::register()). For example, +/// with Rocket via [`Rocket::register()`](crate::Rocket::register()). For example, /// to handle "404 not found" errors, a catcher for the "404" status code is /// registered. /// @@ -98,7 +98,7 @@ impl Catcher { } #[inline(always)] - crate fn handle<'r>(&self, req: &'r Request) -> response::Result<'r> { + crate fn handle<'r>(&self, req: &'r Request<'_>) -> response::Result<'r> { (self.handler)(req) } @@ -116,7 +116,7 @@ impl<'a> From<&'a StaticCatchInfo> for Catcher { } impl fmt::Display for Catcher { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", Blue.paint(&self.code)) } } @@ -149,7 +149,7 @@ macro_rules! default_catchers { let mut map = HashMap::new(); $( - fn $fn_name<'r>(req: &'r Request) -> response::Result<'r> { + fn $fn_name<'r>(req: &'r Request<'_>) -> response::Result<'r> { status::Custom(Status::from_code($code).unwrap(), content::Html(error_page_template!($code, $name, $description)) ).respond_to(req) @@ -167,9 +167,9 @@ pub mod defaults { use std::collections::HashMap; - use request::Request; - use response::{self, content, status, Responder}; - use http::Status; + use crate::request::Request; + use crate::response::{self, content, status, Responder}; + use crate::http::Status; pub fn get() -> HashMap<u16, Catcher> { default_catchers! { diff --git a/core/lib/src/codegen.rs b/core/lib/src/codegen.rs @@ -1,9 +1,9 @@ -use {Request, Data}; -use handler::{Outcome, ErrorHandler}; -use http::{Method, MediaType}; +use crate::{Request, Data}; +use crate::handler::{Outcome, ErrorHandler}; +use crate::http::{Method, MediaType}; /// Type of a static handler, which users annotate with Rocket's attribute. -pub type StaticHandler = for<'r> fn(&'r Request, Data) -> Outcome<'r>; +pub type StaticHandler = for<'r> fn(&'r Request<'_>, Data) -> Outcome<'r>; /// Information generated by the `route` attribute during codegen. pub struct StaticRouteInfo { diff --git a/core/lib/src/config/builder.rs b/core/lib/src/config/builder.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; -use config::{Result, Config, Value, Environment, Limits, LoggingLevel}; +use crate::config::{Result, Config, Value, Environment, Limits, LoggingLevel}; /// Structure following the builder pattern for building `Config` structures. #[derive(Clone)] diff --git a/core/lib/src/config/config.rs b/core/lib/src/config/config.rs @@ -4,13 +4,13 @@ use std::path::{Path, PathBuf}; use std::convert::AsRef; use std::fmt; +use crate::config::Environment::*; +use crate::config::{Result, ConfigBuilder, Environment, ConfigError, LoggingLevel}; +use crate::config::{Table, Value, Array, Datetime}; +use crate::http::private::Key; + use super::custom_values::*; use {num_cpus, base64}; -use config::Environment::*; -use config::{Result, ConfigBuilder, Environment, ConfigError, LoggingLevel}; -use config::{Table, Value, Array, Datetime}; - -use http::private::Key; /// Structure for Rocket application configuration. /// @@ -33,7 +33,7 @@ use http::private::Key; /// ## General Configuration /// /// For more information about Rocket's configuration, see the -/// [`config`](::config) module documentation. +/// [`config`](crate::config) module documentation. #[derive(Clone)] pub struct Config { /// The environment that this configuration corresponds to. @@ -96,7 +96,7 @@ impl Config { } /// Returns a `Config` with the default parameters for the environment - /// `env`. See [`config`](::config) for a list of defaults. + /// `env`. See [`config`](crate::config) for a list of defaults. /// /// # Example /// @@ -138,7 +138,7 @@ impl Config { } /// Returns a `Config` with the default parameters of the development - /// environment. See [`config`](::config) for a list of defaults. + /// environment. See [`config`](crate::config) for a list of defaults. /// /// # Example /// @@ -153,7 +153,7 @@ impl Config { } /// Returns a `Config` with the default parameters of the staging - /// environment. See [`config`](::config) for a list of defaults. + /// environment. See [`config`](crate::config) for a list of defaults. /// /// # Example /// @@ -168,7 +168,7 @@ impl Config { } /// Returns a `Config` with the default parameters of the production - /// environment. See [`config`](::config) for a list of defaults. + /// environment. See [`config`](crate::config) for a list of defaults. /// /// # Example /// @@ -518,7 +518,7 @@ impl Config { /// ``` #[cfg(feature = "tls")] pub fn set_tls(&mut self, certs_path: &str, key_path: &str) -> Result<()> { - use http::tls::util::{self, Error}; + use crate::http::tls::util::{self, Error}; let pem_err = "malformed PEM file"; @@ -908,7 +908,7 @@ impl Config { path.into() } else if let Some(root) = self.root() { root.join(path) - } else if let Ok(cwd) = ::std::env::current_dir() { + } else if let Ok(cwd) = std::env::current_dir() { cwd.join(path) } else { path.into() @@ -917,7 +917,7 @@ impl Config { } impl fmt::Debug for Config { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut s = f.debug_struct("Config"); s.field("environment", &self.environment); s.field("address", &self.address); diff --git a/core/lib/src/config/custom_values.rs b/core/lib/src/config/custom_values.rs @@ -1,10 +1,9 @@ use std::fmt; -#[cfg(feature = "tls")] -use http::tls::{Certificate, PrivateKey}; -use http::private::Key; +#[cfg(feature = "tls")] use crate::http::tls::{Certificate, PrivateKey}; -use config::{Result, Config, Value, ConfigError, LoggingLevel}; +use crate::http::private::Key; +use crate::config::{Result, Config, Value, ConfigError, LoggingLevel}; #[derive(Clone)] pub enum SecretKey { @@ -31,7 +30,7 @@ impl SecretKey { } impl fmt::Display for SecretKey { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { #[cfg(feature = "private-cookies")] match *self { SecretKey::Generated(_) => write!(f, "generated"), @@ -64,7 +63,7 @@ pub struct TlsConfig; /// /// # Defaults /// -/// As documented in [`config`](::config), the default limits are as follows: +/// As documented in [`config`](crate::config), the default limits are as follows: /// /// * **forms**: 32KiB /// @@ -180,8 +179,8 @@ impl Limits { } impl fmt::Display for Limits { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fn fmt_size(n: u64, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fn fmt_size(n: u64, f: &mut fmt::Formatter<'_>) -> fmt::Result { if (n & ((1 << 20) - 1)) == 0 { write!(f, "{}MiB", n >> 20) } else if (n & ((1 << 10) - 1)) == 0 { diff --git a/core/lib/src/config/environment.rs b/core/lib/src/config/environment.rs @@ -150,7 +150,7 @@ impl FromStr for Environment { } impl fmt::Display for Environment { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Development => write!(f, "development"), Staging => write!(f, "staging"), diff --git a/core/lib/src/config/error.rs b/core/lib/src/config/error.rs @@ -131,7 +131,7 @@ impl ConfigError { } impl fmt::Display for ConfigError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { NotFound => write!(f, "config file was not found"), IoError => write!(f, "I/O error while reading the config file"), diff --git a/core/lib/src/config/mod.rs b/core/lib/src/config/mod.rs @@ -158,7 +158,7 @@ //! [`Config`] structure. //! //! The retrivial of configuration parameters usually occurs at launch time via -//! a [launch fairing](::fairing::Fairing). If information about the +//! a [launch fairing](crate::fairing::Fairing). If information about the //! configuraiton is needed later in the program, an attach fairing can be used //! to store the information as managed state. As an example of the latter, //! consider the following short program which reads the `token` configuration @@ -203,15 +203,15 @@ pub use self::error::ConfigError; pub use self::environment::Environment; pub use self::config::Config; pub use self::builder::ConfigBuilder; -pub use logger::LoggingLevel; +pub use crate::logger::LoggingLevel; crate use self::toml_ext::LoggedValue; -use logger; +use crate::logger; use self::Environment::*; use self::environment::CONFIG_ENV; -use logger::COLORS_ENV; +use crate::logger::COLORS_ENV; use self::toml_ext::parse_simple_toml_value; -use http::uncased::uncased_eq; +use crate::http::uncased::uncased_eq; const CONFIG_FILENAME: &str = "Rocket.toml"; const GLOBAL_ENV_NAME: &str = "global"; @@ -219,7 +219,7 @@ const ENV_VAR_PREFIX: &str = "ROCKET_"; const PREHANDLED_VARS: [&str; 3] = ["ROCKET_CODEGEN_DEBUG", CONFIG_ENV, COLORS_ENV]; /// Wraps `std::result` with the error type of [`ConfigError`]. -pub type Result<T> = ::std::result::Result<T, ConfigError>; +pub type Result<T> = std::result::Result<T, ConfigError>; #[doc(hidden)] #[derive(Debug, PartialEq)] @@ -478,12 +478,12 @@ mod test { use super::Environment::*; use super::Result; - use ::logger::LoggingLevel; + use crate::logger::LoggingLevel; const TEST_CONFIG_FILENAME: &'static str = "/tmp/testing/Rocket.toml"; // TODO: It's a shame we have to depend on lazy_static just for this. - lazy_static! { + lazy_static::lazy_static! { static ref ENV_LOCK: Mutex<usize> = Mutex::new(0); } diff --git a/core/lib/src/config/toml_ext.rs b/core/lib/src/config/toml_ext.rs @@ -1,7 +1,7 @@ use std::fmt; use std::result::Result as StdResult; -use config::Value; +use crate::config::Value; use pear::{Result, parser, switch}; use pear::parsers::*; @@ -24,7 +24,7 @@ fn is_not_separator(byte: char) -> bool { #[inline(always)] fn is_ident_char(byte: char) -> bool { match byte { - '0'...'9' | 'A'...'Z' | 'a'...'z' | '_' | '-' => true, + '0'..='9' | 'A'..='Z' | 'a'..='z' | '_' | '-' => true, _ => false } } @@ -83,10 +83,10 @@ pub fn parse_simple_toml_value(mut input: &str) -> StdResult<Value, String> { /// `Display`. This is used to log config values at initialization. crate struct LoggedValue<'a>(pub &'a Value); -impl<'a> fmt::Display for LoggedValue<'a> { +impl fmt::Display for LoggedValue<'_> { #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use config::Value::*; + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + use crate::config::Value::*; match *self.0 { String(_) | Integer(_) | Float(_) | Boolean(_) | Datetime(_) | Array(_) => { self.0.fmt(f) diff --git a/core/lib/src/data/data.rs b/core/lib/src/data/data.rs @@ -7,15 +7,15 @@ use std::time::Duration; use super::data_stream::{DataStream, kill_stream}; use super::net_stream::NetStream; -use ext::ReadExt; +use crate::ext::ReadExt; -use http::hyper; -use http::hyper::h1::HttpReader; -use http::hyper::h1::HttpReader::*; -use http::hyper::net::{HttpStream, NetworkStream}; +use crate::http::hyper; +use crate::http::hyper::h1::HttpReader; +use crate::http::hyper::h1::HttpReader::*; +use crate::http::hyper::net::{HttpStream, NetworkStream}; pub type HyperBodyReader<'a, 'b> = - self::HttpReader<&'a mut hyper::buffer::BufReader<&'b mut NetworkStream>>; + self::HttpReader<&'a mut hyper::buffer::BufReader<&'b mut dyn NetworkStream>>; // |---- from hyper ----| pub type BodyReader = HttpReader<Chain<Cursor<Vec<u8>>, NetStream>>; @@ -27,13 +27,13 @@ const PEEK_BYTES: usize = 512; /// /// This type is the only means by which the body of a request can be retrieved. /// This type is not usually used directly. Instead, types that implement -/// [`FromData`](::data::Data) are used via code generation by specifying the -/// `data = "<var>"` route parameter as follows: +/// [`FromData`](crate::data::FromData) are used via code generation by +/// specifying the `data = "<var>"` route parameter as follows: /// /// ```rust /// # #![feature(proc_macro_hygiene, decl_macro)] /// # #[macro_use] extern crate rocket; -/// # type DataGuard = ::rocket::data::Data; +/// # type DataGuard = rocket::data::Data; /// #[post("/submit", data = "<var>")] /// fn submit(var: DataGuard) { /* ... */ } /// # fn main() { } @@ -79,22 +79,22 @@ impl Data { /// } /// ``` pub fn open(mut self) -> DataStream { - let buffer = ::std::mem::replace(&mut self.buffer, vec![]); + let buffer = std::mem::replace(&mut self.buffer, vec![]); let empty_stream = Cursor::new(vec![]).chain(NetStream::Empty); // FIXME: Insert a `BufReader` in front of the `NetStream` with capacity // 4096. We need the new `Chain` methods to get the inner reader to // actually do this, however. let empty_http_stream = HttpReader::SizedReader(empty_stream, 0); - let stream = ::std::mem::replace(&mut self.stream, empty_http_stream); + let stream = std::mem::replace(&mut self.stream, empty_http_stream); DataStream(Cursor::new(buffer).chain(stream)) } // FIXME: This is absolutely terrible (downcasting!), thanks to Hyper. - crate fn from_hyp(mut body: HyperBodyReader) -> Result<Data, &'static str> { + crate fn from_hyp(mut body: HyperBodyReader<'_, '_>) -> Result<Data, &'static str> { #[inline(always)] #[cfg(feature = "tls")] - fn concrete_stream(stream: &mut NetworkStream) -> Option<NetStream> { + fn concrete_stream(stream: &mut dyn NetworkStream) -> Option<NetStream> { stream.downcast_ref::<HttpsStream>() .map(|s| NetStream::Https(s.clone())) .or_else(|| { @@ -105,7 +105,7 @@ impl Data { #[inline(always)] #[cfg(not(feature = "tls"))] - fn concrete_stream(stream: &mut NetworkStream) -> Option<NetStream> { + fn concrete_stream(stream: &mut dyn NetworkStream) -> Option<NetStream> { stream.downcast_ref::<HttpStream>() .map(|s| NetStream::Http(s.clone())) } diff --git a/core/lib/src/data/data_stream.rs b/core/lib/src/data/data_stream.rs @@ -2,8 +2,8 @@ use std::io::{self, Read, Cursor, Chain}; use std::net::Shutdown; use super::data::BodyReader; -use http::hyper::net::NetworkStream; -use http::hyper::h1::HttpReader; +use crate::http::hyper::net::NetworkStream; +use crate::http::hyper::h1::HttpReader; // |-- peek buf --| pub type InnerStream = Chain<Cursor<Vec<u8>>, BodyReader>; @@ -11,7 +11,7 @@ pub type InnerStream = Chain<Cursor<Vec<u8>>, BodyReader>; /// Raw data stream of a request body. /// /// This stream can only be obtained by calling -/// [`Data::open()`](::data::Data::open()). The stream contains all of the data +/// [`Data::open()`](crate::data::Data::open()). The stream contains all of the data /// in the body of the request. It exposes no methods directly. Instead, it must /// be used as an opaque [`Read`] structure. pub struct DataStream(crate InnerStream); diff --git a/core/lib/src/data/from_data.rs b/core/lib/src/data/from_data.rs @@ -1,15 +1,15 @@ use std::borrow::Borrow; -use outcome::{self, IntoOutcome}; -use outcome::Outcome::*; -use http::Status; -use request::Request; -use data::Data; +use crate::outcome::{self, IntoOutcome}; +use crate::outcome::Outcome::*; +use crate::http::Status; +use crate::request::Request; +use crate::data::Data; /// Type alias for the `Outcome` of a `FromData` conversion. pub type Outcome<S, E> = outcome::Outcome<S, (Status, E), Data>; -impl<'a, S, E> IntoOutcome<S, (Status, E), Data> for Result<S, E> { +impl<S, E> IntoOutcome<S, (Status, E), Data> for Result<S, E> { type Failure = Status; type Forward = Data; @@ -125,7 +125,7 @@ pub type Transformed<'a, T> = /// implement `FromData`. Thus, when possible, prefer to implement /// [`FromDataSimple`] instead of `FromData`. /// -/// [request guard]: ::request::FromRequest +/// [request guard]: crate::request::FromRequest /// /// ## Example /// @@ -137,7 +137,7 @@ pub type Transformed<'a, T> = /// ```rust /// # #![feature(proc_macro_hygiene, decl_macro)] /// # #[macro_use] extern crate rocket; -/// # type DataGuard = ::rocket::data::Data; +/// # type DataGuard = rocket::data::Data; /// #[post("/submit", data = "<var>")] /// fn submit(var: DataGuard) { /* ... */ } /// # fn main() { } @@ -252,7 +252,7 @@ pub type Transformed<'a, T> = /// * **Failure**(Status, E) /// /// If the `Outcome` is [`Failure`], the request will fail with the given -/// status code and error. The designated error [`Catcher`](::Catcher) will be +/// status code and error. The designated error [`Catcher`](crate::Catcher) will be /// used to respond to the request. Note that users can request types of /// `Result<S, E>` and `Option<S>` to catch `Failure`s and retrieve the error /// value. @@ -354,7 +354,7 @@ pub trait FromData<'a>: Sized { /// If transformation succeeds, an outcome of `Success` is returned. /// If the data is not appropriate given the type of `Self`, `Forward` is /// returned. On failure, `Failure` is returned. - fn transform(request: &Request, data: Data) -> Transform<Outcome<Self::Owned, Self::Error>>; + fn transform(request: &Request<'_>, data: Data) -> Transform<Outcome<Self::Owned, Self::Error>>; /// Validates, parses, and converts the incoming request body data into an /// instance of `Self`. @@ -383,7 +383,7 @@ pub trait FromData<'a>: Sized { /// # unimplemented!() /// # } /// ``` - fn from_data(request: &Request, outcome: Transformed<'a, Self>) -> Outcome<Self, Self::Error>; + fn from_data(request: &Request<'_>, outcome: Transformed<'a, Self>) -> Outcome<Self, Self::Error>; } /// The identity implementation of `FromData`. Always returns `Success`. @@ -393,12 +393,12 @@ impl<'f> FromData<'f> for Data { type Borrowed = Data; #[inline(always)] - fn transform(_: &Request, data: Data) -> Transform<Outcome<Self::Owned, Self::Error>> { + fn transform(_: &Request<'_>, data: Data) -> Transform<Outcome<Self::Owned, Self::Error>> { Transform::Owned(Success(data)) } #[inline(always)] - fn from_data(_: &Request, outcome: Transformed<'f, Self>) -> Outcome<Self, Self::Error> { + fn from_data(_: &Request<'_>, outcome: Transformed<'f, Self>) -> Outcome<Self, Self::Error> { Success(outcome.owned()?) } } @@ -429,7 +429,7 @@ impl<'f> FromData<'f> for Data { /// ```rust /// # #![feature(proc_macro_hygiene, decl_macro)] /// # #[macro_use] extern crate rocket; -/// # type Person = ::rocket::data::Data; +/// # type Person = rocket::data::Data; /// #[post("/person", data = "<person>")] /// fn person(person: Person) -> &'static str { /// "Saved the new person to the database!" @@ -502,7 +502,7 @@ pub trait FromDataSimple: Sized { /// If validation and parsing succeeds, an outcome of `Success` is returned. /// If the data is not appropriate given the type of `Self`, `Forward` is /// returned. If parsing fails, `Failure` is returned. - fn from_data(request: &Request, data: Data) -> Outcome<Self, Self::Error>; + fn from_data(request: &Request<'_>, data: Data) -> Outcome<Self, Self::Error>; } impl<'a, T: FromDataSimple> FromData<'a> for T { @@ -511,12 +511,12 @@ impl<'a, T: FromDataSimple> FromData<'a> for T { type Borrowed = Data; #[inline(always)] - fn transform(_: &Request, d: Data) -> Transform<Outcome<Self::Owned, Self::Error>> { + fn transform(_: &Request<'_>, d: Data) -> Transform<Outcome<Self::Owned, Self::Error>> { Transform::Owned(Success(d)) } #[inline(always)] - fn from_data(req: &Request, o: Transformed<'a, Self>) -> Outcome<Self, Self::Error> { + fn from_data(req: &Request<'_>, o: Transformed<'a, Self>) -> Outcome<Self, Self::Error> { T::from_data(req, o.owned()?) } } @@ -527,12 +527,12 @@ impl<'a, T: FromData<'a> + 'a> FromData<'a> for Result<T, T::Error> { type Borrowed = T::Borrowed; #[inline(always)] - fn transform(r: &Request, d: Data) -> Transform<Outcome<Self::Owned, Self::Error>> { + fn transform(r: &Request<'_>, d: Data) -> Transform<Outcome<Self::Owned, Self::Error>> { T::transform(r, d) } #[inline(always)] - fn from_data(r: &Request, o: Transformed<'a, Self>) -> Outcome<Self, Self::Error> { + fn from_data(r: &Request<'_>, o: Transformed<'a, Self>) -> Outcome<Self, Self::Error> { match T::from_data(r, o) { Success(val) => Success(Ok(val)), Forward(data) => Forward(data), @@ -547,12 +547,12 @@ impl<'a, T: FromData<'a> + 'a> FromData<'a> for Option<T> { type Borrowed = T::Borrowed; #[inline(always)] - fn transform(r: &Request, d: Data) -> Transform<Outcome<Self::Owned, Self::Error>> { + fn transform(r: &Request<'_>, d: Data) -> Transform<Outcome<Self::Owned, Self::Error>> { T::transform(r, d) } #[inline(always)] - fn from_data(r: &Request, o: Transformed<'a, Self>) -> Outcome<Self, Self::Error> { + fn from_data(r: &Request<'_>, o: Transformed<'a, Self>) -> Outcome<Self, Self::Error> { match T::from_data(r, o) { Success(val) => Success(Some(val)), Failure(_) | Forward(_) => Success(None), @@ -568,7 +568,7 @@ impl FromDataSimple for String { type Error = io::Error; #[inline(always)] - fn from_data(_: &Request, data: Data) -> Outcome<Self, Self::Error> { + fn from_data(_: &Request<'_>, data: Data) -> Outcome<Self, Self::Error> { let mut string = String::new(); match data.open().read_to_string(&mut string) { Ok(_) => Success(string), @@ -582,7 +582,7 @@ impl FromDataSimple for Vec<u8> { type Error = io::Error; #[inline(always)] - fn from_data(_: &Request, data: Data) -> Outcome<Self, Self::Error> { + fn from_data(_: &Request<'_>, data: Data) -> Outcome<Self, Self::Error> { let mut bytes = Vec::new(); match data.open().read_to_end(&mut bytes) { Ok(_) => Success(bytes), diff --git a/core/lib/src/data/net_stream.rs b/core/lib/src/data/net_stream.rs @@ -2,8 +2,8 @@ use std::io; use std::net::{SocketAddr, Shutdown}; use std::time::Duration; -#[cfg(feature = "tls")] use http::tls::{WrappedStream, ServerSession}; -use http::hyper::net::{HttpStream, NetworkStream}; +#[cfg(feature = "tls")] use crate::http::tls::{WrappedStream, ServerSession}; +use crate::http::hyper::net::{HttpStream, NetworkStream}; use self::NetStream::*; diff --git a/core/lib/src/error.rs b/core/lib/src/error.rs @@ -5,8 +5,8 @@ use std::sync::atomic::{Ordering, AtomicBool}; use yansi::Paint; -use http::hyper; -use router::Route; +use crate::http::hyper; +use crate::router::Route; /// The kind of launch error that occurred. /// @@ -27,12 +27,12 @@ pub enum LaunchErrorKind { /// A launch fairing reported an error. FailedFairings(Vec<&'static str>), /// An otherwise uncategorized error occurred during launch. - Unknown(Box<::std::error::Error + Send + Sync>) + Unknown(Box<dyn std::error::Error + Send + Sync>) } /// An error that occurs during launch. /// -/// A `LaunchError` is returned by [`launch()`](::Rocket::launch()) when +/// A `LaunchError` is returned by [`launch()`](crate::Rocket::launch()) when /// launching an application fails. /// /// # Panics @@ -139,7 +139,7 @@ impl From<io::Error> for LaunchError { impl fmt::Display for LaunchErrorKind { #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { LaunchErrorKind::Bind(ref e) => write!(f, "binding failed: {}", e), LaunchErrorKind::Io(ref e) => write!(f, "I/O error: {}", e), @@ -152,7 +152,7 @@ impl fmt::Display for LaunchErrorKind { impl fmt::Debug for LaunchError { #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.mark_handled(); write!(f, "{:?}", self.kind()) } @@ -160,13 +160,13 @@ impl fmt::Debug for LaunchError { impl fmt::Display for LaunchError { #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.mark_handled(); write!(f, "{}", self.kind()) } } -impl ::std::error::Error for LaunchError { +impl std::error::Error for LaunchError { #[inline] fn description(&self) -> &str { self.mark_handled(); @@ -220,11 +220,11 @@ impl Drop for LaunchError { } } -use http::uri; -use http::ext::IntoOwned; -use http::route::{Error as SegmentError}; +use crate::http::uri; +use crate::http::ext::IntoOwned; +use crate::http::route::{Error as SegmentError}; -/// Error returned by [`set_uri()`](::Route::set_uri()) on invalid URIs. +/// Error returned by [`set_uri()`](crate::Route::set_uri()) on invalid URIs. #[derive(Debug)] pub enum RouteUriError { /// The base (mount point) or route path contains invalid segments. @@ -248,7 +248,7 @@ impl<'a> From<uri::Error<'a>> for RouteUriError { } impl fmt::Display for RouteUriError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { RouteUriError::Segment => { write!(f, "The URI contains malformed dynamic route path segments.") diff --git a/core/lib/src/fairing/ad_hoc.rs b/core/lib/src/fairing/ad_hoc.rs @@ -1,7 +1,7 @@ use std::sync::Mutex; -use {Rocket, Request, Response, Data}; -use fairing::{Fairing, Kind, Info}; +use crate::{Rocket, Request, Response, Data}; +use crate::fairing::{Fairing, Kind, Info}; /// A ad-hoc fairing that can be created from a function or closure. /// @@ -46,10 +46,10 @@ enum AdHocKind { /// An ad-hoc **launch** fairing. Called just before Rocket launches. Launch(Mutex<Option<Box<dyn FnOnce(&Rocket) + Send + 'static>>>), /// An ad-hoc **request** fairing. Called when a request is received. - Request(Box<dyn Fn(&mut Request, &Data) + Send + Sync + 'static>), + Request(Box<dyn Fn(&mut Request<'_>, &Data) + Send + Sync + 'static>), /// An ad-hoc **response** fairing. Called when a response is ready to be /// sent to a client. - Response(Box<dyn Fn(&Request, &mut Response) + Send + Sync + 'static>), + Response(Box<dyn Fn(&Request<'_>, &mut Response<'_>) + Send + Sync + 'static>), } impl AdHoc { @@ -104,7 +104,7 @@ impl AdHoc { /// }); /// ``` pub fn on_request<F>(name: &'static str, f: F) -> AdHoc - where F: Fn(&mut Request, &Data) + Send + Sync + 'static + where F: Fn(&mut Request<'_>, &Data) + Send + Sync + 'static { AdHoc { name, kind: AdHocKind::Request(Box::new(f)) } } @@ -124,7 +124,7 @@ impl AdHoc { /// }); /// ``` pub fn on_response<F>(name: &'static str, f: F) -> AdHoc - where F: Fn(&Request, &mut Response) + Send + Sync + 'static + where F: Fn(&Request<'_>, &mut Response<'_>) + Send + Sync + 'static { AdHoc { name, kind: AdHocKind::Response(Box::new(f)) } } @@ -160,13 +160,13 @@ impl Fairing for AdHoc { } } - fn on_request(&self, request: &mut Request, data: &Data) { + fn on_request(&self, request: &mut Request<'_>, data: &Data) { if let AdHocKind::Request(ref callback) = self.kind { callback(request, data) } } - fn on_response(&self, request: &Request, response: &mut Response) { + fn on_response(&self, request: &Request<'_>, response: &mut Response<'_>) { if let AdHocKind::Response(ref callback) = self.kind { callback(request, response) } diff --git a/core/lib/src/fairing/fairings.rs b/core/lib/src/fairing/fairings.rs @@ -1,11 +1,11 @@ -use {Rocket, Request, Response, Data}; -use fairing::{Fairing, Kind}; +use crate::{Rocket, Request, Response, Data}; +use crate::fairing::{Fairing, Kind}; use yansi::Paint; #[derive(Default)] pub struct Fairings { - all_fairings: Vec<Box<Fairing>>, + all_fairings: Vec<Box<dyn Fairing>>, attach_failures: Vec<&'static str>, // The vectors below hold indices into `all_fairings`. launch: Vec<usize>, @@ -19,7 +19,7 @@ impl Fairings { Fairings::default() } - pub fn attach(&mut self, fairing: Box<Fairing>, mut rocket: Rocket) -> Rocket { + pub fn attach(&mut self, fairing: Box<dyn Fairing>, mut rocket: Rocket) -> Rocket { // Run the `on_attach` callback if this is an 'attach' fairing. let kind = fairing.info().kind; let name = fairing.info().name; @@ -32,7 +32,7 @@ impl Fairings { rocket } - fn add(&mut self, fairing: Box<Fairing>) { + fn add(&mut self, fairing: Box<dyn Fairing>) { let kind = fairing.info().kind; if !kind.is_exactly(Kind::Attach) { let index = self.all_fairings.len(); @@ -58,14 +58,14 @@ impl Fairings { } #[inline(always)] - pub fn handle_request(&self, req: &mut Request, data: &Data) { + pub fn handle_request(&self, req: &mut Request<'_>, data: &Data) { for &i in &self.request { self.all_fairings[i].on_request(req, data); } } #[inline(always)] - pub fn handle_response(&self, request: &Request, response: &mut Response) { + pub fn handle_response(&self, request: &Request<'_>, response: &mut Response<'_>) { for &i in &self.response { self.all_fairings[i].on_response(request, response); } diff --git a/core/lib/src/fairing/info_kind.rs b/core/lib/src/fairing/info_kind.rs @@ -1,6 +1,6 @@ use std::ops::BitOr; -/// Information about a [`Fairing`](::fairing::Fairing). +/// Information about a [`Fairing`](crate::fairing::Fairing). /// /// The `name` field is an arbitrary name for a fairing. The `kind` field is a /// is an `or`d set of [`Kind`] structures. Rocket uses the values set in `Kind` @@ -30,7 +30,7 @@ pub struct Info { } /// A bitset representing the kinds of callbacks a -/// [`Fairing`](::fairing::Fairing) wishes to receive. +/// [`Fairing`](crate::fairing::Fairing) wishes to receive. /// /// A fairing can request any combination of any of the following kinds of /// callbacks: diff --git a/core/lib/src/fairing/mod.rs b/core/lib/src/fairing/mod.rs @@ -33,7 +33,7 @@ //! trait documentation for more information on the dispatching of fairing //! methods. //! -//! [`Fairing`]: ::fairing::Fairing +//! [`Fairing`]: crate::fairing::Fairing //! //! ## Ordering //! @@ -47,7 +47,7 @@ //! of other `Fairings` are not jeopardized. For instance, unless it is made //! abundantly clear, a fairing should not rewrite every request. -use {Rocket, Request, Response, Data}; +use crate::{Rocket, Request, Response, Data}; mod fairings; mod ad_hoc; @@ -88,9 +88,9 @@ pub use self::info_kind::{Info, Kind}; /// entire application. On the other hand, you _should_ use a fairing to record /// timing and/or usage statistics or to implement global security policies. /// -/// [request guard]: ::request::FromRequest -/// [request guards]: ::request::FromRequest -/// [data guards]: ::data::FromData +/// [request guard]: crate::request::FromRequest +/// [request guards]: crate::request::FromRequest +/// [data guards]: crate::data::FromData /// /// ## Fairing Callbacks /// @@ -194,7 +194,7 @@ pub use self::info_kind::{Info, Kind}; /// /// Imagine that we want to record the number of `GET` and `POST` requests that /// our application has received. While we could do this with [request guards] -/// and [managed state](::request::State), it would require us to annotate every +/// and [managed state](crate::request::State), it would require us to annotate every /// `GET` and `POST` request with custom types, polluting handler signatures. /// Instead, we can create a simple fairing that acts globally. /// @@ -308,10 +308,10 @@ pub use self::info_kind::{Info, Kind}; /// pub struct StartTime(pub SystemTime); /// /// // Allows a route to access the time a request was initiated. -/// impl<'a, 'r> FromRequest<'a, 'r> for StartTime { +/// impl FromRequest<'_, '_> for StartTime { /// type Error = (); /// -/// fn from_request(request: &'a Request<'r>) -> request::Outcome<StartTime, ()> { +/// fn from_request(request: &Request<'_>) -> request::Outcome<StartTime, ()> { /// match *request.local_cache(|| TimerStart(None)) { /// TimerStart(Some(time)) => Outcome::Success(StartTime(time)), /// TimerStart(None) => Outcome::Failure((Status::InternalServerError, ())), @@ -395,7 +395,7 @@ pub trait Fairing: Send + Sync + 'static { /// /// The default implementation of this method does nothing. #[allow(unused_variables)] - fn on_request(&self, request: &mut Request, data: &Data) {} + fn on_request(&self, request: &mut Request<'_>, data: &Data) {} /// The response callback. /// @@ -408,10 +408,10 @@ pub trait Fairing: Send + Sync + 'static { /// /// The default implementation of this method does nothing. #[allow(unused_variables)] - fn on_response(&self, request: &Request, response: &mut Response) {} + fn on_response(&self, request: &Request<'_>, response: &mut Response<'_>) {} } -impl<T: Fairing> Fairing for ::std::sync::Arc<T> { +impl<T: Fairing> Fairing for std::sync::Arc<T> { #[inline] fn info(&self) -> Info { (self as &T).info() @@ -428,12 +428,12 @@ impl<T: Fairing> Fairing for ::std::sync::Arc<T> { } #[inline] - fn on_request(&self, request: &mut Request, data: &Data) { + fn on_request(&self, request: &mut Request<'_>, data: &Data) { (self as &T).on_request(request, data) } #[inline] - fn on_response(&self, request: &Request, response: &mut Response) { + fn on_response(&self, request: &Request<'_>, response: &mut Response<'_>) { (self as &T).on_response(request, response) } } diff --git a/core/lib/src/handler.rs b/core/lib/src/handler.rs @@ -1,10 +1,10 @@ //! Types and traits for request and error handlers and their return values. -use data::Data; -use request::Request; -use response::{self, Response, Responder}; -use http::Status; -use outcome; +use crate::data::Data; +use crate::request::Request; +use crate::response::{self, Response, Responder}; +use crate::http::Status; +use crate::outcome; /// Type alias for the `Outcome` of a `Handler`. pub type Outcome<'r> = outcome::Outcome<Response<'r>, Status, Data>; @@ -142,7 +142,7 @@ pub trait Handler: Cloneable + Send + Sync + 'static { /// a response. Otherwise, if the return value is `Forward(Data)`, the next /// matching route is attempted. If there are no other matching routes, the /// `404` error catcher is invoked. - fn handle<'r>(&self, request: &'r Request, data: Data) -> Outcome<'r>; + fn handle<'r>(&self, request: &'r Request<'_>, data: Data) -> Outcome<'r>; } /// Unfortunate but necessary hack to be able to clone a `Box<Handler>`. @@ -152,34 +152,34 @@ pub trait Handler: Cloneable + Send + Sync + 'static { /// `Handler` automatically implement `Cloneable`. pub trait Cloneable { /// Clones `self`. - fn clone_handler(&self) -> Box<Handler>; + fn clone_handler(&self) -> Box<dyn Handler>; } impl<T: Handler + Clone> Cloneable for T { #[inline(always)] - fn clone_handler(&self) -> Box<Handler> { + fn clone_handler(&self) -> Box<dyn Handler> { Box::new(self.clone()) } } -impl Clone for Box<Handler> { +impl Clone for Box<dyn Handler> { #[inline(always)] - fn clone(&self) -> Box<Handler> { + fn clone(&self) -> Box<dyn Handler> { self.clone_handler() } } impl<F: Clone + Sync + Send + 'static> Handler for F - where for<'r> F: Fn(&'r Request, Data) -> Outcome<'r> + where for<'r> F: Fn(&'r Request<'_>, Data) -> Outcome<'r> { #[inline(always)] - fn handle<'r>(&self, req: &'r Request, data: Data) -> Outcome<'r> { + fn handle<'r>(&self, req: &'r Request<'_>, data: Data) -> Outcome<'r> { self(req, data) } } /// The type of an error handler. -pub type ErrorHandler = for<'r> fn(&'r Request) -> response::Result<'r>; +pub type ErrorHandler = for<'r> fn(&'r Request<'_>) -> response::Result<'r>; impl<'r> Outcome<'r> { /// Return the `Outcome` of response to `req` from `responder`. @@ -199,7 +199,7 @@ impl<'r> Outcome<'r> { /// } /// ``` #[inline] - pub fn from<T: Responder<'r>>(req: &Request, responder: T) -> Outcome<'r> { + pub fn from<T: Responder<'r>>(req: &Request<'_>, responder: T) -> Outcome<'r> { match responder.respond_to(req) { Ok(response) => outcome::Outcome::Success(response), Err(status) => outcome::Outcome::Failure(status) diff --git a/core/lib/src/lib.rs b/core/lib/src/lib.rs @@ -12,6 +12,8 @@ #![doc(html_favicon_url = "https://rocket.rs/v0.5/images/favicon.ico")] #![doc(html_logo_url = "https://rocket.rs/v0.5/images/logo-boxed.png")] +#![warn(rust_2018_idioms)] + //! # Rocket - Core API Documentation //! //! Hello, and welcome to the core Rocket API documentation! @@ -99,19 +101,8 @@ #[allow(unused_imports)] #[macro_use] extern crate rocket_codegen; #[doc(hidden)] pub use rocket_codegen::*; -extern crate rocket_http; #[macro_use] extern crate log; #[macro_use] extern crate pear; -extern crate yansi; -extern crate toml; -extern crate num_cpus; -extern crate state; -extern crate time; -extern crate memchr; -extern crate base64; -extern crate atty; - -#[cfg(test)] #[macro_use] extern crate lazy_static; #[doc(hidden)] #[macro_use] pub mod logger; pub mod local; @@ -141,16 +132,16 @@ mod codegen; mod catcher; mod ext; -#[doc(inline)] pub use response::Response; -#[doc(inline)] pub use handler::{Handler, ErrorHandler}; -#[doc(hidden)] pub use codegen::{StaticRouteInfo, StaticCatchInfo}; -#[doc(inline)] pub use outcome::Outcome; -#[doc(inline)] pub use data::Data; -#[doc(inline)] pub use config::Config; -pub use router::Route; -pub use request::{Request, State}; -pub use catcher::Catcher; -pub use rocket::Rocket; +#[doc(inline)] pub use crate::response::Response; +#[doc(inline)] pub use crate::handler::{Handler, ErrorHandler}; +#[doc(hidden)] pub use crate::codegen::{StaticRouteInfo, StaticCatchInfo}; +#[doc(inline)] pub use crate::outcome::Outcome; +#[doc(inline)] pub use crate::data::Data; +#[doc(inline)] pub use crate::config::Config; +pub use crate::router::Route; +pub use crate::request::{Request, State}; +pub use crate::catcher::Catcher; +pub use crate::rocket::Rocket; /// Alias to [`Rocket::ignite()`] Creates a new instance of `Rocket`. pub fn ignite() -> Rocket { diff --git a/core/lib/src/local/client.rs b/core/lib/src/local/client.rs @@ -1,10 +1,10 @@ use std::sync::RwLock; use std::borrow::Cow; -use Rocket; -use local::LocalRequest; -use http::{Method, private::CookieJar}; -use error::LaunchError; +use crate::Rocket; +use crate::local::LocalRequest; +use crate::http::{Method, private::CookieJar}; +use crate::error::LaunchError; /// A structure to construct requests for local dispatching. /// @@ -16,7 +16,7 @@ use error::LaunchError; /// [`post()`], and so on) can be used to create a `LocalRequest` for /// dispatching. /// -/// See the [top-level documentation](::local) for more usage information. +/// See the [top-level documentation](crate::local) for more usage information. /// /// ## Cookie Tracking /// diff --git a/core/lib/src/local/request.rs b/core/lib/src/local/request.rs @@ -4,9 +4,9 @@ use std::net::SocketAddr; use std::ops::{Deref, DerefMut}; use std::borrow::Cow; -use {Request, Response, Data}; -use http::{Status, Method, Header, Cookie, uri::Origin, ext::IntoOwned}; -use local::Client; +use crate::{Request, Response, Data}; +use crate::http::{Status, Method, Header, Cookie, uri::Origin, ext::IntoOwned}; +use crate::local::Client; /// A structure representing a local request as created by [`Client`]. /// @@ -56,7 +56,7 @@ use local::Client; /// same request needs to be dispatched multiple times, the request can first be /// cloned and then dispatched: `request.clone().dispatch()`. /// -/// [`Client`]: ::local::Client +/// [`Client`]: crate::local::Client /// [`header`]: #method.header /// [`add_header`]: #method.add_header /// [`cookie`]: #method.cookie @@ -119,7 +119,7 @@ impl<'c> LocalRequest<'c> { // See the comments on the structure for what's going on here. let mut request = Rc::new(request); - let ptr = Rc::get_mut(&mut request).unwrap() as *mut Request; + let ptr = Rc::get_mut(&mut request).unwrap() as *mut Request<'_>; LocalRequest { client, ptr, request, uri, data: vec![] } } @@ -160,8 +160,8 @@ impl<'c> LocalRequest<'c> { /// Any type that implements `Into<Header>` can be used here. Among others, /// this includes [`ContentType`] and [`Accept`]. /// - /// [`ContentType`]: ::http::ContentType - /// [`Accept`]: ::http::Accept + /// [`ContentType`]: crate::http::ContentType + /// [`Accept`]: crate::http::Accept /// /// # Examples /// @@ -236,7 +236,7 @@ impl<'c> LocalRequest<'c> { /// .cookie(Cookie::new("user_id", "12")); /// ``` #[inline] - pub fn cookie(self, cookie: Cookie) -> Self { + pub fn cookie(self, cookie: Cookie<'_>) -> Self { self.request.cookies().add_original(cookie.into_owned()); self } @@ -257,7 +257,7 @@ impl<'c> LocalRequest<'c> { /// let req = client.get("/").cookies(cookies); /// ``` #[inline] - pub fn cookies(self, cookies: Vec<Cookie>) -> Self { + pub fn cookies(self, cookies: Vec<Cookie<'_>>) -> Self { for cookie in cookies { self.request.cookies().add_original(cookie.into_owned()); } @@ -270,7 +270,7 @@ impl<'c> LocalRequest<'c> { /// This method is only available when the `private-cookies` feature is /// enabled. /// - /// [private cookie]: ::http::Cookies::add_private() + /// [private cookie]: crate::http::Cookies::add_private() /// /// # Examples /// @@ -384,7 +384,7 @@ impl<'c> LocalRequest<'c> { #[inline(always)] pub fn mut_dispatch(&mut self) -> LocalResponse<'c> { let req = self.long_lived_request(); - let data = ::std::mem::replace(&mut self.data, vec![]); + let data = std::mem::replace(&mut self.data, vec![]); let rc_req = self.request.clone(); LocalRequest::_dispatch(self.client, req, rc_req, &self.uri, data) } @@ -414,7 +414,7 @@ impl<'c> LocalRequest<'c> { // with the changes reflected by `response`. if let Some(ref jar) = client.cookies { let mut jar = jar.write().expect("LocalRequest::_dispatch() write lock"); - let current_time = ::time::now(); + let current_time = time::now(); for cookie in response.cookies() { if let Some(expires) = cookie.expires() { if expires <= current_time { @@ -434,8 +434,8 @@ impl<'c> LocalRequest<'c> { } } -impl<'c> fmt::Debug for LocalRequest<'c> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +impl fmt::Debug for LocalRequest<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.request, f) } } @@ -468,8 +468,8 @@ impl<'c> DerefMut for LocalResponse<'c> { } } -impl<'c> fmt::Debug for LocalResponse<'c> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +impl fmt::Debug for LocalResponse<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.response, f) } } diff --git a/core/lib/src/logger.rs b/core/lib/src/logger.rs @@ -52,7 +52,7 @@ impl FromStr for LoggingLevel { } impl fmt::Display for LoggingLevel { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let string = match *self { LoggingLevel::Critical => "critical", LoggingLevel::Normal => "normal", @@ -83,14 +83,14 @@ macro_rules! warn_ { ($($args:expr),+) => { log_!(warn: $($args),+); }; } impl log::Log for RocketLogger { #[inline(always)] - fn enabled(&self, record: &log::Metadata) -> bool { + fn enabled(&self, record: &log::Metadata<'_>) -> bool { match self.0.to_level_filter().to_level() { Some(max) => record.level() <= max || record.target().starts_with("launch"), None => false } } - fn log(&self, record: &log::Record) { + fn log(&self, record: &log::Record<'_>) { // Print nothing if this level isn't enabled and this isn't launch info. if !self.enabled(record.metadata()) { return; @@ -150,7 +150,7 @@ crate fn try_init(level: LoggingLevel, verbose: bool) -> bool { return false; } - if !::atty::is(::atty::Stream::Stdout) + if !atty::is(atty::Stream::Stdout) || (cfg!(windows) && !Paint::enable_windows_ascii()) || env::var_os(COLORS_ENV).map(|v| v == "0" || v == "off").unwrap_or(false) { diff --git a/core/lib/src/outcome.rs b/core/lib/src/outcome.rs @@ -9,9 +9,10 @@ //! processing next. //! //! The `Outcome` type is the return type of many of the core Rocket traits, -//! including [`FromRequest`](::request::FromRequest), -//! [`FromData`](::data::FromData), and [`Responder`](::response::Responder). It -//! is also the return type of request handlers via the [`Response`] type. +//! including [`FromRequest`](crate::request::FromRequest), +//! [`FromData`](crate::data::FromData), and +//! [`Responder`](crate::response::Responder). It is also the return type of +//! request handlers via the [`Response`] type. //! //! # Success //! @@ -87,7 +88,7 @@ use self::Outcome::*; /// An enum representing success (`Success`), failure (`Failure`), or /// forwarding (`Forward`). /// -/// See the [top level documentation](::outcome) for detailed information. +/// See the [top level documentation](crate::outcome) for detailed information. #[must_use] #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] pub enum Outcome<S, E, F> { @@ -625,13 +626,13 @@ impl<S, E, F> Try for Outcome<S, E, F> { } impl<S, E, F> fmt::Debug for Outcome<S, E, F> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Outcome::{}", self.formatting().1) } } impl<S, E, F> fmt::Display for Outcome<S, E, F> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let (color, string) = self.formatting(); write!(f, "{}", Paint::default(string).fg(color)) } diff --git a/core/lib/src/request/form/error.rs b/core/lib/src/request/form/error.rs @@ -1,7 +1,7 @@ use std::io; -use http::RawStr; +use crate::http::RawStr; -/// Error returned by the [`FromForm`](::request::FromForm) derive on form +/// Error returned by the [`FromForm`](crate::request::FromForm) derive on form /// parsing errors. /// /// If multiple errors occur while parsing a form, the first error in the @@ -22,8 +22,8 @@ pub enum FormParseError<'f> { Missing(&'f RawStr), } -/// Error returned by the [`FromData`](::data::FromData) implementations of -/// [`Form`](::request::Form) and [`LenientForm`](::request::LenientForm). +/// Error returned by the [`FromData`](crate::data::FromData) implementations of +/// [`Form`](crate::request::Form) and [`LenientForm`](crate::request::LenientForm). #[derive(Debug)] pub enum FormDataError<'f, E> { /// An I/O error occurred while reading reading the data stream. This can @@ -43,9 +43,9 @@ pub enum FormDataError<'f, E> { /// /// This alias is particularly useful when "catching" form errors in routes. /// -/// [`FromData`]: ::data::FromData -/// [`Form<T>`]: ::request::Form -/// [`FromForm`]: ::request::FromForm +/// [`FromData`]: crate::data::FromData +/// [`Form<T>`]: crate::request::Form +/// [`FromForm`]: crate::request::FromForm /// /// # Example /// diff --git a/core/lib/src/request/form/form.rs b/core/lib/src/request/form/form.rs @@ -1,9 +1,9 @@ use std::ops::Deref; -use outcome::Outcome::*; -use request::{Request, form::{FromForm, FormItems, FormDataError}}; -use data::{Outcome, Transform, Transformed, Data, FromData}; -use http::{Status, uri::{Query, FromUriParam}}; +use crate::outcome::Outcome::*; +use crate::request::{Request, form::{FromForm, FormItems, FormDataError}}; +use crate::data::{Outcome, Transform, Transformed, Data, FromData}; +use crate::http::{Status, uri::{Query, FromUriParam}}; /// A data guard for parsing [`FromForm`] types strictly. /// @@ -17,7 +17,7 @@ use http::{Status, uri::{Query, FromUriParam}}; /// error on missing and/or extra fields. For instance, if an incoming form /// contains the fields "a", "b", and "c" while `T` only contains "a" and "c", /// the form _will not_ parse as `Form<T>`. If you would like to admit extra -/// fields without error, see [`LenientForm`](::request::LenientForm). +/// fields without error, see [`LenientForm`](crate::request::LenientForm). /// /// # Usage /// @@ -89,7 +89,7 @@ use http::{Status, uri::{Query, FromUriParam}}; /// depends on your use case. The primary question to answer is: _Can the input /// contain characters that must be URL encoded?_ Note that this includes common /// characters such as spaces. If so, then you must use `String`, whose -/// [`FromFormValue`](::request::FromFormValue) implementation automatically URL +/// [`FromFormValue`](crate::request::FromFormValue) implementation automatically URL /// decodes the value. Because the `&RawStr` references will refer directly to /// the underlying form data, they will be raw and URL encoded. /// @@ -190,7 +190,7 @@ impl<'f, T: FromForm<'f>> FromData<'f> for Form<T> { type Borrowed = str; fn transform( - request: &Request, + request: &Request<'_>, data: Data ) -> Transform<Outcome<Self::Owned, Self::Error>> { use std::{cmp::min, io::Read}; @@ -214,7 +214,7 @@ impl<'f, T: FromForm<'f>> FromData<'f> for Form<T> { Transform::Borrowed(outcome) } - fn from_data(_: &Request, o: Transformed<'f, Self>) -> Outcome<Self, Self::Error> { + fn from_data(_: &Request<'_>, o: Transformed<'f, Self>) -> Outcome<Self, Self::Error> { <Form<T>>::from_data(o.borrowed()?, true).map(Form) } } diff --git a/core/lib/src/request/form/form_items.rs b/core/lib/src/request/form/form_items.rs @@ -1,6 +1,6 @@ use memchr::memchr2; -use http::RawStr; +use crate::http::RawStr; /// Iterator over the key/value pairs of a given HTTP form string. /// @@ -211,7 +211,7 @@ impl<'f> FormItem<'f> { } } -impl<'f> FormItems<'f> { +impl FormItems<'_> { /// Returns `true` if the form string was parsed to completion. Returns /// `false` otherwise. All valid form strings will parse to completion, /// while invalid form strings will not. @@ -380,7 +380,7 @@ impl<'f> Iterator for FormItems<'f> { // #[inline(always)] // fn from(triples: &'f [(&'f str, &'f str, &'f str)]) -> FormItems<'f> { // // Safe because RawStr(str) is repr(transparent). -// let triples = unsafe { ::std::mem::transmute(triples) }; +// let triples = unsafe { std::mem::transmute(triples) }; // FormItems::Cooked { triples, next_index: 0 } // } // } @@ -391,7 +391,7 @@ impl<'f> Iterator for FormItems<'f> { // } // fn check_form<'a, T>(items: T, expected: Option<&[(&str, &str, &str)]>) -// where T: Into<FormItems<'a>> + ::std::fmt::Debug +// where T: Into<FormItems<'a>> + std::fmt::Debug // { // let string = format!("{:?}", items); // let mut items = items.into(); diff --git a/core/lib/src/request/form/from_form.rs b/core/lib/src/request/form/from_form.rs @@ -1,13 +1,13 @@ -use request::FormItems; +use crate::request::FormItems; /// Trait to create an instance of some type from an HTTP form. -/// [`Form`](::request::Form) requires its generic type to implement this trait. +/// [`Form`](crate::request::Form) requires its generic type to implement this trait. /// /// # Deriving /// /// This trait can be automatically derived. When deriving `FromForm`, every /// field in the structure must implement -/// [`FromFormValue`](::request::FromFormValue). Rocket validates each field in +/// [`FromFormValue`](crate::request::FromFormValue). Rocket validates each field in /// the structure by calling its `FromFormValue` implementation. You may wish to /// implement `FromFormValue` for your own types for custom, automatic /// validation. diff --git a/core/lib/src/request/form/from_form_value.rs b/core/lib/src/request/form/from_form_value.rs @@ -1,13 +1,13 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6, SocketAddr}; use std::str::FromStr; -use http::RawStr; +use crate::http::RawStr; /// Trait to parse a typed value from a form value. /// /// This trait is used by Rocket's code generation in two places: /// -/// 1. Fields in structs deriving [`FromForm`](::request::FromForm) are +/// 1. Fields in structs deriving [`FromForm`](crate::request::FromForm) are /// required to implement this trait. /// 2. Types of dynamic query parameters (`?<param>`) are required to /// implement this trait. diff --git a/core/lib/src/request/form/lenient.rs b/core/lib/src/request/form/lenient.rs @@ -1,8 +1,8 @@ use std::ops::Deref; -use request::{Request, form::{Form, FormDataError, FromForm}}; -use data::{Data, Transform, Transformed, FromData, Outcome}; -use http::uri::{Query, FromUriParam}; +use crate::request::{Request, form::{Form, FormDataError, FromForm}}; +use crate::data::{Data, Transform, Transformed, FromData, Outcome}; +use crate::http::uri::{Query, FromUriParam}; /// A data guard for parsing [`FromForm`] types leniently. /// @@ -100,11 +100,11 @@ impl<'f, T: FromForm<'f>> FromData<'f> for LenientForm<T> { type Owned = String; type Borrowed = str; - fn transform(r: &Request, d: Data) -> Transform<Outcome<Self::Owned, Self::Error>> { + fn transform(r: &Request<'_>, d: Data) -> Transform<Outcome<Self::Owned, Self::Error>> { <Form<T>>::transform(r, d) } - fn from_data(_: &Request, o: Transformed<'f, Self>) -> Outcome<Self, Self::Error> { + fn from_data(_: &Request<'_>, o: Transformed<'f, Self>) -> Outcome<Self, Self::Error> { <Form<T>>::from_data(o.borrowed()?, false).map(LenientForm) } } diff --git a/core/lib/src/request/from_request.rs b/core/lib/src/request/from_request.rs @@ -1,12 +1,12 @@ use std::fmt::Debug; use std::net::SocketAddr; -use router::Route; -use request::Request; -use outcome::{self, IntoOutcome}; -use outcome::Outcome::*; +use crate::router::Route; +use crate::request::Request; +use crate::outcome::{self, IntoOutcome}; +use crate::outcome::Outcome::*; -use http::{Status, ContentType, Accept, Method, Cookies, uri::Origin}; +use crate::http::{Status, ContentType, Accept, Method, Cookies, uri::Origin}; /// Type alias for the `Outcome` of a `FromRequest` conversion. pub type Outcome<S, E> = outcome::Outcome<S, (Status, E), ()>; @@ -82,7 +82,7 @@ impl<S, E> IntoOutcome<S, (Status, E), ()> for Result<S, E> { /// * **Failure**(Status, E) /// /// If the `Outcome` is [`Failure`], the request will fail with the given -/// status code and error. The designated error [`Catcher`](::Catcher) will be +/// status code and error. The designated error [`Catcher`](crate::Catcher) will be /// used to respond to the request. Note that users can request types of /// `Result<S, E>` and `Option<S>` to catch `Failure`s and retrieve the error /// value. @@ -186,10 +186,10 @@ impl<S, E> IntoOutcome<S, (Status, E), ()> for Result<S, E> { /// Invalid, /// } /// -/// impl<'a, 'r> FromRequest<'a, 'r> for ApiKey { +/// impl FromRequest<'_, '_> for ApiKey { /// type Error = ApiKeyError; /// -/// fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> { +/// fn from_request(request: &Request<'_>) -> request::Outcome<Self, Self::Error> { /// let keys: Vec<_> = request.headers().get("x-api-key").collect(); /// match keys.len() { /// 0 => Outcome::Failure((Status::BadRequest, ApiKeyError::Missing)), @@ -232,19 +232,19 @@ impl<S, E> IntoOutcome<S, (Status, E), ()> for Result<S, E> { /// # Ok(User { id, is_admin: false }) /// # } /// # } -/// # impl<'a, 'r> FromRequest<'a, 'r> for Database { +/// # impl FromRequest<'_, '_> for Database { /// # type Error = (); -/// # fn from_request(request: &'a Request<'r>) -> request::Outcome<Database, ()> { +/// # fn from_request(request: &Request<'_>) -> request::Outcome<Database, ()> { /// # Outcome::Success(Database) /// # } /// # } /// # /// # struct Admin { user: User } /// # -/// impl<'a, 'r> FromRequest<'a, 'r> for User { +/// impl FromRequest<'_, '_> for User { /// type Error = (); /// -/// fn from_request(request: &'a Request<'r>) -> request::Outcome<User, ()> { +/// fn from_request(request: &Request<'_>) -> request::Outcome<User, ()> { /// let db = request.guard::<Database>()?; /// request.cookies() /// .get_private("user_id") @@ -254,10 +254,10 @@ impl<S, E> IntoOutcome<S, (Status, E), ()> for Result<S, E> { /// } /// } /// -/// impl<'a, 'r> FromRequest<'a, 'r> for Admin { +/// impl FromRequest<'_, '_> for Admin { /// type Error = (); /// -/// fn from_request(request: &'a Request<'r>) -> request::Outcome<Admin, ()> { +/// fn from_request(request: &Request<'_>) -> request::Outcome<Admin, ()> { /// // This will unconditionally query the database! /// let user = request.guard::<User>()?; /// @@ -296,19 +296,19 @@ impl<S, E> IntoOutcome<S, (Status, E), ()> for Result<S, E> { /// # Ok(User { id, is_admin: false }) /// # } /// # } -/// # impl<'a, 'r> FromRequest<'a, 'r> for Database { +/// # impl FromRequest<'_, '_> for Database { /// # type Error = (); -/// # fn from_request(request: &'a Request<'r>) -> request::Outcome<Database, ()> { +/// # fn from_request(request: &Request<'_>) -> request::Outcome<Database, ()> { /// # Outcome::Success(Database) /// # } /// # } /// # /// # struct Admin<'a> { user: &'a User } /// # -/// impl<'a, 'r> FromRequest<'a, 'r> for &'a User { +/// impl<'a> FromRequest<'a, '_> for &'a User { /// type Error = !; /// -/// fn from_request(request: &'a Request<'r>) -> request::Outcome<&'a User, !> { +/// fn from_request(request: &'a Request<'_>) -> request::Outcome<&'a User, !> { /// // This closure will execute at most once per request, regardless of /// // the number of times the `User` guard is executed. /// let user_result = request.local_cache(|| { @@ -323,10 +323,10 @@ impl<S, E> IntoOutcome<S, (Status, E), ()> for Result<S, E> { /// } /// } /// -/// impl<'a, 'r> FromRequest<'a, 'r> for Admin<'a> { +/// impl<'a> FromRequest<'a, '_> for Admin<'a> { /// type Error = !; /// -/// fn from_request(request: &'a Request<'r>) -> request::Outcome<Admin<'a>, !> { +/// fn from_request(request: &'a Request<'_>) -> request::Outcome<Admin<'a>, !> { /// let user = request.guard::<&User>()?; /// /// if user.is_admin { @@ -357,26 +357,26 @@ pub trait FromRequest<'a, 'r>: Sized { fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error>; } -impl<'a, 'r> FromRequest<'a, 'r> for Method { +impl FromRequest<'_, '_> for Method { type Error = !; - fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> { + fn from_request(request: &Request<'_>) -> Outcome<Self, Self::Error> { Success(request.method()) } } -impl<'a, 'r> FromRequest<'a, 'r> for &'a Origin<'a> { +impl<'a> FromRequest<'a, '_> for &'a Origin<'a> { type Error = !; - fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> { + fn from_request(request: &'a Request<'_>) -> Outcome<Self, Self::Error> { Success(request.uri()) } } -impl<'a, 'r> FromRequest<'a, 'r> for &'r Route { +impl<'r> FromRequest<'_, 'r> for &'r Route { type Error = !; - fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> { + fn from_request(request: &Request<'r>) -> Outcome<Self, Self::Error> { match request.route() { Some(route) => Success(route), None => Forward(()) @@ -384,18 +384,18 @@ impl<'a, 'r> FromRequest<'a, 'r> for &'r Route { } } -impl<'a, 'r> FromRequest<'a, 'r> for Cookies<'a> { +impl<'a> FromRequest<'a, '_> for Cookies<'a> { type Error = !; - fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> { + fn from_request(request: &'a Request<'_>) -> Outcome<Self, Self::Error> { Success(request.cookies()) } } -impl<'a, 'r> FromRequest<'a, 'r> for &'a Accept { +impl<'a> FromRequest<'a, '_> for &'a Accept { type Error = !; - fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> { + fn from_request(request: &'a Request<'_>) -> Outcome<Self, Self::Error> { match request.accept() { Some(accept) => Success(accept), None => Forward(()) @@ -403,10 +403,10 @@ impl<'a, 'r> FromRequest<'a, 'r> for &'a Accept { } } -impl<'a, 'r> FromRequest<'a, 'r> for &'a ContentType { +impl<'a> FromRequest<'a, '_> for &'a ContentType { type Error = !; - fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> { + fn from_request(request: &'a Request<'_>) -> Outcome<Self, Self::Error> { match request.content_type() { Some(content_type) => Success(content_type), None => Forward(()) @@ -414,10 +414,10 @@ impl<'a, 'r> FromRequest<'a, 'r> for &'a ContentType { } } -impl<'a, 'r> FromRequest<'a, 'r> for SocketAddr { +impl FromRequest<'_, '_> for SocketAddr { type Error = !; - fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> { + fn from_request(request: &Request<'_>) -> Outcome<Self, Self::Error> { match request.remote() { Some(addr) => Success(addr), None => Forward(()) diff --git a/core/lib/src/request/mod.rs b/core/lib/src/request/mod.rs @@ -22,4 +22,4 @@ pub use self::state::State; pub use self::query::{Query, FromQuery}; #[doc(inline)] -pub use response::flash::FlashMessage; +pub use crate::response::flash::FlashMessage; diff --git a/core/lib/src/request/param.rs b/core/lib/src/request/param.rs @@ -3,7 +3,7 @@ use std::path::PathBuf; use std::fmt::Debug; use std::borrow::Cow; -use http::{RawStr, uri::{Segments, SegmentError}}; +use crate::http::{RawStr, uri::{Segments, SegmentError}}; /// Trait to convert a dynamic path segment string to a concrete value. /// @@ -322,10 +322,10 @@ impl<'a> FromSegments<'a> for Segments<'a> { /// As a result of these conditions, a `PathBuf` derived via `FromSegments` is /// safe to interpolate within, or use as a suffix of, a path without additional /// checks. -impl<'a> FromSegments<'a> for PathBuf { +impl FromSegments<'_> for PathBuf { type Error = SegmentError; - fn from_segments(segments: Segments<'a>) -> Result<PathBuf, SegmentError> { + fn from_segments(segments: Segments<'_>) -> Result<PathBuf, SegmentError> { segments.into_path_buf(false) } } diff --git a/core/lib/src/request/query.rs b/core/lib/src/request/query.rs @@ -1,4 +1,4 @@ -use request::{FormItems, FormItem, Form, LenientForm, FromForm}; +use crate::request::{FormItems, FormItem, Form, LenientForm, FromForm}; /// Iterator over form items in a query string. /// @@ -34,9 +34,9 @@ use request::{FormItems, FormItem, Form, LenientForm, FromForm}; /// # use rocket::request::FromQuery; /// # /// # struct MyType; -/// # type Result = ::std::result::Result<MyType, ()>; +/// # type Result = std::result::Result<MyType, ()>; /// # -/// # impl<'q> FromQuery<'q> for MyType { +/// # impl FromQuery<'_> for MyType { /// # type Error = (); /// # /// fn from_query(query: Query) -> Result { diff --git a/core/lib/src/request/request.rs b/core/lib/src/request/request.rs @@ -7,16 +7,16 @@ use std::str; use yansi::Paint; use state::{Container, Storage}; -use request::{FromParam, FromSegments, FromRequest, Outcome}; -use request::{FromFormValue, FormItems, FormItem}; +use crate::request::{FromParam, FromSegments, FromRequest, Outcome}; +use crate::request::{FromFormValue, FormItems, FormItem}; -use rocket::Rocket; -use router::Route; -use config::{Config, Limits}; -use http::{hyper, uri::{Origin, Segments}}; -use http::{Method, Header, HeaderMap, Cookies}; -use http::{RawStr, ContentType, Accept, MediaType}; -use http::private::{Indexed, SmallVec, CookieJar}; +use crate::rocket::Rocket; +use crate::router::Route; +use crate::config::{Config, Limits}; +use crate::http::{hyper, uri::{Origin, Segments}}; +use crate::http::{Method, Header, HeaderMap, Cookies}; +use crate::http::{RawStr, ContentType, Accept, MediaType}; +use crate::http::private::{Indexed, SmallVec, CookieJar}; type Indices = (usize, usize); @@ -135,7 +135,7 @@ impl<'r> Request<'r> { /// # }); /// ``` #[inline(always)] - pub fn uri(&self) -> &Origin { + pub fn uri(&self) -> &Origin<'_> { &self.uri } @@ -287,7 +287,7 @@ impl<'r> Request<'r> { /// request.cookies().add(Cookie::new("ans", format!("life: {}", 38 + 4))); /// # }); /// ``` - pub fn cookies(&self) -> Cookies { + pub fn cookies(&self) -> Cookies<'_> { // FIXME: Can we do better? This is disappointing. match self.state.cookies.try_borrow_mut() { Ok(jar) => Cookies::new(jar, self.state.config.secret_key()), @@ -696,7 +696,7 @@ impl<'r> Request<'r> { #[doc(hidden)] impl<'r> Request<'r> { // Only used by doc-tests! Needs to be `pub` because doc-test are external. - pub fn example<F: Fn(&mut Request)>(method: Method, uri: &str, f: F) { + pub fn example<F: Fn(&mut Request<'_>)>(method: Method, uri: &str, f: F) { let rocket = Rocket::custom(Config::development()); let uri = Origin::parse(uri).expect("invalid URI in example"); let mut request = Request::new(&rocket, method, uri); @@ -732,7 +732,7 @@ impl<'r> Request<'r> { /// Get the segments beginning at the `n`th, 0-indexed, after the mount /// point for the currently matched route, if they exist. Used by codegen. #[inline] - pub fn raw_segments(&self, n: usize) -> Option<Segments> { + pub fn raw_segments(&self, n: usize) -> Option<Segments<'_>> { self.routed_path_segment(n) .map(|(i, _)| Segments(&self.uri.path()[i..]) ) } @@ -759,7 +759,7 @@ impl<'r> Request<'r> { #[inline] pub fn raw_query_items( &self - ) -> Option<impl Iterator<Item = FormItem> + DoubleEndedIterator + Clone> { + ) -> Option<impl Iterator<Item = FormItem<'_>> + DoubleEndedIterator + Clone> { let query = self.uri.query()?; self.state.query_items.as_ref().map(move |items| { items.iter().map(move |item| item.convert(query)) @@ -811,7 +811,7 @@ impl<'r> Request<'r> { if let Some(cookie_headers) = h_headers.get_raw("Cookie") { let mut cookie_jar = CookieJar::new(); for header in cookie_headers { - let raw_str = match ::std::str::from_utf8(header) { + let raw_str = match std::str::from_utf8(header) { Ok(string) => string, Err(_) => continue }; @@ -842,8 +842,8 @@ impl<'r> Request<'r> { } } -impl<'r> fmt::Debug for Request<'r> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { +impl fmt::Debug for Request<'_> { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Request") .field("method", &self.method) .field("uri", &self.uri) @@ -853,10 +853,10 @@ impl<'r> fmt::Debug for Request<'r> { } } -impl<'r> fmt::Display for Request<'r> { +impl fmt::Display for Request<'_> { /// Pretty prints a Request. This is primarily used by Rocket's logging /// infrastructure. - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} {}", Paint::green(self.method()), Paint::blue(&self.uri))?; // Print the requests media type when the route specifies a format. @@ -872,7 +872,7 @@ impl<'r> fmt::Display for Request<'r> { impl IndexedFormItem { #[inline(always)] - fn from(s: &str, i: FormItem) -> Self { + fn from(s: &str, i: FormItem<'_>) -> Self { let (r, k, v) = (indices(i.raw, s), indices(i.key, s), indices(i.value, s)); IndexedFormItem { raw: r, key: k, value: v } } diff --git a/core/lib/src/request/state.rs b/core/lib/src/request/state.rs @@ -1,9 +1,9 @@ use std::ops::Deref; -use Rocket; -use request::{self, FromRequest, Request}; -use outcome::Outcome; -use http::Status; +use crate::Rocket; +use crate::request::{self, FromRequest, Request}; +use crate::outcome::Outcome; +use crate::http::Status; /// Request guard to retrieve managed state. /// @@ -11,7 +11,7 @@ use http::Status; /// managing for some type `T`. This allows for the sharing of state across any /// number of handlers. A value for the given type must previously have been /// registered to be managed by Rocket via -/// [`Rocket::manage()`](::Rocket::manage()). The type being managed must be +/// [`Rocket::manage()`]. The type being managed must be /// thread safe and sendable across thread boundaries. In other words, it must /// implement [`Send`] + [`Sync`] + 'static`. /// @@ -70,10 +70,10 @@ use http::Status; /// # struct MyConfig{ user_val: String }; /// struct Item(String); /// -/// impl<'a, 'r> FromRequest<'a, 'r> for Item { +/// impl FromRequest<'_, '_> for Item { /// type Error = (); /// -/// fn from_request(request: &'a Request<'r>) -> request::Outcome<Item, ()> { +/// fn from_request(request: &Request<'_>) -> request::Outcome<Item, ()> { /// request.guard::<State<MyConfig>>() /// .map(|my_config| Item(my_config.user_val.clone())) /// } @@ -165,11 +165,11 @@ impl<'r, T: Send + Sync + 'static> State<'r, T> { } } -impl<'a, 'r, T: Send + Sync + 'static> FromRequest<'a, 'r> for State<'r, T> { +impl<'r, T: Send + Sync + 'static> FromRequest<'_, 'r> for State<'r, T> { type Error = (); #[inline(always)] - fn from_request(req: &'a Request<'r>) -> request::Outcome<State<'r, T>, ()> { + fn from_request(req: &Request<'r>) -> request::Outcome<State<'r, T>, ()> { match req.state.managed.try_get::<T>() { Some(state) => Outcome::Success(State(state)), None => { @@ -180,7 +180,7 @@ impl<'a, 'r, T: Send + Sync + 'static> FromRequest<'a, 'r> for State<'r, T> { } } -impl<'r, T: Send + Sync + 'static> Deref for State<'r, T> { +impl<T: Send + Sync + 'static> Deref for State<'_, T> { type Target = T; #[inline(always)] diff --git a/core/lib/src/request/tests.rs b/core/lib/src/request/tests.rs @@ -1,8 +1,8 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::collections::HashMap; -use {Rocket, Request, Config}; -use http::hyper; +use crate::{Rocket, Request, Config}; +use crate::http::hyper; macro_rules! assert_headers { ($($key:expr => [$($value:expr),+]),+) => ({ diff --git a/core/lib/src/response/content.rs b/core/lib/src/response/content.rs @@ -22,9 +22,9 @@ //! let response = content::Html("<h1>Hello, world!</h1>"); //! ``` -use request::Request; -use response::{Response, Responder}; -use http::{Status, ContentType}; +use crate::request::Request; +use crate::response::{Response, Responder}; +use crate::http::{Status, ContentType}; /// Sets the Content-Type of a `Responder` to a chosen value. /// @@ -48,7 +48,7 @@ pub struct Content<R>(pub ContentType, pub R); /// delegates the remainder of the response to the wrapped responder. impl<'r, R: Responder<'r>> Responder<'r> for Content<R> { #[inline(always)] - fn respond_to(self, req: &Request) -> Result<Response<'r>, Status> { + fn respond_to(self, req: &Request<'_>) -> Result<Response<'r>, Status> { Response::build() .merge(self.1.respond_to(req)?) .header(self.0) @@ -72,7 +72,7 @@ macro_rules! ctrs { /// Sets the Content-Type of the response then delegates the /// remainder of the response to the wrapped responder. impl<'r, R: Responder<'r>> Responder<'r> for $name<R> { - fn respond_to(self, req: &Request) -> Result<Response<'r>, Status> { + fn respond_to(self, req: &Request<'_>) -> Result<Response<'r>, Status> { Content(ContentType::$ct, self.0).respond_to(req) } } diff --git a/core/lib/src/response/flash.rs b/core/lib/src/response/flash.rs @@ -2,10 +2,10 @@ use std::convert::AsRef; use time::Duration; -use outcome::IntoOutcome; -use response::{Response, Responder}; -use request::{self, Request, FromRequest}; -use http::{Status, Cookie}; +use crate::outcome::IntoOutcome; +use crate::response::{Response, Responder}; +use crate::request::{self, Request, FromRequest}; +use crate::http::{Status, Cookie}; use std::sync::atomic::{AtomicBool, Ordering}; // The name of the actual flash cookie. @@ -100,7 +100,7 @@ pub struct Flash<R> { /// /// [`name()`]: Flash::name() /// [`msg()`]: Flash::msg() -pub type FlashMessage<'a, 'r> = ::response::Flash<&'a Request<'r>>; +pub type FlashMessage<'a, 'r> = crate::response::Flash<&'a Request<'r>>; impl<'r, R: Responder<'r>> Flash<R> { /// Constructs a new `Flash` message with the given `name`, `msg`, and @@ -194,7 +194,7 @@ impl<'r, R: Responder<'r>> Flash<R> { /// response handling to the wrapped responder. As a result, the `Outcome` of /// the response is the `Outcome` of the wrapped `Responder`. impl<'r, R: Responder<'r>> Responder<'r> for Flash<R> { - fn respond_to(self, req: &Request) -> Result<Response<'r>, Status> { + fn respond_to(self, req: &Request<'_>) -> Result<Response<'r>, Status> { trace_!("Flash: setting message: {}:{}", self.name, self.message); req.cookies().add(self.cookie()); self.inner.respond_to(req) diff --git a/core/lib/src/response/mod.rs b/core/lib/src/response/mod.rs @@ -1,7 +1,7 @@ //! Types and traits to build and send responses. //! //! The return type of a Rocket handler can be any type that implements the -//! [`Responder`](::response::Responder) trait, which means that the type knows +//! [`Responder`](crate::response::Responder) trait, which means that the type knows //! how to generate a [`Response`]. Among other things, this module contains //! several such types. //! @@ -42,4 +42,4 @@ pub use self::stream::Stream; #[doc(inline)] pub use self::content::Content; /// Type alias for the `Result` of a `Responder::respond` call. -pub type Result<'r> = ::std::result::Result<self::Response<'r>, ::http::Status>; +pub type Result<'r> = std::result::Result<self::Response<'r>, crate::http::Status>; diff --git a/core/lib/src/response/named_file.rs b/core/lib/src/response/named_file.rs @@ -3,9 +3,9 @@ use std::path::{Path, PathBuf}; use std::io; use std::ops::{Deref, DerefMut}; -use request::Request; -use response::{self, Responder}; -use http::ContentType; +use crate::request::Request; +use crate::response::{self, Responder}; +use crate::http::ContentType; /// A file with an associated name; responds with the Content-Type based on the /// file extension. @@ -78,8 +78,8 @@ impl NamedFile { /// recognized. See [`ContentType::from_extension()`] for more information. If /// you would like to stream a file with a different Content-Type than that /// implied by its extension, use a [`File`] directly. -impl<'r> Responder<'r> for NamedFile { - fn respond_to(self, req: &Request) -> response::Result<'r> { +impl Responder<'_> for NamedFile { + fn respond_to(self, req: &Request<'_>) -> response::Result<'static> { let mut response = self.1.respond_to(req)?; if let Some(ext) = self.0.extension() { if let Some(ct) = ContentType::from_extension(&ext.to_string_lossy()) { @@ -131,7 +131,7 @@ impl io::Seek for NamedFile { } } -impl<'a> io::Read for &'a NamedFile { +impl io::Read for &NamedFile { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.file().read(buf) } @@ -141,7 +141,7 @@ impl<'a> io::Read for &'a NamedFile { } } -impl<'a> io::Write for &'a NamedFile { +impl io::Write for &NamedFile { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.file().write(buf) } @@ -151,7 +151,7 @@ impl<'a> io::Write for &'a NamedFile { } } -impl<'a> io::Seek for &'a NamedFile { +impl io::Seek for &NamedFile { fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> { self.file().seek(pos) } diff --git a/core/lib/src/response/redirect.rs b/core/lib/src/response/redirect.rs @@ -1,9 +1,9 @@ use std::convert::TryInto; -use request::Request; -use response::{Response, Responder}; -use http::uri::Uri; -use http::Status; +use crate::request::Request; +use crate::response::{Response, Responder}; +use crate::http::uri::Uri; +use crate::http::Status; /// An empty redirect response to a given URL. /// @@ -16,10 +16,10 @@ use http::Status; /// /// * `String` /// * `&'static str` -/// * [`Origin`](::http::uri::Origin) -/// * [`Authority`](::http::uri::Authority) -/// * [`Absolute`](::http::uri::Absolute) -/// * [`Uri`](::http::uri::Uri) +/// * [`Origin`](crate::http::uri::Origin) +/// * [`Authority`](crate::http::uri::Authority) +/// * [`Absolute`](crate::http::uri::Absolute) +/// * [`Uri`](crate::http::uri::Uri) /// /// Any non-`'static` strings must first be allocated using `.to_string()` or /// similar before being passed to a `Redirect` constructor. When redirecting to @@ -41,7 +41,7 @@ use http::Status; /// } /// ``` /// -/// [`Origin`]: ::http::uri::Origin +/// [`Origin`]: crate::http::uri::Origin /// [`uri!`]: ../../rocket_codegen/macro.uri.html #[derive(Debug)] pub struct Redirect(Status, Option<Uri<'static>>); @@ -147,8 +147,8 @@ impl Redirect { /// the `Location` header field. The body of the response is empty. If the URI /// value used to create the `Responder` is an invalid URI, an error of /// `Status::InternalServerError` is returned. -impl<'a> Responder<'a> for Redirect { - fn respond_to(self, _: &Request) -> Result<Response<'static>, Status> { +impl Responder<'_> for Redirect { + fn respond_to(self, _: &Request<'_>) -> Result<Response<'static>, Status> { if let Some(uri) = self.1 { Response::build() .status(self.0) diff --git a/core/lib/src/response/responder.rs b/core/lib/src/response/responder.rs @@ -2,9 +2,9 @@ use std::fs::File; use std::io::{Cursor, BufReader}; use std::fmt; -use http::{Status, ContentType, StatusClass}; -use response::{self, Response, Body}; -use request::Request; +use crate::http::{Status, ContentType, StatusClass}; +use crate::response::{self, Response, Body}; +use crate::request::Request; /// Trait implemented by types that generate responses for clients. /// @@ -70,7 +70,7 @@ use request::Request; /// /// Responds with a streamed body containing the data in the `File`. No /// `Content-Type` is set. To automatically have a `Content-Type` set based -/// on the file's extension, use [`NamedFile`](::response::NamedFile). +/// on the file's extension, use [`NamedFile`](crate::response::NamedFile). /// /// * **()** /// @@ -165,8 +165,8 @@ use request::Request; /// use rocket::response::{self, Response, Responder}; /// use rocket::http::ContentType; /// -/// impl<'r> Responder<'r> for Person { -/// fn respond_to(self, _: &Request) -> response::Result<'r> { +/// impl Responder<'_> for Person { +/// fn respond_to(self, _: &Request) -> response::Result<'static> { /// Response::build() /// .sized_body(Cursor::new(format!("{}:{}", self.name, self.age))) /// .raw_header("X-Person-Name", self.name) @@ -192,13 +192,13 @@ pub trait Responder<'r> { /// returned, the error catcher for the given status is retrieved and called /// to generate a final error response, which is then written out to the /// client. - fn respond_to(self, request: &Request) -> response::Result<'r>; + fn respond_to(self, request: &Request<'_>) -> response::Result<'r>; } /// Returns a response with Content-Type `text/plain` and a fixed-size body /// containing the string `self`. Always returns `Ok`. impl<'r> Responder<'r> for &'r str { - fn respond_to(self, _: &Request) -> response::Result<'r> { + fn respond_to(self, _: &Request<'_>) -> response::Result<'r> { Response::build() .header(ContentType::Plain) .sized_body(Cursor::new(self)) @@ -208,8 +208,8 @@ impl<'r> Responder<'r> for &'r str { /// Returns a response with Content-Type `text/plain` and a fixed-size body /// containing the string `self`. Always returns `Ok`. -impl<'r> Responder<'r> for String { - fn respond_to(self, _: &Request) -> response::Result<'r> { +impl Responder<'_> for String { + fn respond_to(self, _: &Request<'_>) -> response::Result<'static> { Response::build() .header(ContentType::Plain) .sized_body(Cursor::new(self)) @@ -220,7 +220,7 @@ impl<'r> Responder<'r> for String { /// Returns a response with Content-Type `application/octet-stream` and a /// fixed-size body containing the data in `self`. Always returns `Ok`. impl<'r> Responder<'r> for &'r [u8] { - fn respond_to(self, _: &Request) -> response::Result<'r> { + fn respond_to(self, _: &Request<'_>) -> response::Result<'r> { Response::build() .header(ContentType::Binary) .sized_body(Cursor::new(self)) @@ -230,8 +230,8 @@ impl<'r> Responder<'r> for &'r [u8] { /// Returns a response with Content-Type `application/octet-stream` and a /// fixed-size body containing the data in `self`. Always returns `Ok`. -impl<'r> Responder<'r> for Vec<u8> { - fn respond_to(self, _: &Request) -> response::Result<'r> { +impl Responder<'_> for Vec<u8> { + fn respond_to(self, _: &Request<'_>) -> response::Result<'static> { Response::build() .header(ContentType::Binary) .sized_body(Cursor::new(self)) @@ -240,8 +240,8 @@ impl<'r> Responder<'r> for Vec<u8> { } /// Returns a response with a sized body for the file. Always returns `Ok`. -impl<'r> Responder<'r> for File { - fn respond_to(self, _: &Request) -> response::Result<'r> { +impl Responder<'_> for File { + fn respond_to(self, _: &Request<'_>) -> response::Result<'static> { let (metadata, file) = (self.metadata(), BufReader::new(self)); match metadata { Ok(md) => Response::build().raw_body(Body::Sized(file, md.len())).ok(), @@ -251,8 +251,8 @@ impl<'r> Responder<'r> for File { } /// Returns an empty, default `Response`. Always returns `Ok`. -impl<'r> Responder<'r> for () { - fn respond_to(self, _: &Request) -> response::Result<'r> { +impl Responder<'_> for () { + fn respond_to(self, _: &Request<'_>) -> response::Result<'static> { Ok(Response::new()) } } @@ -260,7 +260,7 @@ impl<'r> Responder<'r> for () { /// If `self` is `Some`, responds with the wrapped `Responder`. Otherwise prints /// a warning message and returns an `Err` of `Status::NotFound`. impl<'r, R: Responder<'r>> Responder<'r> for Option<R> { - fn respond_to(self, req: &Request) -> response::Result<'r> { + fn respond_to(self, req: &Request<'_>) -> response::Result<'r> { self.map_or_else(|| { warn_!("Response was `None`."); Err(Status::NotFound) @@ -272,7 +272,7 @@ impl<'r, R: Responder<'r>> Responder<'r> for Option<R> { /// an error message with the `Err` value returns an `Err` of /// `Status::InternalServerError`. impl<'r, R: Responder<'r>, E: fmt::Debug> Responder<'r> for Result<R, E> { - default fn respond_to(self, req: &Request) -> response::Result<'r> { + default fn respond_to(self, req: &Request<'_>) -> response::Result<'r> { self.map(|r| r.respond_to(req)).unwrap_or_else(|e| { error_!("Response was a non-`Responder` `Err`: {:?}.", e); Err(Status::InternalServerError) @@ -283,7 +283,7 @@ impl<'r, R: Responder<'r>, E: fmt::Debug> Responder<'r> for Result<R, E> { /// Responds with the wrapped `Responder` in `self`, whether it is `Ok` or /// `Err`. impl<'r, R: Responder<'r>, E: Responder<'r> + fmt::Debug> Responder<'r> for Result<R, E> { - fn respond_to(self, req: &Request) -> response::Result<'r> { + fn respond_to(self, req: &Request<'_>) -> response::Result<'r> { match self { Ok(responder) => responder.respond_to(req), Err(responder) => responder.respond_to(req), @@ -305,8 +305,8 @@ impl<'r, R: Responder<'r>, E: Responder<'r> + fmt::Debug> Responder<'r> for Resu /// `100` responds with any empty body and the given status code, and all other /// status code emit an error message and forward to the `500` (internal server /// error) catcher. -impl<'r> Responder<'r> for Status { - fn respond_to(self, _: &Request) -> response::Result<'r> { +impl Responder<'_> for Status { + fn respond_to(self, _: &Request<'_>) -> response::Result<'static> { match self.class() { StatusClass::ClientError | StatusClass::ServerError => Err(self), StatusClass::Success if self.code < 206 => { diff --git a/core/lib/src/response/response.rs b/core/lib/src/response/response.rs @@ -1,8 +1,8 @@ use std::{io, fmt, str}; use std::borrow::Cow; -use response::Responder; -use http::{Header, HeaderMap, Status, ContentType, Cookie}; +use crate::response::Responder; +use crate::http::{Header, HeaderMap, Status, ContentType, Cookie}; /// The default size, in bytes, of a chunk for streamed responses. pub const DEFAULT_CHUNK_SIZE: u64 = 4096; @@ -88,7 +88,7 @@ impl<T: io::Read> Body<T> { } impl<T> fmt::Debug for Body<T> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Body::Sized(_, n) => writeln!(f, "Sized Body [{} bytes]", n), Body::Chunked(_, n) => writeln!(f, "Chunked Body [{} bytes]", n), @@ -223,8 +223,8 @@ impl<'r> ResponseBuilder<'r> { /// value will remain. /// /// The type of `header` can be any type that implements `Into<Header>`. - /// This includes `Header` itself, [`ContentType`](::http::ContentType) and - /// [hyper::header types](::http::hyper::header). + /// This includes `Header` itself, [`ContentType`](crate::http::ContentType) and + /// [hyper::header types](crate::http::hyper::header). /// /// # Example /// @@ -253,8 +253,8 @@ impl<'r> ResponseBuilder<'r> { /// potentially different values to be present in the `Response`. /// /// The type of `header` can be any type that implements `Into<Header>`. - /// This includes `Header` itself, [`ContentType`](::http::ContentType) and - /// [hyper::header types](::http::hyper::header). + /// This includes `Header` itself, [`ContentType`](crate::http::ContentType) and + /// [hyper::header types](crate::http::hyper::header). /// /// # Example /// @@ -533,7 +533,7 @@ impl<'r> ResponseBuilder<'r> { /// ``` #[inline(always)] pub fn finalize(&mut self) -> Response<'r> { - ::std::mem::replace(&mut self.response, Response::new()) + std::mem::replace(&mut self.response, Response::new()) } /// Retrieve the built `Response` wrapped in `Ok`. @@ -560,7 +560,7 @@ impl<'r> ResponseBuilder<'r> { pub struct Response<'r> { status: Option<Status>, headers: HeaderMap<'r>, - body: Option<Body<Box<io::Read + 'r>>>, + body: Option<Body<Box<dyn io::Read + 'r>>>, } impl<'r> Response<'r> { @@ -707,7 +707,7 @@ impl<'r> Response<'r> { /// response.set_header(Cookie::new("hello", "world!")); /// assert_eq!(response.cookies(), vec![Cookie::new("hello", "world!")]); /// ``` - pub fn cookies(&self) -> Vec<Cookie> { + pub fn cookies(&self) -> Vec<Cookie<'_>> { let mut cookies = vec![]; for header in self.headers().get("Set-Cookie") { if let Ok(cookie) = Cookie::parse_encoded(header) { @@ -743,8 +743,8 @@ impl<'r> Response<'r> { /// Sets the header `header` in `self`. Any existing headers with the name /// `header.name` will be lost, and only `header` will remain. The type of /// `header` can be any type that implements `Into<Header>`. This includes - /// `Header` itself, [`ContentType`](::http::ContentType) and - /// [`hyper::header` types](::http::hyper::header). + /// `Header` itself, [`ContentType`](crate::http::ContentType) and + /// [`hyper::header` types](crate::http::hyper::header). /// /// # Example /// @@ -799,8 +799,8 @@ impl<'r> Response<'r> { /// name `header.name`, another header with the same name and value /// `header.value` is added. The type of `header` can be any type that /// implements `Into<Header>`. This includes `Header` itself, - /// [`ContentType`](::http::ContentType) and [`hyper::header` - /// types](::http::hyper::header). + /// [`ContentType`](crate::http::ContentType) and [`hyper::header` + /// types](crate::http::hyper::header). /// /// # Example /// @@ -826,8 +826,8 @@ impl<'r> Response<'r> { /// `self` already contains headers with the name `name`, another header /// with the same `name` and `value` is added. The type of `header` can be /// any type implements `Into<Header>`. This includes `Header` itself, - /// [`ContentType`](::http::ContentType) and [`hyper::header` - /// types](::http::hyper::header). + /// [`ContentType`](crate::http::ContentType) and [`hyper::header` + /// types](crate::http::hyper::header). /// /// # Example /// @@ -889,7 +889,7 @@ impl<'r> Response<'r> { /// assert_eq!(response.body_string(), Some("Hello, world!".to_string())); /// ``` #[inline(always)] - pub fn body(&mut self) -> Option<Body<&mut io::Read>> { + pub fn body(&mut self) -> Option<Body<&mut dyn io::Read>> { // Looks crazy, right? Needed so Rust infers lifetime correctly. Weird. match self.body.as_mut() { Some(body) => Some(match body.as_mut() { @@ -966,7 +966,7 @@ impl<'r> Response<'r> { /// assert!(response.body().is_none()); /// ``` #[inline(always)] - pub fn take_body(&mut self) -> Option<Body<Box<io::Read + 'r>>> { + pub fn take_body(&mut self) -> Option<Body<Box<dyn io::Read + 'r>>> { self.body.take() } @@ -1015,7 +1015,7 @@ impl<'r> Response<'r> { /// Sets the body of `self` to be `body`, which will be streamed. The chunk /// size of the stream is - /// [DEFAULT_CHUNK_SIZE](::response::DEFAULT_CHUNK_SIZE). Use + /// [DEFAULT_CHUNK_SIZE](crate::response::DEFAULT_CHUNK_SIZE). Use /// [set_chunked_body](#method.set_chunked_body) for custom chunk sizes. /// /// # Example @@ -1176,8 +1176,8 @@ impl<'r> Response<'r> { } } -impl<'r> fmt::Debug for Response<'r> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +impl fmt::Debug for Response<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!(f, "{}", self.status())?; for header in self.headers().iter() { @@ -1191,11 +1191,11 @@ impl<'r> fmt::Debug for Response<'r> { } } -use request::Request; +use crate::request::Request; impl<'r> Responder<'r> for Response<'r> { /// This is the identity implementation. It simply returns `Ok(self)`. - fn respond_to(self, _: &Request) -> Result<Response<'r>, Status> { + fn respond_to(self, _: &Request<'_>) -> Result<Response<'r>, Status> { Ok(self) } } diff --git a/core/lib/src/response/status.rs b/core/lib/src/response/status.rs @@ -10,10 +10,10 @@ use std::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher; -use request::Request; -use response::{Responder, Response}; -use http::hyper::header; -use http::Status; +use crate::request::Request; +use crate::response::{Responder, Response}; +use crate::http::hyper::header; +use crate::http::Status; /// Sets the status of the response to 201 (Created). /// @@ -41,7 +41,7 @@ pub struct Created<R>(pub String, pub Option<R>); /// information about the created resource. If no responder is provided, the /// response body will be empty. impl<'r, R: Responder<'r>> Responder<'r> for Created<R> { - default fn respond_to(self, req: &Request) -> Result<Response<'r>, Status> { + default fn respond_to(self, req: &Request<'_>) -> Result<Response<'r>, Status> { let mut build = Response::build(); if let Some(responder) = self.1 { build.merge(responder.respond_to(req)?); @@ -56,7 +56,7 @@ impl<'r, R: Responder<'r>> Responder<'r> for Created<R> { /// a `Responder` is provided that implements `Hash`. The `ETag` header is set /// to a hash value of the responder. impl<'r, R: Responder<'r> + Hash> Responder<'r> for Created<R> { - fn respond_to(self, req: &Request) -> Result<Response<'r>, Status> { + fn respond_to(self, req: &Request<'_>) -> Result<Response<'r>, Status> { let mut hasher = DefaultHasher::default(); let mut build = Response::build(); if let Some(responder) = self.1 { @@ -101,7 +101,7 @@ pub struct Accepted<R>(pub Option<R>); /// Sets the status code of the response to 202 Accepted. If the responder is /// `Some`, it is used to finalize the response. impl<'r, R: Responder<'r>> Responder<'r> for Accepted<R> { - fn respond_to(self, req: &Request) -> Result<Response<'r>, Status> { + fn respond_to(self, req: &Request<'_>) -> Result<Response<'r>, Status> { let mut build = Response::build(); if let Some(responder) = self.0 { build.merge(responder.respond_to(req)?); @@ -141,7 +141,7 @@ pub struct BadRequest<R>(pub Option<R>); /// Sets the status code of the response to 400 Bad Request. If the responder is /// `Some`, it is used to finalize the response. impl<'r, R: Responder<'r>> Responder<'r> for BadRequest<R> { - fn respond_to(self, req: &Request) -> Result<Response<'r>, Status> { + fn respond_to(self, req: &Request<'_>) -> Result<Response<'r>, Status> { let mut build = Response::build(); if let Some(responder) = self.0 { build.merge(responder.respond_to(req)?); @@ -168,7 +168,7 @@ pub struct NotFound<R>(pub R); /// Sets the status code of the response to 404 Not Found. impl<'r, R: Responder<'r>> Responder<'r> for NotFound<R> { - fn respond_to(self, req: &Request) -> Result<Response<'r>, Status> { + fn respond_to(self, req: &Request<'_>) -> Result<Response<'r>, Status> { Response::build_from(self.0.respond_to(req)?) .status(Status::NotFound) .ok() @@ -192,7 +192,7 @@ pub struct Custom<R>(pub Status, pub R); /// Sets the status code of the response and then delegates the remainder of the /// response to the wrapped responder. impl<'r, R: Responder<'r>> Responder<'r> for Custom<R> { - fn respond_to(self, req: &Request) -> Result<Response<'r>, Status> { + fn respond_to(self, req: &Request<'_>) -> Result<Response<'r>, Status> { Response::build_from(self.1.respond_to(req)?) .status(self.0) .ok() diff --git a/core/lib/src/response/stream.rs b/core/lib/src/response/stream.rs @@ -1,9 +1,9 @@ use std::io::Read; use std::fmt::{self, Debug}; -use request::Request; -use response::{Response, Responder, DEFAULT_CHUNK_SIZE}; -use http::Status; +use crate::request::Request; +use crate::response::{Response, Responder, DEFAULT_CHUNK_SIZE}; +use crate::http::Status; /// Streams a response to a client from an arbitrary `Read`er type. /// @@ -35,7 +35,7 @@ impl<T: Read> Stream<T> { } impl<T: Read + Debug> Debug for Stream<T> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Stream({:?})", self.0) } } @@ -69,7 +69,7 @@ impl<T: Read> From<T> for Stream<T> { /// response is abandoned, and the response ends abruptly. An error is printed /// to the console with an indication of what went wrong. impl<'r, T: Read + 'r> Responder<'r> for Stream<T> { - fn respond_to(self, _: &Request) -> Result<Response<'r>, Status> { + fn respond_to(self, _: &Request<'_>) -> Result<Response<'r>, Status> { Response::build().chunked_body(self.0, self.1).ok() } } diff --git a/core/lib/src/rocket.rs b/core/lib/src/rocket.rs @@ -8,23 +8,23 @@ use std::mem; use yansi::Paint; use state::Container; -#[cfg(feature = "tls")] use http::tls::TlsServer; - -use {logger, handler}; -use ext::ReadExt; -use config::{self, Config, LoggedValue}; -use request::{Request, FormItems}; -use data::Data; -use response::{Body, Response}; -use router::{Router, Route}; -use catcher::{self, Catcher}; -use outcome::Outcome; -use error::{LaunchError, LaunchErrorKind}; -use fairing::{Fairing, Fairings}; - -use http::{Method, Status, Header}; -use http::hyper::{self, header}; -use http::uri::Origin; +#[cfg(feature = "tls")] use crate::http::tls::TlsServer; + +use crate::{logger, handler}; +use crate::ext::ReadExt; +use crate::config::{self, Config, LoggedValue}; +use crate::request::{Request, FormItems}; +use crate::data::Data; +use crate::response::{Body, Response}; +use crate::router::{Router, Route}; +use crate::catcher::{self, Catcher}; +use crate::outcome::Outcome; +use crate::error::{LaunchError, LaunchErrorKind}; +use crate::fairing::{Fairing, Fairings}; + +use crate::http::{Method, Status, Header}; +use crate::http::hyper::{self, header}; +use crate::http::uri::Origin; /// The main `Rocket` type: used to mount routes and catchers and launch the /// application. @@ -115,7 +115,7 @@ macro_rules! serve { impl Rocket { #[inline] - fn issue_response(&self, response: Response, hyp_res: hyper::FreshResponse) { + fn issue_response(&self, response: Response<'_>, hyp_res: hyper::FreshResponse<'_>) { match self.write_response(response, hyp_res) { Ok(_) => info_!("{}", Paint::green("Response succeeded.")), Err(e) => error_!("Failed to write response: {:?}.", e), @@ -125,8 +125,8 @@ impl Rocket { #[inline] fn write_response( &self, - mut response: Response, - mut hyp_res: hyper::FreshResponse, + mut response: Response<'_>, + mut hyp_res: hyper::FreshResponse<'_>, ) -> io::Result<()> { *hyp_res.status_mut() = hyper::StatusCode::from_u16(response.status().code); @@ -175,7 +175,7 @@ impl Rocket { /// * Rewriting the method in the request if _method form field exists. /// /// Keep this in-sync with derive_form when preprocessing form fields. - fn preprocess_request(&self, req: &mut Request, data: &Data) { + fn preprocess_request(&self, req: &mut Request<'_>, data: &Data) { // Check if this is a form and if the form contains the special _method // field which we use to reinterpret the request's method. let data_len = data.peek().len(); @@ -313,7 +313,7 @@ impl Rocket { crate fn handle_error<'r>( &self, status: Status, - req: &'r Request + req: &'r Request<'_> ) -> Response<'r> { warn_!("Responding with {} catcher.", Paint::red(&status)); @@ -338,7 +338,7 @@ impl Rocket { /// documentation for more information on defaults. /// /// This method is typically called through the - /// [`rocket::ignite()`](::ignite) alias. + /// [`rocket::ignite()`](crate::ignite) alias. /// /// # Panics /// @@ -573,7 +573,7 @@ impl Rocket { /// refers to a different `T`. /// /// Managed state can be retrieved by any request handler via the - /// [`State`](::State) request guard. In particular, if a value of type `T` + /// [`State`](crate::State) request guard. In particular, if a value of type `T` /// is managed by Rocket, adding `State<T>` to the list of arguments in a /// request handler instructs Rocket to retrieve the managed value. /// diff --git a/core/lib/src/router/collider.rs b/core/lib/src/router/collider.rs @@ -1,8 +1,8 @@ use super::Route; -use http::MediaType; -use http::route::Kind; -use request::Request; +use crate::http::MediaType; +use crate::http::route::Kind; +use crate::request::Request; impl Route { /// Determines if two routes can match against some request. That is, if two @@ -38,7 +38,7 @@ impl Route { /// request query string, though in any position. /// - If no query in route, requests with/without queries match. #[doc(hidden)] - pub fn matches(&self, req: &Request) -> bool { + pub fn matches(&self, req: &Request<'_>) -> bool { self.method == req.method() && paths_match(self, req) && queries_match(self, req) @@ -64,7 +64,7 @@ fn paths_collide(route: &Route, other: &Route) -> bool { a_segments.len() == b_segments.len() } -fn paths_match(route: &Route, request: &Request) -> bool { +fn paths_match(route: &Route, request: &Request<'_>) -> bool { let route_segments = &route.metadata.path_segments; if route_segments.len() > request.state.path_segments.len() { return false; @@ -82,7 +82,7 @@ fn paths_match(route: &Route, request: &Request) -> bool { route_segments.len() == request.state.path_segments.len() } -fn queries_match(route: &Route, request: &Request) -> bool { +fn queries_match(route: &Route, request: &Request<'_>) -> bool { if route.metadata.fully_dynamic_query { return true; } @@ -126,7 +126,7 @@ fn formats_collide(route: &Route, other: &Route) -> bool { } } -fn formats_match(route: &Route, request: &Request) -> bool { +fn formats_match(route: &Route, request: &Request<'_>) -> bool { if !route.method.supports_payload() { route.format.as_ref() .and_then(|a| request.format().map(|b| (a, b))) @@ -153,13 +153,13 @@ mod tests { use std::str::FromStr; use super::*; - use rocket::Rocket; - use config::Config; - use request::Request; - use router::{dummy_handler, route::Route}; - use http::{Method, MediaType, ContentType, Accept}; - use http::uri::Origin; - use http::Method::*; + use crate::rocket::Rocket; + use crate::config::Config; + use crate::request::Request; + use crate::router::{dummy_handler, route::Route}; + use crate::http::{Method, MediaType, ContentType, Accept}; + use crate::http::uri::Origin; + use crate::http::Method::*; type SimpleRoute = (Method, &'static str); diff --git a/core/lib/src/router/mod.rs b/core/lib/src/router/mod.rs @@ -5,15 +5,15 @@ use std::collections::hash_map::HashMap; pub use self::route::Route; -use request::Request; -use http::Method; +use crate::request::Request; +use crate::http::Method; // type Selector = (Method, usize); type Selector = Method; // A handler to use when one is needed temporarily. -crate fn dummy_handler<'r>(r: &'r ::Request, _: ::Data) -> ::handler::Outcome<'r> { - ::Outcome::from(r, ()) +crate fn dummy_handler<'r>(r: &'r crate::Request<'_>, _: crate::Data) -> crate::handler::Outcome<'r> { + crate::Outcome::from(r, ()) } #[derive(Default)] @@ -35,7 +35,7 @@ impl Router { entries.insert(i, route); } - pub fn route<'b>(&'b self, req: &Request) -> Vec<&'b Route> { + pub fn route<'b>(&'b self, req: &Request<'_>) -> Vec<&'b Route> { // Note that routes are presorted by rank on each `add`. let matches = self.routes.get(&req.method()).map_or(vec![], |routes| { routes.iter() @@ -57,9 +57,9 @@ impl Router { for b_route in right.iter_mut() { if a_route.collides_with(b_route) { let dummy_a = Route::new(Method::Get, "/", dummy_handler); - let a = ::std::mem::replace(a_route, dummy_a); + let a = std::mem::replace(a_route, dummy_a); let dummy_b = Route::new(Method::Get, "/", dummy_handler); - let b = ::std::mem::replace(b_route, dummy_b); + let b = std::mem::replace(b_route, dummy_b); collisions.push((a, b)); } } @@ -100,12 +100,12 @@ impl Router { mod test { use super::{Router, Route, dummy_handler}; - use rocket::Rocket; - use config::Config; - use http::Method; - use http::Method::*; - use http::uri::Origin; - use request::Request; + use crate::rocket::Rocket; + use crate::config::Config; + use crate::http::Method; + use crate::http::Method::*; + use crate::http::uri::Origin; + use crate::request::Request; fn router_with_routes(routes: &[&'static str]) -> Router { let mut router = Router::new(); diff --git a/core/lib/src/router/route.rs b/core/lib/src/router/route.rs @@ -3,13 +3,13 @@ use std::convert::From; use yansi::Paint; -use codegen::StaticRouteInfo; -use handler::Handler; -use http::{Method, MediaType}; -use http::route::{RouteSegment, Kind}; -use error::RouteUriError; -use http::ext::IntoOwned; -use http::uri::{Origin, Path, Query}; +use crate::codegen::StaticRouteInfo; +use crate::handler::Handler; +use crate::http::{Method, MediaType}; +use crate::http::route::{RouteSegment, Kind}; +use crate::error::RouteUriError; +use crate::http::ext::IntoOwned; +use crate::http::uri::{Origin, Path, Query}; /// A route: a method, its handler, path, rank, and format/media type. #[derive(Clone)] @@ -19,7 +19,7 @@ pub struct Route { /// The method this route matches against. pub method: Method, /// The function that should be called when the route matches. - pub handler: Box<Handler>, + pub handler: Box<dyn Handler>, /// The base mount point of this `Route`. pub base: Origin<'static>, /// The uri (in Rocket's route format) that should be matched against. This @@ -42,11 +42,11 @@ crate struct Metadata { impl Metadata { fn from(route: &Route) -> Result<Metadata, RouteUriError> { - let path_segments = <RouteSegment<Path>>::parse(&route.uri) + let path_segments = <RouteSegment<'_, Path>>::parse(&route.uri) .map(|res| res.map(|s| s.into_owned())) .collect::<Result<Vec<_>, _>>()?; - let (query_segments, dyn) = match <RouteSegment<Query>>::parse(&route.uri) { + let (query_segments, is_dyn) = match <RouteSegment<'_, Query>>::parse(&route.uri) { Some(results) => { let segments = results.map(|res| res.map(|s| s.into_owned())) .collect::<Result<Vec<_>, _>>()?; @@ -58,7 +58,7 @@ impl Metadata { None => (None, true) }; - Ok(Metadata { path_segments, query_segments, fully_dynamic_query: dyn }) + Ok(Metadata { path_segments, query_segments, fully_dynamic_query: is_dyn }) } } @@ -264,7 +264,7 @@ impl Route { path: Origin<'a> ) -> Result<(), RouteUriError> { base.clear_query(); - for segment in <RouteSegment<Path>>::parse(&base) { + for segment in <RouteSegment<'_, Path>>::parse(&base) { if segment?.kind != Kind::Static { return Err(RouteUriError::DynamicBase); } @@ -281,7 +281,7 @@ impl Route { } impl fmt::Display for Route { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} {}", Paint::green(&self.method), Paint::blue(&self.uri))?; if self.rank > 1 { @@ -302,7 +302,7 @@ impl fmt::Display for Route { } impl fmt::Debug for Route { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Route") .field("name", &self.name) .field("method", &self.method) @@ -316,8 +316,8 @@ impl fmt::Debug for Route { } #[doc(hidden)] -impl<'a> From<&'a StaticRouteInfo> for Route { - fn from(info: &'a StaticRouteInfo) -> Route { +impl From<&StaticRouteInfo> for Route { + fn from(info: &StaticRouteInfo) -> Route { // This should never panic since `info.path` is statically checked. let mut route = Route::new(info.method, info.path, info.handler); route.format = info.format.clone(); diff --git a/core/lib/tests/derive-reexports.rs b/core/lib/tests/derive-reexports.rs @@ -1,6 +1,6 @@ #![feature(proc_macro_hygiene, decl_macro)] -extern crate rocket; +use rocket; use rocket::{get, routes}; use rocket::request::{Form, FromForm, FromFormValue}; @@ -14,7 +14,7 @@ enum Thing { } impl std::fmt::Display for Thing { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { Thing::A => write!(f, "a"), Thing::B => write!(f, "b"), diff --git a/core/lib/tests/flash-lazy-removes-issue-466.rs b/core/lib/tests/flash-lazy-removes-issue-466.rs @@ -13,12 +13,12 @@ fn set() -> Flash<&'static str> { } #[get("/unused")] -fn unused(flash: Option<FlashMessage>) -> Option<()> { +fn unused(flash: Option<FlashMessage<'_, '_>>) -> Option<()> { flash.map(|_| ()) } #[get("/use")] -fn used(flash: Option<FlashMessage>) -> Option<String> { +fn used(flash: Option<FlashMessage<'_, '_>>) -> Option<String> { flash.map(|flash| flash.msg().into()) } diff --git a/core/lib/tests/mount_point.rs b/core/lib/tests/mount_point.rs @@ -1,5 +1,3 @@ -extern crate rocket; - #[test] #[should_panic] fn bad_dynamic_mount() { diff --git a/core/lib/tests/nested-fairing-attaches.rs b/core/lib/tests/nested-fairing-attaches.rs @@ -15,7 +15,7 @@ struct Counter { } #[get("/")] -fn index(counter: State<Counter>) -> String { +fn index(counter: State<'_, Counter>) -> String { let attaches = counter.attach.load(Ordering::Relaxed); let gets = counter.get.load(Ordering::Acquire); format!("{}, {}", attaches, gets) @@ -30,7 +30,7 @@ fn rocket() -> rocket::Rocket { let rocket = rocket.manage(counter) .attach(AdHoc::on_request("Inner", |req, _| { if req.method() == Method::Get { - let counter = req.guard::<State<Counter>>().unwrap(); + let counter = req.guard::<State<'_, Counter>>().unwrap(); counter.get.fetch_add(1, Ordering::Release); } })); diff --git a/core/lib/tests/segments-issues-41-86.rs b/core/lib/tests/segments-issues-41-86.rs @@ -5,27 +5,27 @@ use rocket::http::uri::Segments; #[get("/test/<path..>")] -fn test(path: Segments) -> String { +fn test(path: Segments<'_>) -> String { path.collect::<Vec<_>>().join("/") } #[get("/two/<path..>")] -fn two(path: Segments) -> String { +fn two(path: Segments<'_>) -> String { path.collect::<Vec<_>>().join("/") } #[get("/one/two/<path..>")] -fn one_two(path: Segments) -> String { +fn one_two(path: Segments<'_>) -> String { path.collect::<Vec<_>>().join("/") } #[get("/<path..>", rank = 2)] -fn none(path: Segments) -> String { +fn none(path: Segments<'_>) -> String { path.collect::<Vec<_>>().join("/") } #[get("/static/<user>/is/<path..>")] -fn dual(user: String, path: Segments) -> String { +fn dual(user: String, path: Segments<'_>) -> String { user + "/is/" + &path.collect::<Vec<_>>().join("/") }