diff --git a/contrib/codegen/Cargo.toml b/contrib/codegen/Cargo.toml index ce4b4b0226..c3907d43a7 100644 --- a/contrib/codegen/Cargo.toml +++ b/contrib/codegen/Cargo.toml @@ -10,6 +10,7 @@ readme = "../../README.md" keywords = ["rocket", "contrib", "code", "generation", "proc-macro"] license = "MIT/Apache-2.0" build = "build.rs" +edition = "2018" [features] database_attribute = [] diff --git a/contrib/codegen/src/database.rs b/contrib/codegen/src/database.rs index 2bec14bfa6..67ec3dceae 100644 --- a/contrib/codegen/src/database.rs +++ b/contrib/codegen/src/database.rs @@ -1,6 +1,6 @@ use proc_macro::TokenStream; use devise::{Spanned, Result}; -use syn::{DataStruct, Fields, Data, Type, LitStr, DeriveInput, Ident, Visibility}; +use crate::syn::{DataStruct, Fields, Data, Type, LitStr, DeriveInput, Ident, Visibility}; #[derive(Debug)] struct DatabaseInvocation { @@ -24,12 +24,12 @@ const NO_GENERIC_STRUCTS: &str = "`database` attribute cannot be applied to stru with generics"; fn parse_invocation(attr: TokenStream, input: TokenStream) -> Result { - let attr_stream2 = ::proc_macro2::TokenStream::from(attr); + let attr_stream2 = crate::proc_macro2::TokenStream::from(attr); let attr_span = attr_stream2.span(); - let string_lit = ::syn::parse2::(attr_stream2) + let string_lit = crate::syn::parse2::(attr_stream2) .map_err(|_| attr_span.error("expected string literal"))?; - let input = ::syn::parse::(input).unwrap(); + let input = crate::syn::parse::(input).unwrap(); if !input.generics.params.is_empty() { return Err(input.generics.span().error(NO_GENERIC_STRUCTS)); } diff --git a/contrib/codegen/src/lib.rs b/contrib/codegen/src/lib.rs index 49743890b2..7f61fc22aa 100644 --- a/contrib/codegen/src/lib.rs +++ b/contrib/codegen/src/lib.rs @@ -2,6 +2,8 @@ #![feature(crate_visibility_modifier)] #![recursion_limit="256"] +#![warn(rust_2018_idioms)] + //! # Rocket Contrib - Code Generation //! This crate implements the code generation portion of the Rocket Contrib //! crate. This is for officially sanctioned contributor libraries that require @@ -24,7 +26,6 @@ //! DATABASE_NAME := (string literal) //! -extern crate devise; extern crate proc_macro; #[allow(unused_imports)] @@ -43,7 +44,7 @@ use proc_macro::TokenStream; #[cfg(feature = "database_attribute")] #[proc_macro_attribute] pub fn database(attr: TokenStream, input: TokenStream) -> TokenStream { - ::database::database_attr(attr, input).unwrap_or_else(|diag| { + crate::database::database_attr(attr, input).unwrap_or_else(|diag| { diag.emit(); TokenStream::new() }) diff --git a/contrib/lib/Cargo.toml b/contrib/lib/Cargo.toml index e9b57fe752..1b13a30b52 100644 --- a/contrib/lib/Cargo.toml +++ b/contrib/lib/Cargo.toml @@ -9,6 +9,7 @@ repository = "https://github.com/SergioBenitez/Rocket" readme = "../../README.md" keywords = ["rocket", "web", "framework", "contrib", "contributed"] license = "MIT/Apache-2.0" +edition = "2018" [features] # Internal use only. diff --git a/contrib/lib/src/compression/fairing.rs b/contrib/lib/src/compression/fairing.rs index 2e10d5e25b..8de4cee78e 100644 --- a/contrib/lib/src/compression/fairing.rs +++ b/contrib/lib/src/compression/fairing.rs @@ -144,9 +144,9 @@ impl Fairing for Compression { Ok(rocket.manage(ctxt)) } - fn on_response(&self, request: &Request, response: &mut Response) { + fn on_response(&self, request: &Request<'_>, response: &mut Response<'_>) { let context = request - .guard::<::rocket::State>() + .guard::>() .expect("Compression Context registered in on_attach"); super::CompressionUtils::compress_response(request, response, &context.exclusions); diff --git a/contrib/lib/src/compression/mod.rs b/contrib/lib/src/compression/mod.rs index 9d64455676..4655407ba0 100644 --- a/contrib/lib/src/compression/mod.rs +++ b/contrib/lib/src/compression/mod.rs @@ -22,8 +22,6 @@ //! application vulnerable to attacks including BREACH. These risks should be //! evaluated in the context of your application before enabling compression. //! -#[cfg(feature="brotli_compression")] extern crate brotli; -#[cfg(feature="gzip_compression")] extern crate flate2; mod fairing; mod responder; @@ -38,15 +36,15 @@ use rocket::http::hyper::header::{ContentEncoding, Encoding}; use rocket::{Request, Response}; #[cfg(feature = "brotli_compression")] -use self::brotli::enc::backward_references::BrotliEncoderMode; +use brotli::enc::backward_references::BrotliEncoderMode; #[cfg(feature = "gzip_compression")] -use self::flate2::read::GzEncoder; +use flate2::read::GzEncoder; struct CompressionUtils; impl CompressionUtils { - fn accepts_encoding(request: &Request, encoding: &str) -> bool { + fn accepts_encoding(request: &Request<'_>, encoding: &str) -> bool { request .headers() .get("Accept-Encoding") @@ -55,7 +53,7 @@ impl CompressionUtils { .any(|accept| accept == encoding) } - fn already_encoded(response: &Response) -> bool { + fn already_encoded(response: &Response<'_>) -> bool { response.headers().get("Content-Encoding").next().is_some() } @@ -84,7 +82,7 @@ impl CompressionUtils { } } - fn compress_response(request: &Request, response: &mut Response, exclusions: &[MediaType]) { + fn compress_response(request: &Request<'_>, response: &mut Response<'_>, exclusions: &[MediaType]) { if CompressionUtils::already_encoded(response) { return; } diff --git a/contrib/lib/src/compression/responder.rs b/contrib/lib/src/compression/responder.rs index 8130b59483..05a6bfa81f 100644 --- a/contrib/lib/src/compression/responder.rs +++ b/contrib/lib/src/compression/responder.rs @@ -36,7 +36,7 @@ pub struct Compress(pub R); impl<'r, R: Responder<'r>> Responder<'r> for Compress { #[inline(always)] - fn respond_to(self, request: &Request) -> response::Result<'r> { + fn respond_to(self, request: &Request<'_>) -> response::Result<'r> { let mut response = Response::build() .merge(self.0.respond_to(request)?) .finalize(); diff --git a/contrib/lib/src/databases.rs b/contrib/lib/src/databases.rs index b98f579321..a35cd7bcaf 100644 --- a/contrib/lib/src/databases.rs +++ b/contrib/lib/src/databases.rs @@ -86,7 +86,7 @@ //! # struct LogsDbConn(diesel::SqliteConnection); //! # //! # type Logs = (); -//! # type Result = ::std::result::Result; +//! # type Result = std::result::Result; //! # //! #[get("/logs/")] //! fn get_logs(conn: LogsDbConn, id: usize) -> Result { @@ -229,7 +229,7 @@ //! allowing the type to be used as a request guard. This implementation //! retrieves a connection from the database pool or fails with a //! `Status::ServiceUnavailable` if no connections are available. The macro also -//! generates an implementation of the [`Deref`](::std::ops::Deref) trait with +//! generates an implementation of the [`Deref`](std::ops::Deref) trait with //! the internal `Poolable` type as the target. //! //! The macro will also generate two inherent methods on the decorated type: @@ -395,6 +395,7 @@ //! [request guards]: rocket::request::FromRequest //! [`Poolable`]: databases::Poolable +#![allow(unused_extern_crates)] pub extern crate r2d2; #[cfg(any(feature = "diesel_sqlite_pool", @@ -491,7 +492,7 @@ pub enum ConfigError { /// configuration. MissingKey, /// The configuration associated with the key isn't a - /// [`Table`](::rocket::config::Table). + /// [`Table`](rocket::config::Table). MalformedConfiguration, /// The required `url` key is missing. MissingUrl, @@ -594,7 +595,7 @@ pub fn database_config<'a>( } impl<'a> Display for ConfigError { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { ConfigError::MissingTable => { write!(f, "A table named `databases` was not found for this configuration") @@ -659,7 +660,7 @@ impl<'a> Display for ConfigError { /// # use std::fmt; /// # use rocket_contrib::databases::r2d2; /// # #[derive(Debug)] pub struct Error; -/// # impl ::std::error::Error for Error { } +/// # impl std::error::Error for Error { } /// # impl fmt::Display for Error { /// # fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Ok(()) } /// # } @@ -667,7 +668,7 @@ impl<'a> Display for ConfigError { /// # pub struct Connection; /// # pub struct ConnectionManager; /// # -/// # type Result = ::std::result::Result; +/// # type Result = std::result::Result; /// # /// # impl ConnectionManager { /// # pub fn new(url: &str) -> Result { Err(Error) } @@ -717,7 +718,7 @@ pub trait Poolable: Send + Sized + 'static { /// Creates an `r2d2` connection pool for `Manager::Connection`, returning /// the pool on success. - fn pool(config: DatabaseConfig) -> Result, Self::Error>; + fn pool(config: DatabaseConfig<'_>) -> Result, Self::Error>; } #[cfg(feature = "diesel_sqlite_pool")] @@ -725,7 +726,7 @@ impl Poolable for diesel::SqliteConnection { type Manager = diesel::r2d2::ConnectionManager; type Error = r2d2::Error; - fn pool(config: DatabaseConfig) -> Result, Self::Error> { + fn pool(config: DatabaseConfig<'_>) -> Result, Self::Error> { let manager = diesel::r2d2::ConnectionManager::new(config.url); r2d2::Pool::builder().max_size(config.pool_size).build(manager) } @@ -736,7 +737,7 @@ impl Poolable for diesel::PgConnection { type Manager = diesel::r2d2::ConnectionManager; type Error = r2d2::Error; - fn pool(config: DatabaseConfig) -> Result, Self::Error> { + fn pool(config: DatabaseConfig<'_>) -> Result, Self::Error> { let manager = diesel::r2d2::ConnectionManager::new(config.url); r2d2::Pool::builder().max_size(config.pool_size).build(manager) } @@ -747,7 +748,7 @@ impl Poolable for diesel::MysqlConnection { type Manager = diesel::r2d2::ConnectionManager; type Error = r2d2::Error; - fn pool(config: DatabaseConfig) -> Result, Self::Error> { + fn pool(config: DatabaseConfig<'_>) -> Result, Self::Error> { let manager = diesel::r2d2::ConnectionManager::new(config.url); r2d2::Pool::builder().max_size(config.pool_size).build(manager) } @@ -759,7 +760,7 @@ impl Poolable for postgres::Connection { type Manager = r2d2_postgres::PostgresConnectionManager; type Error = DbError; - fn pool(config: DatabaseConfig) -> Result, Self::Error> { + fn pool(config: DatabaseConfig<'_>) -> Result, Self::Error> { let manager = r2d2_postgres::PostgresConnectionManager::new(config.url, r2d2_postgres::TlsMode::None) .map_err(DbError::Custom)?; @@ -773,7 +774,7 @@ impl Poolable for mysql::Conn { type Manager = r2d2_mysql::MysqlConnectionManager; type Error = r2d2::Error; - fn pool(config: DatabaseConfig) -> Result, Self::Error> { + fn pool(config: DatabaseConfig<'_>) -> Result, Self::Error> { let opts = mysql::OptsBuilder::from_opts(config.url); let manager = r2d2_mysql::MysqlConnectionManager::new(opts); r2d2::Pool::builder().max_size(config.pool_size).build(manager) @@ -785,7 +786,7 @@ impl Poolable for rusqlite::Connection { type Manager = r2d2_sqlite::SqliteConnectionManager; type Error = r2d2::Error; - fn pool(config: DatabaseConfig) -> Result, Self::Error> { + fn pool(config: DatabaseConfig<'_>) -> Result, Self::Error> { let manager = r2d2_sqlite::SqliteConnectionManager::file(config.url); r2d2::Pool::builder().max_size(config.pool_size).build(manager) @@ -797,7 +798,7 @@ impl Poolable for rusted_cypher::GraphClient { type Manager = r2d2_cypher::CypherConnectionManager; type Error = r2d2::Error; - fn pool(config: DatabaseConfig) -> Result, Self::Error> { + fn pool(config: DatabaseConfig<'_>) -> Result, Self::Error> { let manager = r2d2_cypher::CypherConnectionManager { url: config.url.to_string() }; r2d2::Pool::builder().max_size(config.pool_size).build(manager) } @@ -808,7 +809,7 @@ impl Poolable for redis::Connection { type Manager = r2d2_redis::RedisConnectionManager; type Error = DbError; - fn pool(config: DatabaseConfig) -> Result, Self::Error> { + fn pool(config: DatabaseConfig<'_>) -> Result, Self::Error> { let manager = r2d2_redis::RedisConnectionManager::new(config.url).map_err(DbError::Custom)?; r2d2::Pool::builder().max_size(config.pool_size).build(manager) .map_err(DbError::PoolError) @@ -820,7 +821,7 @@ impl Poolable for mongodb::db::Database { type Manager = r2d2_mongodb::MongodbConnectionManager; type Error = DbError; - fn pool(config: DatabaseConfig) -> Result, Self::Error> { + fn pool(config: DatabaseConfig<'_>) -> Result, Self::Error> { let manager = r2d2_mongodb::MongodbConnectionManager::new_with_uri(config.url).map_err(DbError::Custom)?; r2d2::Pool::builder().max_size(config.pool_size).build(manager).map_err(DbError::PoolError) } @@ -831,7 +832,7 @@ impl Poolable for memcache::Client { type Manager = r2d2_memcache::MemcacheConnectionManager; type Error = DbError; - fn pool(config: DatabaseConfig) -> Result, Self::Error> { + fn pool(config: DatabaseConfig<'_>) -> Result, Self::Error> { let manager = r2d2_memcache::MemcacheConnectionManager::new(config.url); r2d2::Pool::builder().max_size(config.pool_size).build(manager).map_err(DbError::PoolError) } diff --git a/contrib/lib/src/helmet/helmet.rs b/contrib/lib/src/helmet/helmet.rs index 8f68d0b84c..c18251d87f 100644 --- a/contrib/lib/src/helmet/helmet.rs +++ b/contrib/lib/src/helmet/helmet.rs @@ -5,7 +5,7 @@ use rocket::http::uncased::UncasedStr; use rocket::fairing::{Fairing, Info, Kind}; use rocket::{Request, Response, Rocket}; -use helmet::*; +use crate::helmet::*; /// A [`Fairing`](../../rocket/fairing/trait.Fairing.html) that adds HTTP /// headers to outgoing responses that control security features on the browser. @@ -167,7 +167,7 @@ impl SpaceHelmet { /// Sets all of the headers in `self.policies` in `response` as long as the /// header is not already in the response. - fn apply(&self, response: &mut Response) { + fn apply(&self, response: &mut Response<'_>) { for policy in self.policies.values() { let name = policy.name(); if response.headers().contains(name.as_str()) { @@ -196,7 +196,7 @@ impl Fairing for SpaceHelmet { } } - fn on_response(&self, _request: &Request, response: &mut Response) { + fn on_response(&self, _request: &Request<'_>, response: &mut Response<'_>) { self.apply(response); } diff --git a/contrib/lib/src/helmet/mod.rs b/contrib/lib/src/helmet/mod.rs index 7aa34b210e..4b4a32afaf 100644 --- a/contrib/lib/src/helmet/mod.rs +++ b/contrib/lib/src/helmet/mod.rs @@ -103,8 +103,6 @@ //! //! [OWASP]: https://www.owasp.org/index.php/OWASP_Secure_Headers_Project#tab=Headers -extern crate time; - mod helmet; mod policy; diff --git a/contrib/lib/src/helmet/policy.rs b/contrib/lib/src/helmet/policy.rs index bb40532e96..699e6dc9d1 100644 --- a/contrib/lib/src/helmet/policy.rs +++ b/contrib/lib/src/helmet/policy.rs @@ -4,16 +4,16 @@ use std::borrow::Cow; use rocket::http::{Header, uri::Uri, uncased::UncasedStr}; -use helmet::time::Duration; +use time::Duration; /// Trait implemented by security and privacy policy headers. /// /// Types that implement this trait can be [`enable()`]d and [`disable()`]d on /// instances of [`SpaceHelmet`]. /// -/// [`SpaceHelmet`]: ::helmet::SpaceHelmet -/// [`enable()`]: ::helmet::SpaceHelmet::enable() -/// [`disable()`]: ::helmet::SpaceHelmet::disable() +/// [`SpaceHelmet`]: crate::helmet::SpaceHelmet +/// [`enable()`]: crate::helmet::SpaceHelmet::enable() +/// [`disable()`]: crate::helmet::SpaceHelmet::disable() pub trait Policy: Default + Send + Sync + 'static { /// The actual name of the HTTP header. /// @@ -151,8 +151,8 @@ impl Default for Referrer { } } -impl<'h, 'a> Into> for &'a Referrer { - fn into(self) -> Header<'h> { +impl Into> for &Referrer { + fn into(self) -> Header<'static> { let policy_string = match self { Referrer::NoReferrer => "no-referrer", Referrer::NoReferrerWhenDowngrade => "no-referrer-when-downgrade", @@ -209,7 +209,7 @@ impl Default for ExpectCt { } } -impl<'a> Into> for &'a ExpectCt { +impl Into> for &ExpectCt { fn into(self) -> Header<'static> { let policy_string = match self { ExpectCt::Enforce(age) => format!("max-age={}, enforce", age.num_seconds()), @@ -243,8 +243,8 @@ impl Default for NoSniff { } } -impl<'h, 'a> Into> for &'a NoSniff { - fn into(self) -> Header<'h> { +impl Into> for &NoSniff { + fn into(self) -> Header<'static> { Header::new(NoSniff::NAME, "nosniff") } } @@ -295,7 +295,7 @@ impl Default for Hsts { } } -impl<'a> Into> for &'a Hsts { +impl Into> for &Hsts { fn into(self) -> Header<'static> { let policy_string = match self { Hsts::Enable(age) => format!("max-age={}", age.num_seconds()), @@ -345,7 +345,7 @@ impl Default for Frame { } } -impl<'a> Into> for &'a Frame { +impl Into> for &Frame { fn into(self) -> Header<'static> { let policy_string: Cow<'static, str> = match self { Frame::Deny => "DENY".into(), @@ -387,7 +387,7 @@ impl Default for XssFilter { } } -impl<'a> Into> for &'a XssFilter { +impl Into> for &XssFilter { fn into(self) -> Header<'static> { let policy_string: Cow<'static, str> = match self { XssFilter::Disable => "0".into(), diff --git a/contrib/lib/src/json.rs b/contrib/lib/src/json.rs index 0605e48fd1..aa114f849f 100644 --- a/contrib/lib/src/json.rs +++ b/contrib/lib/src/json.rs @@ -14,9 +14,6 @@ //! features = ["json"] //! ``` -extern crate serde; -extern crate serde_json; - use std::ops::{Deref, DerefMut}; use std::io::{self, Read}; use std::iter::FromIterator; @@ -27,11 +24,11 @@ use rocket::data::{Outcome, Transform, Transform::*, Transformed, Data, FromData use rocket::response::{self, Responder, content}; use rocket::http::Status; -use self::serde::{Serialize, Serializer}; -use self::serde::de::{Deserialize, Deserializer}; +use serde::{Serialize, Serializer}; +use serde::de::{Deserialize, Deserializer}; #[doc(hidden)] -pub use self::serde_json::{json_internal, json_internal_vec}; +pub use serde_json::{json_internal, json_internal_vec}; /// The JSON type: implements [`FromData`] and [`Responder`], allowing you to /// easily consume and respond with JSON. @@ -136,7 +133,7 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for Json { type Owned = String; type Borrowed = str; - fn transform(r: &Request, d: Data) -> Transform> { + fn transform(r: &Request<'_>, d: Data) -> Transform> { let size_limit = r.limits().get("json").unwrap_or(LIMIT); let mut s = String::with_capacity(512); match d.open().take(size_limit).read_to_string(&mut s) { @@ -145,7 +142,7 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for Json { } } - fn from_data(_: &Request, o: Transformed<'a, Self>) -> Outcome { + fn from_data(_: &Request<'_>, o: Transformed<'a, Self>) -> Outcome { let string = o.borrowed()?; match serde_json::from_str(&string) { Ok(v) => Success(Json(v)), @@ -165,7 +162,7 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for Json { /// JSON and a fixed-size body with the serialized value. If serialization /// fails, an `Err` of `Status::InternalServerError` is returned. impl<'a, T: Serialize> Responder<'a> for Json { - fn respond_to(self, req: &Request) -> response::Result<'a> { + fn respond_to(self, req: &Request<'_>) -> response::Result<'a> { serde_json::to_string(&self.0).map(|string| { content::Json(string).respond_to(req).unwrap() }).map_err(|e| { @@ -288,7 +285,7 @@ impl FromIterator for JsonValue where serde_json::Value: FromIterator { /// and a fixed-size body with the serialized value. impl<'a> Responder<'a> for JsonValue { #[inline] - fn respond_to(self, req: &Request) -> response::Result<'a> { + fn respond_to(self, req: &Request<'_>) -> response::Result<'a> { content::Json(self.0.to_string()).respond_to(req) } } diff --git a/contrib/lib/src/lib.rs b/contrib/lib/src/lib.rs index 7b877cd13f..59c8f0a742 100644 --- a/contrib/lib/src/lib.rs +++ b/contrib/lib/src/lib.rs @@ -6,6 +6,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)] + //! This crate contains officially sanctioned contributor libraries that provide //! functionality commonly used by Rocket applications. //! @@ -54,5 +56,4 @@ #[cfg(feature = "helmet")] pub mod helmet; #[cfg(any(feature="brotli_compression", feature="gzip_compression"))] pub mod compression; -#[cfg(feature="databases")] extern crate rocket_contrib_codegen; #[cfg(feature="databases")] #[doc(hidden)] pub use rocket_contrib_codegen::*; diff --git a/contrib/lib/src/msgpack.rs b/contrib/lib/src/msgpack.rs index 8be0fe9f0e..77e2842ed6 100644 --- a/contrib/lib/src/msgpack.rs +++ b/contrib/lib/src/msgpack.rs @@ -1,6 +1,6 @@ //! Automatic MessagePack (de)serialization support. //! -//! See the [`MsgPack`](msgpack::MessagePack) type for further details. +//! See the [`MsgPack`](crate::msgpack::MsgPack) type for further details. //! //! # Enabling //! @@ -13,8 +13,6 @@ //! default-features = false //! features = ["msgpack"] //! ``` -extern crate serde; -extern crate rmp_serde; use std::io::Read; use std::ops::{Deref, DerefMut}; @@ -25,10 +23,10 @@ use rocket::data::{Outcome, Transform, Transform::*, Transformed, Data, FromData use rocket::response::{self, Responder, content}; use rocket::http::Status; -use self::serde::Serialize; -use self::serde::de::Deserialize; +use serde::Serialize; +use serde::de::Deserialize; -pub use self::rmp_serde::decode::Error; +pub use rmp_serde::decode::Error; /// The `MsgPack` type: implements [`FromData`] and [`Responder`], allowing you /// to easily consume and respond with MessagePack data. @@ -121,7 +119,7 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for MsgPack { type Owned = Vec; type Borrowed = [u8]; - fn transform(r: &Request, d: Data) -> Transform> { + fn transform(r: &Request<'_>, d: Data) -> Transform> { let mut buf = Vec::new(); let size_limit = r.limits().get("msgpack").unwrap_or(LIMIT); match d.open().take(size_limit).read_to_end(&mut buf) { @@ -130,7 +128,7 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for MsgPack { } } - fn from_data(_: &Request, o: Transformed<'a, Self>) -> Outcome { + fn from_data(_: &Request<'_>, o: Transformed<'a, Self>) -> Outcome { use self::Error::*; let buf = o.borrowed()?; @@ -153,7 +151,7 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for MsgPack { /// Content-Type `MsgPack` and a fixed-size body with the serialization. If /// serialization fails, an `Err` of `Status::InternalServerError` is returned. impl Responder<'static> for MsgPack { - fn respond_to(self, req: &Request) -> response::Result<'static> { + fn respond_to(self, req: &Request<'_>) -> response::Result<'static> { rmp_serde::to_vec(&self.0).map_err(|e| { error_!("MsgPack failed to serialize: {:?}", e); Status::InternalServerError diff --git a/contrib/lib/src/serve.rs b/contrib/lib/src/serve.rs index c33ab2aa7f..c7765b3b83 100644 --- a/contrib/lib/src/serve.rs +++ b/contrib/lib/src/serve.rs @@ -86,7 +86,7 @@ impl Default for Options { } } -impl ::std::ops::BitOr for Options { +impl std::ops::BitOr for Options { type Output = Self; #[inline(always)] @@ -272,8 +272,8 @@ impl Into> for StaticFiles { } impl Handler for StaticFiles { - fn handle<'r>(&self, req: &'r Request, _: Data) -> Outcome<'r> { - fn handle_index<'r>(opt: Options, r: &'r Request, path: &Path) -> Outcome<'r> { + fn handle<'r>(&self, req: &'r Request<'_>, _: Data) -> Outcome<'r> { + fn handle_index<'r>(opt: Options, r: &'r Request<'_>, path: &Path) -> Outcome<'r> { if !opt.contains(Options::Index) { return Outcome::failure(Status::NotFound); } @@ -292,7 +292,7 @@ impl Handler for StaticFiles { // Otherwise, we're handling segments. Get the segments as a `PathBuf`, // only allowing dotfiles if the user allowed it. let allow_dotfiles = self.options.contains(Options::DotFiles); - let path = req.get_segments::(0) + let path = req.get_segments::>(0) .and_then(|res| res.ok()) .and_then(|segments| segments.into_path_buf(allow_dotfiles).ok()) .map(|path| self.root.join(path)) diff --git a/contrib/lib/src/templates/context.rs b/contrib/lib/src/templates/context.rs index 89f824d60f..ed73ea26b6 100644 --- a/contrib/lib/src/templates/context.rs +++ b/contrib/lib/src/templates/context.rs @@ -1,7 +1,7 @@ use std::path::{Path, PathBuf}; use std::collections::HashMap; -use templates::{glob, Engines, TemplateInfo}; +use crate::templates::{Engines, TemplateInfo}; use rocket::http::ContentType; @@ -25,7 +25,7 @@ impl Context { glob_path.set_extension(ext); let glob_path = glob_path.to_str().expect("valid glob path string"); - for path in glob(glob_path).unwrap().filter_map(Result::ok) { + for path in glob::glob(glob_path).unwrap().filter_map(Result::ok) { let (name, data_type_str) = split_path(&root, &path); if let Some(info) = templates.get(&*name) { warn_!("Template name '{}' does not have a unique path.", name); diff --git a/contrib/lib/src/templates/engine.rs b/contrib/lib/src/templates/engine.rs index a63c19798d..c40abd51ed 100644 --- a/contrib/lib/src/templates/engine.rs +++ b/contrib/lib/src/templates/engine.rs @@ -1,9 +1,11 @@ use std::collections::HashMap; -use templates::{TemplateInfo, serde::Serialize}; +use serde::Serialize; -#[cfg(feature = "tera_templates")] use templates::tera::Tera; -#[cfg(feature = "handlebars_templates")] use templates::handlebars::Handlebars; +use crate::templates::TemplateInfo; + +#[cfg(feature = "tera_templates")] use crate::templates::tera::Tera; +#[cfg(feature = "handlebars_templates")] use crate::templates::handlebars::Handlebars; crate trait Engine: Send + Sync + 'static { const EXT: &'static str; @@ -40,8 +42,8 @@ crate trait Engine: Send + Sync + 'static { /// # } /// ``` /// -/// [`tera::Value`]: ::templates::tera::Value -/// [`tera::Result`]: ::templates::tera::Result +/// [`tera::Value`]: crate::templates::tera::Value +/// [`tera::Result`]: crate::templates::tera::Result pub struct Engines { /// A `Tera` templating engine. This field is only available when the /// `tera_templates` feature is enabled. When calling methods on the `Tera` diff --git a/contrib/lib/src/templates/fairing.rs b/contrib/lib/src/templates/fairing.rs index 71e138f191..c9383b0be3 100644 --- a/contrib/lib/src/templates/fairing.rs +++ b/contrib/lib/src/templates/fairing.rs @@ -1,4 +1,4 @@ -use templates::{DEFAULT_TEMPLATE_DIR, Context, Engines}; +use crate::templates::{DEFAULT_TEMPLATE_DIR, Context, Engines}; use rocket::Rocket; use rocket::config::ConfigError; @@ -9,7 +9,7 @@ crate use self::context::ContextManager; #[cfg(not(debug_assertions))] mod context { use std::ops::Deref; - use templates::Context; + use crate::templates::Context; /// Wraps a Context. With `cfg(debug_assertions)` active, this structure /// additionally provides a method to reload the context at runtime. @@ -32,15 +32,13 @@ mod context { #[cfg(debug_assertions)] mod context { - extern crate notify; - use std::ops::{Deref, DerefMut}; use std::sync::{RwLock, Mutex}; use std::sync::mpsc::{channel, Receiver}; - use templates::{Context, Engines}; + use notify::{raw_watcher, RawEvent, RecommendedWatcher, RecursiveMode, Watcher}; - use self::notify::{raw_watcher, RawEvent, RecommendedWatcher, RecursiveMode, Watcher}; + use crate::templates::{Context, Engines}; /// Wraps a Context. With `cfg(debug_assertions)` active, this structure /// additionally provides a method to reload the context at runtime. @@ -75,7 +73,7 @@ mod context { } } - crate fn context<'a>(&'a self) -> impl Deref + 'a { + crate fn context(&self) -> impl Deref + '_ { self.context.read().unwrap() } @@ -83,7 +81,7 @@ mod context { self.watcher.is_some() } - fn context_mut<'a>(&'a self) -> impl DerefMut + 'a { + fn context_mut(&self) -> impl DerefMut + '_ { self.context.write().unwrap() } @@ -123,7 +121,7 @@ pub struct TemplateFairing { /// The user-provided customization callback, allowing the use of /// functionality specific to individual template engines. In debug mode, /// this callback might be run multiple times as templates are reloaded. - crate custom_callback: Box, + crate custom_callback: Box, } impl Fairing for TemplateFairing { @@ -165,8 +163,8 @@ impl Fairing for TemplateFairing { } #[cfg(debug_assertions)] - fn on_request(&self, req: &mut ::rocket::Request, _data: &::rocket::Data) { - let cm = req.guard::<::rocket::State>() + fn on_request(&self, req: &mut rocket::Request<'_>, _data: &rocket::Data) { + let cm = req.guard::>() .expect("Template ContextManager registered in on_attach"); cm.reload_if_needed(&*self.custom_callback); diff --git a/contrib/lib/src/templates/handlebars_templates.rs b/contrib/lib/src/templates/handlebars_templates.rs index 9310011145..8220639f81 100644 --- a/contrib/lib/src/templates/handlebars_templates.rs +++ b/contrib/lib/src/templates/handlebars_templates.rs @@ -1,7 +1,8 @@ -use templates::serde::Serialize; -use templates::{Engine, TemplateInfo}; +use serde::Serialize; -pub use templates::handlebars::Handlebars; +use crate::templates::{Engine, TemplateInfo}; + +pub use crate::templates::handlebars::Handlebars; impl Engine for Handlebars { const EXT: &'static str = "hbs"; diff --git a/contrib/lib/src/templates/metadata.rs b/contrib/lib/src/templates/metadata.rs index 7e8333850f..26cf2feac1 100644 --- a/contrib/lib/src/templates/metadata.rs +++ b/contrib/lib/src/templates/metadata.rs @@ -2,7 +2,7 @@ use rocket::{Request, State, Outcome}; use rocket::http::Status; use rocket::request::{self, FromRequest}; -use templates::ContextManager; +use crate::templates::ContextManager; /// Request guard for dynamiclly querying template metadata. /// @@ -39,7 +39,7 @@ use templates::ContextManager; /// ``` pub struct Metadata<'a>(&'a ContextManager); -impl<'a> Metadata<'a> { +impl Metadata<'_> { /// Returns `true` if the template with the given `name` is currently /// loaded. Otherwise, returns `false`. /// @@ -87,11 +87,11 @@ impl<'a> Metadata<'a> { /// Retrieves the template metadata. If a template fairing hasn't been attached, /// an error is printed and an empty `Err` with status `InternalServerError` /// (`500`) is returned. -impl<'a, 'r> FromRequest<'a, 'r> for Metadata<'a> { +impl<'a> FromRequest<'a, '_> for Metadata<'a> { type Error = (); - fn from_request(request: &'a Request) -> request::Outcome { - request.guard::>() + fn from_request(request: &'a Request<'_>) -> request::Outcome { + request.guard::>() .succeeded() .and_then(|cm| Some(Outcome::Success(Metadata(cm.inner())))) .unwrap_or_else(|| { diff --git a/contrib/lib/src/templates/mod.rs b/contrib/lib/src/templates/mod.rs index 14c10f8787..c3554a207f 100644 --- a/contrib/lib/src/templates/mod.rs +++ b/contrib/lib/src/templates/mod.rs @@ -111,10 +111,6 @@ //! [`Template::custom()`]: templates::Template::custom() //! [`Template::render()`]: templates::Template::render() -extern crate serde; -extern crate serde_json; -extern crate glob; - #[cfg(feature = "tera_templates")] pub extern crate tera; #[cfg(feature = "tera_templates")] mod tera_templates; @@ -133,9 +129,9 @@ crate use self::fairing::ContextManager; use self::engine::Engine; use self::fairing::TemplateFairing; -use self::serde::Serialize; -use self::serde_json::{Value, to_value}; -use self::glob::glob; + +use serde::Serialize; +use serde_json::{Value, to_value}; use std::borrow::Cow; use std::path::PathBuf; @@ -387,8 +383,8 @@ impl Template { /// extension and a fixed-size body containing the rendered template. If /// rendering fails, an `Err` of `Status::InternalServerError` is returned. impl Responder<'static> for Template { - fn respond_to(self, req: &Request) -> response::Result<'static> { - let ctxt = req.guard::>().succeeded().ok_or_else(|| { + fn respond_to(self, req: &Request<'_>) -> response::Result<'static> { + let ctxt = req.guard::>().succeeded().ok_or_else(|| { error_!("Uninitialized template context: missing fairing."); info_!("To use templates, you must attach `Template::fairing()`."); info_!("See the `Template` documentation for more information."); diff --git a/contrib/lib/src/templates/tera_templates.rs b/contrib/lib/src/templates/tera_templates.rs index dc07c24b07..9dcccfcff9 100644 --- a/contrib/lib/src/templates/tera_templates.rs +++ b/contrib/lib/src/templates/tera_templates.rs @@ -1,7 +1,8 @@ -use templates::serde::Serialize; -use templates::{Engine, TemplateInfo}; +use serde::Serialize; -pub use templates::tera::Tera; +use crate::templates::{Engine, TemplateInfo}; + +pub use crate::templates::tera::Tera; impl Engine for Tera { const EXT: &'static str = "tera"; diff --git a/contrib/lib/src/uuid.rs b/contrib/lib/src/uuid.rs index 8265defcb7..24fd756df3 100644 --- a/contrib/lib/src/uuid.rs +++ b/contrib/lib/src/uuid.rs @@ -95,7 +95,7 @@ impl Uuid { impl fmt::Display for Uuid { #[inline(always)] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } @@ -127,7 +127,7 @@ impl FromStr for Uuid { #[inline] fn from_str(s: &str) -> Result { - Ok(Uuid(try!(s.parse()))) + s.parse().map(Uuid) } } diff --git a/contrib/lib/tests/compress_responder.rs b/contrib/lib/tests/compress_responder.rs index 9ab5ec9cbd..ab3c79f03c 100644 --- a/contrib/lib/tests/compress_responder.rs +++ b/contrib/lib/tests/compress_responder.rs @@ -4,14 +4,8 @@ #[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))] extern crate rocket; -#[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))] -extern crate rocket_contrib; - #[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))] mod compress_responder_tests { - extern crate brotli; - extern crate flate2; - use rocket::http::hyper::header::{ContentEncoding, Encoding}; use rocket::http::Status; use rocket::http::{ContentType, Header}; @@ -22,7 +16,7 @@ mod compress_responder_tests { use std::io::Cursor; use std::io::Read; - use self::flate2::read::{GzDecoder, GzEncoder}; + use flate2::read::{GzDecoder, GzEncoder}; const HELLO: &str = r"This is a message to hello with more than 100 bytes \ in order to have to read more than one buffer when gzipping. こんにちは!"; diff --git a/contrib/lib/tests/compression_fairing.rs b/contrib/lib/tests/compression_fairing.rs index 68284a8650..9f3b13c331 100644 --- a/contrib/lib/tests/compression_fairing.rs +++ b/contrib/lib/tests/compression_fairing.rs @@ -4,14 +4,8 @@ #[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))] extern crate rocket; -#[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))] -extern crate rocket_contrib; - #[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))] mod compression_fairing_tests { - extern crate brotli; - extern crate flate2; - use rocket::config::{Config, Environment}; use rocket::http::hyper::header::{ContentEncoding, Encoding}; use rocket::http::Status; @@ -23,7 +17,7 @@ mod compression_fairing_tests { use std::io::Cursor; use std::io::Read; - use self::flate2::read::{GzDecoder, GzEncoder}; + use flate2::read::{GzDecoder, GzEncoder}; const HELLO: &str = r"This is a message to hello with more than 100 bytes \ in order to have to read more than one buffer when gzipping. こんにちは!"; diff --git a/contrib/lib/tests/databases.rs b/contrib/lib/tests/databases.rs index ec7a320e8a..ca51b8d632 100644 --- a/contrib/lib/tests/databases.rs +++ b/contrib/lib/tests/databases.rs @@ -1,6 +1,3 @@ -extern crate rocket; -extern crate rocket_contrib; - #[cfg(all(feature = "diesel_sqlite_pool", feature = "diesel_postgres_pool"))] mod databases_tests { use rocket_contrib::databases::{database, diesel}; @@ -20,7 +17,7 @@ mod rusqlite_integration_test { use rocket_contrib::databases::rusqlite; use rocket_contrib::database; - use self::rusqlite::types::ToSql; + use rusqlite::types::ToSql; #[database("test_db")] struct SqliteDb(pub rusqlite::Connection); diff --git a/contrib/lib/tests/helmet.rs b/contrib/lib/tests/helmet.rs index c45a21dcc8..d6dcbb5f17 100644 --- a/contrib/lib/tests/helmet.rs +++ b/contrib/lib/tests/helmet.rs @@ -6,15 +6,11 @@ extern crate rocket; #[cfg(feature = "helmet")] mod helmet_tests { - extern crate time; - extern crate rocket_contrib; - - use rocket; use rocket::http::{Status, uri::Uri}; use rocket::local::{Client, LocalResponse}; - use self::rocket_contrib::helmet::*; - use self::time::Duration; + use rocket_contrib::helmet::*; + use time::Duration; #[get("/")] fn hello() { } @@ -47,7 +43,7 @@ mod helmet_tests { #[test] fn default_headers_test() { - dispatch!(SpaceHelmet::default(), |response: LocalResponse| { + dispatch!(SpaceHelmet::default(), |response: LocalResponse<'_>| { assert_header!(response, "X-XSS-Protection", "1"); assert_header!(response, "X-Frame-Options", "SAMEORIGIN"); assert_header!(response, "X-Content-Type-Options", "nosniff"); @@ -57,14 +53,14 @@ mod helmet_tests { #[test] fn disable_headers_test() { let helmet = SpaceHelmet::default().disable::(); - dispatch!(helmet, |response: LocalResponse| { + dispatch!(helmet, |response: LocalResponse<'_>| { assert_header!(response, "X-Frame-Options", "SAMEORIGIN"); assert_header!(response, "X-Content-Type-Options", "nosniff"); assert_no_header!(response, "X-XSS-Protection"); }); let helmet = SpaceHelmet::default().disable::(); - dispatch!(helmet, |response: LocalResponse| { + dispatch!(helmet, |response: LocalResponse<'_>| { assert_header!(response, "X-XSS-Protection", "1"); assert_header!(response, "X-Content-Type-Options", "nosniff"); assert_no_header!(response, "X-Frame-Options"); @@ -75,13 +71,13 @@ mod helmet_tests { .disable::() .disable::(); - dispatch!(helmet, |response: LocalResponse| { + dispatch!(helmet, |response: LocalResponse<'_>| { assert_no_header!(response, "X-Frame-Options"); assert_no_header!(response, "X-XSS-Protection"); assert_no_header!(response, "X-Content-Type-Options"); }); - dispatch!(SpaceHelmet::new(), |response: LocalResponse| { + dispatch!(SpaceHelmet::new(), |response: LocalResponse<'_>| { assert_no_header!(response, "X-Frame-Options"); assert_no_header!(response, "X-XSS-Protection"); assert_no_header!(response, "X-Content-Type-Options"); @@ -95,7 +91,7 @@ mod helmet_tests { .enable(ExpectCt::default()) .enable(Referrer::default()); - dispatch!(helmet, |response: LocalResponse| { + dispatch!(helmet, |response: LocalResponse<'_>| { assert_header!( response, "Strict-Transport-Security", @@ -123,7 +119,7 @@ mod helmet_tests { .enable(XssFilter::EnableReport(report_uri)) .enable(ExpectCt::ReportAndEnforce(Duration::seconds(30), enforce_uri)); - dispatch!(helmet, |response: LocalResponse| { + dispatch!(helmet, |response: LocalResponse<'_>| { assert_header!(response, "X-Frame-Options", "ALLOW-FROM https://www.google.com"); diff --git a/contrib/lib/tests/static_files.rs b/contrib/lib/tests/static_files.rs index ebc93ecef9..b5318d195b 100644 --- a/contrib/lib/tests/static_files.rs +++ b/contrib/lib/tests/static_files.rs @@ -1,8 +1,5 @@ #![feature(proc_macro_hygiene, decl_macro)] -extern crate rocket; -extern crate rocket_contrib; - #[cfg(feature = "serve")] mod static_tests { use std::{io::Read, fs::File}; diff --git a/contrib/lib/tests/templates.rs b/contrib/lib/tests/templates.rs index 2c267715c3..acdc787b05 100644 --- a/contrib/lib/tests/templates.rs +++ b/contrib/lib/tests/templates.rs @@ -3,9 +3,6 @@ #[cfg(feature = "templates")] #[macro_use] extern crate rocket; -#[cfg(feature = "templates")] -extern crate rocket_contrib; - #[cfg(feature = "templates")] mod templates_tests { use std::path::{Path, PathBuf}; @@ -15,7 +12,7 @@ mod templates_tests { use rocket_contrib::templates::{Template, Metadata}; #[get("//")] - fn template_check(md: Metadata, engine: &RawStr, name: &RawStr) -> Option<()> { + fn template_check(md: Metadata<'_>, engine: &RawStr, name: &RawStr) -> Option<()> { match md.contains_template(&format!("{}/{}", engine, name)) { true => Some(()), false => None @@ -23,7 +20,7 @@ mod templates_tests { } #[get("/is_reloading")] - fn is_reloading(md: Metadata) -> Option<()> { + fn is_reloading(md: Metadata<'_>) -> Option<()> { if md.reloading() { Some(()) } else { None } } @@ -36,7 +33,7 @@ mod templates_tests { .extra("template_dir", template_root().to_str().expect("template directory")) .expect("valid configuration"); - ::rocket::custom(config).attach(Template::fairing()) + rocket::custom(config).attach(Template::fairing()) .mount("/", routes![template_check, is_reloading]) } diff --git a/core/codegen/Cargo.toml b/core/codegen/Cargo.toml index a5a890556a..9384466ef3 100644 --- a/core/codegen/Cargo.toml +++ b/core/codegen/Cargo.toml @@ -10,6 +10,7 @@ readme = "../../README.md" keywords = ["rocket", "web", "framework", "code", "generation"] license = "MIT/Apache-2.0" build = "build.rs" +edition = "2018" [lib] proc-macro = true diff --git a/core/codegen/build.rs b/core/codegen/build.rs index 1f5c8131c1..75e4a537de 100644 --- a/core/codegen/build.rs +++ b/core/codegen/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/codegen/src/attribute/catch.rs b/core/codegen/src/attribute/catch.rs index 9a32ca12d1..372620d955 100644 --- a/core/codegen/src/attribute/catch.rs +++ b/core/codegen/src/attribute/catch.rs @@ -1,11 +1,11 @@ use proc_macro::{TokenStream, Span}; use devise::{syn, Spanned, Result, FromMeta}; -use proc_macro2::TokenStream as TokenStream2; +use crate::proc_macro2::TokenStream as TokenStream2; -use http_codegen::Status; -use syn_ext::{syn_to_diag, IdentExt, ReturnTypeExt}; +use crate::http_codegen::Status; +use crate::syn_ext::{syn_to_diag, IdentExt, ReturnTypeExt}; use self::syn::{Attribute, parse::Parser}; -use {CATCH_FN_PREFIX, CATCH_STRUCT_PREFIX}; +use crate::{CATCH_FN_PREFIX, CATCH_STRUCT_PREFIX}; /// The raw, parsed `#[catch(code)]` attribute. #[derive(Debug, FromMeta)] diff --git a/core/codegen/src/attribute/route.rs b/core/codegen/src/attribute/route.rs index 638ab0310f..7aa8d945a0 100644 --- a/core/codegen/src/attribute/route.rs +++ b/core/codegen/src/attribute/route.rs @@ -1,15 +1,15 @@ use proc_macro::{TokenStream, Span}; -use proc_macro2::TokenStream as TokenStream2; +use crate::proc_macro2::TokenStream as TokenStream2; use devise::{syn, Spanned, SpanWrapped, Result, FromMeta, ext::TypeExt}; use indexmap::IndexSet; -use proc_macro_ext::{Diagnostics, StringLit}; -use syn_ext::{syn_to_diag, IdentExt}; +use crate::proc_macro_ext::{Diagnostics, StringLit}; +use crate::syn_ext::{syn_to_diag, IdentExt}; use self::syn::{Attribute, parse::Parser}; -use http_codegen::{Method, MediaType, RoutePath, DataSegment, Optional}; -use attribute::segments::{Source, Kind, Segment}; -use {ROUTE_FN_PREFIX, ROUTE_STRUCT_PREFIX, URI_MACRO_PREFIX, ROCKET_PARAM_PREFIX}; +use crate::http_codegen::{Method, MediaType, RoutePath, DataSegment, Optional}; +use crate::attribute::segments::{Source, Kind, Segment}; +use crate::{ROUTE_FN_PREFIX, ROUTE_STRUCT_PREFIX, URI_MACRO_PREFIX, ROCKET_PARAM_PREFIX}; /// The raw, parsed `#[route]` attribute. #[derive(Debug, FromMeta)] @@ -425,7 +425,7 @@ fn complete_route(args: TokenStream2, input: TokenStream) -> Result } fn incomplete_route( - method: ::http::Method, + method: crate::http::Method, args: TokenStream2, input: TokenStream ) -> Result { @@ -459,7 +459,7 @@ fn incomplete_route( codegen_route(parse_route(attribute, function)?) } -pub fn route_attribute>>( +pub fn route_attribute>>( method: M, args: TokenStream, input: TokenStream diff --git a/core/codegen/src/attribute/segments.rs b/core/codegen/src/attribute/segments.rs index 4d1bb43e52..716ea0949e 100644 --- a/core/codegen/src/attribute/segments.rs +++ b/core/codegen/src/attribute/segments.rs @@ -3,11 +3,11 @@ use std::hash::{Hash, Hasher}; use devise::syn; use proc_macro::{Span, Diagnostic}; -use http::uri::{UriPart, Path}; -use http::route::RouteSegment; -use proc_macro_ext::{Diagnostics, StringLit, PResult, DResult}; +use crate::http::uri::{UriPart, Path}; +use crate::http::route::RouteSegment; +use crate::proc_macro_ext::{Diagnostics, StringLit, PResult, DResult}; -crate use http::route::{Error, Kind, Source}; +crate use crate::http::route::{Error, Kind, Source}; #[derive(Debug, Clone)] crate struct Segment { @@ -19,7 +19,7 @@ crate struct Segment { } impl Segment { - fn from(segment: RouteSegment

, span: Span) -> Segment { + fn from(segment: RouteSegment<'_, P>, span: Span) -> Segment { let source = match P::DELIMITER { '/' => Source::Path, '&' => Source::Query, @@ -31,7 +31,7 @@ impl Segment { } } -impl<'a> From<&'a syn::Ident> for Segment { +impl From<&syn::Ident> for Segment { fn from(ident: &syn::Ident) -> Segment { Segment { kind: Kind::Static, @@ -76,7 +76,7 @@ fn into_diagnostic( segment: &str, // The segment that failed. source: &str, // The haystack where `segment` can be found. span: Span, // The `Span` of `Source`. - error: &Error, // The error. + error: &Error<'_>, // The error. ) -> Diagnostic { let seg_span = subspan(segment, source, span); match error { @@ -116,7 +116,7 @@ fn into_diagnostic( } crate fn parse_data_segment(segment: &str, span: Span) -> PResult { - >::parse_one(segment) + >::parse_one(segment) .map(|segment| { let mut seg = Segment::from(segment, span); seg.source = Source::Data; @@ -133,7 +133,7 @@ crate fn parse_segments( let mut segments = vec![]; let mut diags = Diagnostics::new(); - for result in >::parse_many(string) { + for result in >::parse_many(string) { if let Err((segment_string, error)) = result { diags.push(into_diagnostic(segment_string, string, span, &error)); if let Error::Trailing(..) = error { diff --git a/core/codegen/src/bang/mod.rs b/core/codegen/src/bang/mod.rs index a0a4eab485..a93785ce77 100644 --- a/core/codegen/src/bang/mod.rs +++ b/core/codegen/src/bang/mod.rs @@ -1,10 +1,10 @@ use proc_macro::TokenStream; -use proc_macro2::TokenStream as TokenStream2; +use crate::proc_macro2::TokenStream as TokenStream2; use devise::{syn, Spanned, Result}; use self::syn::{Path, punctuated::Punctuated, parse::Parser, token::Comma}; -use syn_ext::{IdentExt, syn_to_diag}; -use {ROUTE_STRUCT_PREFIX, CATCH_STRUCT_PREFIX}; +use crate::syn_ext::{IdentExt, syn_to_diag}; +use crate::{ROUTE_STRUCT_PREFIX, CATCH_STRUCT_PREFIX}; mod uri; mod uri_parsing; diff --git a/core/codegen/src/bang/uri.rs b/core/codegen/src/bang/uri.rs index ac890d66e6..8b0c7fc6c1 100644 --- a/core/codegen/src/bang/uri.rs +++ b/core/codegen/src/bang/uri.rs @@ -1,17 +1,17 @@ use std::fmt::Display; use proc_macro::TokenStream; -use proc_macro2::TokenStream as TokenStream2; +use crate::proc_macro2::TokenStream as TokenStream2; use devise::{syn, Result}; use devise::syn::{Expr, Ident, Type, spanned::Spanned}; -use http::{uri::{Origin, Path, Query}, ext::IntoOwned}; -use http::route::{RouteSegment, Kind, Source}; +use crate::http::{uri::{Origin, Path, Query}, ext::IntoOwned}; +use crate::http::route::{RouteSegment, Kind, Source}; -use http_codegen::Optional; -use syn_ext::{IdentExt, syn_to_diag}; -use bang::{prefix_last_segment, uri_parsing::*}; +use crate::http_codegen::Optional; +use crate::syn_ext::{IdentExt, syn_to_diag}; +use crate::bang::{prefix_last_segment, uri_parsing::*}; -use URI_MACRO_PREFIX; +use crate::URI_MACRO_PREFIX; macro_rules! p { (@go $num:expr, $singular:expr, $plural:expr) => ( @@ -122,7 +122,7 @@ fn add_binding(to: &mut Vec, ident: &Ident, ty: &Type, expr: &Expr } fn explode_path<'a, I: Iterator>( - uri: &Origin, + uri: &Origin<'_>, bindings: &mut Vec, mut items: I ) -> TokenStream2 { @@ -132,7 +132,7 @@ fn explode_path<'a, I: Iterator>( } let uri_display = quote!(#uri_mod::UriDisplay<#uri_mod::Path>); - let dyn_exprs = >::parse(uri).map(|segment| { + let dyn_exprs = >::parse(uri).map(|segment| { let segment = segment.expect("segment okay; prechecked on parse"); match segment.kind { Kind::Static => { @@ -151,7 +151,7 @@ fn explode_path<'a, I: Iterator>( } fn explode_query<'a, I: Iterator>( - uri: &Origin, + uri: &Origin<'_>, bindings: &mut Vec, mut items: I ) -> Option { @@ -162,7 +162,7 @@ fn explode_query<'a, I: Iterator>( let query_arg = quote!(#uri_mod::UriQueryArgument); let uri_display = quote!(#uri_mod::UriDisplay<#uri_mod::Query>); - let dyn_exprs = >::parse(uri)?.filter_map(|segment| { + let dyn_exprs = >::parse(uri)?.filter_map(|segment| { let segment = segment.expect("segment okay; prechecked on parse"); if segment.kind == Kind::Static { let string = &segment.string; diff --git a/core/codegen/src/bang/uri_parsing.rs b/core/codegen/src/bang/uri_parsing.rs index ddb765dead..ab6edf8be7 100644 --- a/core/codegen/src/bang/uri_parsing.rs +++ b/core/codegen/src/bang/uri_parsing.rs @@ -9,7 +9,7 @@ use self::syn::{Expr, Ident, LitStr, Path, Token, Type}; use self::syn::parse::{self, Parse, ParseStream}; use self::syn::punctuated::Punctuated; -use http::{uri::Origin, ext::IntoOwned}; +use crate::http::{uri::Origin, ext::IntoOwned}; use indexmap::IndexMap; #[derive(Debug)] @@ -79,7 +79,7 @@ pub struct InternalUriParams { } impl Parse for ArgExpr { - fn parse(input: ParseStream) -> parse::Result { + fn parse(input: ParseStream<'_>) -> parse::Result { if input.peek(Token![_]) { return Ok(ArgExpr::Ignored(input.parse::()?)); } @@ -89,7 +89,7 @@ impl Parse for ArgExpr { } impl Parse for Arg { - fn parse(input: ParseStream) -> parse::Result { + fn parse(input: ParseStream<'_>) -> parse::Result { let has_key = input.peek2(Token![=]); if has_key { let ident = input.parse::()?; @@ -109,7 +109,7 @@ fn err>(span: Span, s: S) -> parse::Result { impl Parse for UriParams { // Parses the mount point, if any, route identifier, and arguments. - fn parse(input: ParseStream) -> parse::Result { + fn parse(input: ParseStream<'_>) -> parse::Result { if input.is_empty() { return Err(input.error("call to `uri!` cannot be empty")); } @@ -176,7 +176,7 @@ impl Parse for UriParams { } impl Parse for FnArg { - fn parse(input: ParseStream) -> parse::Result { + fn parse(input: ParseStream<'_>) -> parse::Result { let ident = input.parse::()?; input.parse::()?; let mut ty = input.parse::()?; @@ -186,7 +186,7 @@ impl Parse for FnArg { } impl Parse for InternalUriParams { - fn parse(input: ParseStream) -> parse::Result { + fn parse(input: ParseStream<'_>) -> parse::Result { let route_uri_str = input.parse::()?; input.parse::()?; @@ -215,7 +215,7 @@ impl InternalUriParams { .join(", ") } - pub fn validate(&self) -> Validation { + pub fn validate(&self) -> Validation<'_> { let args = &self.uri_params.arguments; match args { Args::Unnamed(inner) => { diff --git a/core/codegen/src/derive/from_form.rs b/core/codegen/src/derive/from_form.rs index 27b84875ee..5a6835323e 100644 --- a/core/codegen/src/derive/from_form.rs +++ b/core/codegen/src/derive/from_form.rs @@ -23,7 +23,7 @@ fn is_valid_field_name(s: &str) -> bool { } impl FromMeta for FormField { - fn from_meta(meta: MetaItem) -> Result { + fn from_meta(meta: MetaItem<'_>) -> Result { let string = String::from_meta(meta)?; if !is_valid_field_name(&string) { return Err(meta.value_span().error("invalid form field name")); @@ -33,7 +33,7 @@ impl FromMeta for FormField { } } -fn validate_struct(gen: &DeriveGenerator, data: Struct) -> Result<()> { +fn validate_struct(gen: &DeriveGenerator, data: Struct<'_>) -> Result<()> { if data.fields().is_empty() { return Err(gen.input.span().error("at least one field is required")); } diff --git a/core/codegen/src/derive/responder.rs b/core/codegen/src/derive/responder.rs index e2c87a9cf4..4e181209d2 100644 --- a/core/codegen/src/derive/responder.rs +++ b/core/codegen/src/derive/responder.rs @@ -3,7 +3,7 @@ use proc_macro::TokenStream; use devise::{*, ext::TypeExt}; use devise::proc_macro2::TokenStream as TokenStream2; -use http_codegen::{ContentType, Status}; +use crate::http_codegen::{ContentType, Status}; #[derive(Default, FromMeta)] struct ItemAttr { diff --git a/core/codegen/src/derive/uri_display.rs b/core/codegen/src/derive/uri_display.rs index 4c59213365..aaf0fb9499 100644 --- a/core/codegen/src/derive/uri_display.rs +++ b/core/codegen/src/derive/uri_display.rs @@ -1,8 +1,8 @@ use proc_macro::{Span, TokenStream}; use devise::*; -use derive::from_form::Form; -use proc_macro2::TokenStream as TokenStream2; +use crate::derive::from_form::Form; +use crate::proc_macro2::TokenStream as TokenStream2; const NO_EMPTY_FIELDS: &str = "fieldless structs or variants are not supported"; const NO_NULLARY: &str = "nullary items are not supported"; @@ -10,7 +10,7 @@ const NO_EMPTY_ENUMS: &str = "empty enums are not supported"; const ONLY_ONE_UNNAMED: &str = "tuple structs or variants must have exactly one field"; const EXACTLY_ONE_FIELD: &str = "struct must have exactly one field"; -fn validate_fields(fields: Fields, parent_span: Span) -> Result<()> { +fn validate_fields(fields: Fields<'_>, parent_span: Span) -> Result<()> { if fields.count() == 0 { return Err(parent_span.error(NO_EMPTY_FIELDS)) } else if fields.are_unnamed() && fields.count() > 1 { @@ -22,11 +22,11 @@ fn validate_fields(fields: Fields, parent_span: Span) -> Result<()> { Ok(()) } -fn validate_struct(gen: &DeriveGenerator, data: Struct) -> Result<()> { +fn validate_struct(gen: &DeriveGenerator, data: Struct<'_>) -> Result<()> { validate_fields(data.fields(), gen.input.span()) } -fn validate_enum(gen: &DeriveGenerator, data: Enum) -> Result<()> { +fn validate_enum(gen: &DeriveGenerator, data: Enum<'_>) -> Result<()> { if data.variants().count() == 0 { return Err(gen.input.span().error(NO_EMPTY_ENUMS)); } diff --git a/core/codegen/src/http_codegen.rs b/core/codegen/src/http_codegen.rs index 1d44508a8c..782394282c 100644 --- a/core/codegen/src/http_codegen.rs +++ b/core/codegen/src/http_codegen.rs @@ -1,11 +1,11 @@ use quote::ToTokens; -use proc_macro2::TokenStream as TokenStream2; +use crate::proc_macro2::TokenStream as TokenStream2; use devise::{FromMeta, MetaItem, Result, ext::Split2}; -use http::{self, ext::IntoOwned}; -use http::uri::{Path, Query}; -use attribute::segments::{parse_segments, parse_data_segment, Segment, Kind}; +use crate::http::{self, ext::IntoOwned}; +use crate::http::uri::{Path, Query}; +use crate::attribute::segments::{parse_segments, parse_data_segment, Segment, Kind}; -use proc_macro_ext::StringLit; +use crate::proc_macro_ext::StringLit; #[derive(Debug)] crate struct ContentType(crate http::ContentType); @@ -29,7 +29,7 @@ crate struct DataSegment(crate Segment); crate struct Optional(crate Option); impl FromMeta for StringLit { - fn from_meta(meta: MetaItem) -> Result { + fn from_meta(meta: MetaItem<'_>) -> Result { Ok(StringLit::new(String::from_meta(meta)?, meta.value_span())) } } @@ -42,7 +42,7 @@ crate struct RoutePath { } impl FromMeta for Status { - fn from_meta(meta: MetaItem) -> Result { + fn from_meta(meta: MetaItem<'_>) -> Result { let num = usize::from_meta(meta)?; if num < 100 || num >= 600 { return Err(meta.value_span().error("status must be in range [100, 599]")); @@ -60,7 +60,7 @@ impl ToTokens for Status { } impl FromMeta for ContentType { - fn from_meta(meta: MetaItem) -> Result { + fn from_meta(meta: MetaItem<'_>) -> Result { http::ContentType::parse_flexible(&String::from_meta(meta)?) .map(ContentType) .ok_or(meta.value_span().error("invalid or unknown content type")) @@ -76,7 +76,7 @@ impl ToTokens for ContentType { } impl FromMeta for MediaType { - fn from_meta(meta: MetaItem) -> Result { + fn from_meta(meta: MetaItem<'_>) -> Result { let mt = http::MediaType::parse_flexible(&String::from_meta(meta)?) .ok_or(meta.value_span().error("invalid or unknown media type"))?; @@ -126,7 +126,7 @@ const VALID_METHODS: &[http::Method] = &[ ]; impl FromMeta for Method { - fn from_meta(meta: MetaItem) -> Result { + fn from_meta(meta: MetaItem<'_>) -> Result { let span = meta.value_span(); let help_text = format!("method must be one of: {}", VALID_METHODS_STR); @@ -166,7 +166,7 @@ impl ToTokens for Method { } impl FromMeta for Origin { - fn from_meta(meta: MetaItem) -> Result { + fn from_meta(meta: MetaItem<'_>) -> Result { let string = StringLit::from_meta(meta)?; let uri = http::uri::Origin::parse_route(&string) @@ -190,7 +190,7 @@ impl FromMeta for Origin { } impl FromMeta for DataSegment { - fn from_meta(meta: MetaItem) -> Result { + fn from_meta(meta: MetaItem<'_>) -> Result { let string = StringLit::from_meta(meta)?; let span = string.subspan(1..(string.len() + 1)); @@ -205,7 +205,7 @@ impl FromMeta for DataSegment { } impl FromMeta for RoutePath { - fn from_meta(meta: MetaItem) -> Result { + fn from_meta(meta: MetaItem<'_>) -> Result { let (origin, string) = (Origin::from_meta(meta)?, StringLit::from_meta(meta)?); let path_span = string.subspan(1..origin.0.path().len() + 1); let path = parse_segments::(origin.0.path(), path_span); diff --git a/core/codegen/src/lib.rs b/core/codegen/src/lib.rs index a8657877c6..e7fc207c6b 100644 --- a/core/codegen/src/lib.rs +++ b/core/codegen/src/lib.rs @@ -6,6 +6,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 - Code Generation //! //! This crate implements the code generation portions of Rocket. This includes @@ -58,10 +60,9 @@ //! ``` #[macro_use] extern crate quote; -extern crate devise; extern crate proc_macro; -extern crate rocket_http as http; -extern crate indexmap; + +use rocket_http as http; macro_rules! define { ($val:path as $v:ident) => (#[allow(non_snake_case)] let $v = quote!($val);); @@ -97,7 +98,7 @@ mod bang; mod http_codegen; mod syn_ext; -use http::Method; +use crate::http::Method; use proc_macro::TokenStream; crate use devise::proc_macro2; @@ -111,8 +112,8 @@ crate static ROCKET_PARAM_PREFIX: &str = "__rocket_param_"; macro_rules! emit { ($tokens:expr) => ({ let tokens = $tokens; - if ::std::env::var_os("ROCKET_CODEGEN_DEBUG").is_some() { - ::proc_macro::Span::call_site() + if std::env::var_os("ROCKET_CODEGEN_DEBUG").is_some() { + proc_macro::Span::call_site() .note("emitting Rocket code generation debug output") .note(tokens.to_string()) .emit() diff --git a/core/codegen/src/proc_macro_ext.rs b/core/codegen/src/proc_macro_ext.rs index 6d4e0b03b3..e084962eed 100644 --- a/core/codegen/src/proc_macro_ext.rs +++ b/core/codegen/src/proc_macro_ext.rs @@ -2,9 +2,9 @@ use std::ops::RangeBounds; use proc_macro::{Span, Diagnostic, Literal}; -pub type PResult = ::std::result::Result; +pub type PResult = std::result::Result; -pub type DResult = ::std::result::Result; +pub type DResult = std::result::Result; // An experiment. pub struct Diagnostics(Vec); diff --git a/core/codegen/tests/from_form.rs b/core/codegen/tests/from_form.rs index 72c7d156a9..0530e005af 100644 --- a/core/codegen/tests/from_form.rs +++ b/core/codegen/tests/from_form.rs @@ -103,7 +103,7 @@ fn base_conditions() { "checkbox=off", "textarea=", "select=a", "radio=c", ].join("&"); - let input: Option = strict(&form_string).ok(); + let input: Option> = strict(&form_string).ok(); assert_eq!(input, Some(FormInput { checkbox: false, number: 10, @@ -114,26 +114,26 @@ fn base_conditions() { })); // Argument not in string with default in form. - let default: Option = strict("").ok(); + let default: Option> = strict("").ok(); assert_eq!(default, Some(DefaultInput { arg: None })); // Ensure _method can be captured if desired. - let manual: Option = strict("_method=put&done=true").ok(); + let manual: Option> = strict("_method=put&done=true").ok(); assert_eq!(manual, Some(ManualMethod { _method: Some("put".into()), done: true })); - let manual: Option = lenient("_method=put&done=true").ok(); + let manual: Option> = lenient("_method=put&done=true").ok(); assert_eq!(manual, Some(ManualMethod { _method: Some("put".into()), done: true })); // And ignored when not present. - let manual: Option = strict("done=true").ok(); + let manual: Option> = strict("done=true").ok(); assert_eq!(manual, Some(ManualMethod { _method: None, done: true @@ -146,14 +146,14 @@ fn base_conditions() { })); // Check that a `bool` value that isn't in the form is marked as `false`. - let manual: Option = strict("something=hello").ok(); + let manual: Option> = strict("something=hello").ok(); assert_eq!(manual, Some(UnpresentCheckboxTwo { checkbox: false, something: "hello".into() })); // Check that a structure with one field `v` parses correctly. - let manual: Option = strict("v=abc").ok(); + let manual: Option> = strict("v=abc").ok(); assert_eq!(manual, Some(FieldNamedV { v: "abc".into() })); @@ -163,33 +163,33 @@ fn base_conditions() { #[test] fn lenient_parsing() { // Check that a structure with one field `v` parses correctly (lenient). - let manual: Option = lenient("v=abc").ok(); + let manual: Option> = lenient("v=abc").ok(); assert_eq!(manual, Some(FieldNamedV { v: "abc".into() })); - let manual: Option = lenient("v=abc&a=123").ok(); + let manual: Option> = lenient("v=abc&a=123").ok(); assert_eq!(manual, Some(FieldNamedV { v: "abc".into() })); - let manual: Option = lenient("c=abcddef&v=abc&a=123").ok(); + let manual: Option> = lenient("c=abcddef&v=abc&a=123").ok(); assert_eq!(manual, Some(FieldNamedV { v: "abc".into() })); // Check default values (bool) with lenient parsing. - let manual: Option = lenient("something=hello").ok(); + let manual: Option> = lenient("something=hello").ok(); assert_eq!(manual, Some(UnpresentCheckboxTwo { checkbox: false, something: "hello".into() })); - let manual: Option = lenient("hi=hi&something=hello").ok(); + let manual: Option> = lenient("hi=hi&something=hello").ok(); assert_eq!(manual, Some(UnpresentCheckboxTwo { checkbox: false, something: "hello".into() })); // Check that a missing field doesn't parse, even leniently. - let manual: Option = lenient("a=abc").ok(); + let manual: Option> = lenient("a=abc").ok(); assert!(manual.is_none()); - let manual: Option = lenient("_method=abc").ok(); + let manual: Option> = lenient("_method=abc").ok(); assert!(manual.is_none()); } @@ -257,19 +257,19 @@ fn generics() { "string=hello", "other=00128" ].join("&"); - let form: Option> = strict(&form_string).ok(); + let form: Option> = strict(&form_string).ok(); assert_eq!(form, Some(YetOneMore { string: "hello".into(), other: 128, })); - let form: Option> = strict(&form_string).ok(); + let form: Option> = strict(&form_string).ok(); assert_eq!(form, Some(YetOneMore { string: "hello".into(), other: 128, })); - let form: Option> = strict(&form_string).ok(); + let form: Option> = strict(&form_string).ok(); assert!(form.is_none()); let form_string = &[ diff --git a/core/codegen/tests/from_form_value.rs b/core/codegen/tests/from_form_value.rs index 0d81ad8a53..b21300a604 100644 --- a/core/codegen/tests/from_form_value.rs +++ b/core/codegen/tests/from_form_value.rs @@ -1,5 +1,3 @@ -extern crate rocket; - use rocket::request::FromFormValue; macro_rules! assert_parse { diff --git a/core/codegen/tests/responder.rs b/core/codegen/tests/responder.rs index f7c8233804..6c7d1d1ac2 100644 --- a/core/codegen/tests/responder.rs +++ b/core/codegen/tests/responder.rs @@ -1,7 +1,5 @@ #![feature(proc_macro_hygiene, decl_macro)] -extern crate rocket; - use rocket::local::Client; use rocket::response::Responder; use rocket::http::{Status, ContentType, Cookie}; @@ -14,12 +12,12 @@ pub enum Foo<'r> { #[response(status = 404, content_type = "html")] Third { responder: &'r str, - ct: ::rocket::http::ContentType, + ct: rocket::http::ContentType, }, #[response(status = 105)] Fourth { string: &'r str, - ct: ::rocket::http::ContentType, + ct: rocket::http::ContentType, }, } diff --git a/core/codegen/tests/route-data.rs b/core/codegen/tests/route-data.rs index 640e0ada3a..168de24b71 100644 --- a/core/codegen/tests/route-data.rs +++ b/core/codegen/tests/route-data.rs @@ -22,7 +22,7 @@ struct Simple(String); impl FromDataSimple for Simple { type Error = (); - fn from_data(_: &Request, data: Data) -> data::Outcome { + fn from_data(_: &Request<'_>, data: Data) -> data::Outcome { let mut string = String::new(); if let Err(_) = data.open().take(64).read_to_string(&mut string) { return Failure((Status::InternalServerError, ())); @@ -33,7 +33,7 @@ impl FromDataSimple for Simple { } #[post("/f", data = "

")] -fn form(form: Form) -> String { form.field.url_decode_lossy() } +fn form(form: Form>) -> String { form.field.url_decode_lossy() } #[post("/s", data = "")] fn simple(simple: Simple) -> String { simple.0 } diff --git a/core/codegen/tests/route.rs b/core/codegen/tests/route.rs index c418e23265..ecc554663e 100644 --- a/core/codegen/tests/route.rs +++ b/core/codegen/tests/route.rs @@ -28,7 +28,7 @@ struct Simple(String); impl FromDataSimple for Simple { type Error = (); - fn from_data(_: &Request, data: Data) -> data::Outcome { + fn from_data(_: &Request<'_>, data: Data) -> data::Outcome { use std::io::Read; let mut string = String::new(); data.open().take(64).read_to_string(&mut string).unwrap(); @@ -41,7 +41,7 @@ fn post1( sky: usize, name: &RawStr, a: String, - query: Form, + query: Form>, path: PathBuf, simple: Simple, ) -> String { @@ -58,7 +58,7 @@ fn post2( sky: usize, name: &RawStr, a: String, - query: Form, + query: Form>, path: PathBuf, simple: Simple, ) -> String { diff --git a/core/codegen/tests/typed-uris.rs b/core/codegen/tests/typed-uris.rs index d1ab280ac8..28fac9a3b7 100644 --- a/core/codegen/tests/typed-uris.rs +++ b/core/codegen/tests/typed-uris.rs @@ -52,13 +52,13 @@ fn simple4_flipped(name: String, id: i32) { } fn unused_param(used: i32, _unused: i32) { } #[post("/")] -fn guard_1(cookies: Cookies, id: i32) { } +fn guard_1(cookies: Cookies<'_>, id: i32) { } #[post("//")] -fn guard_2(name: String, cookies: Cookies, id: i32) { } +fn guard_2(name: String, cookies: Cookies<'_>, id: i32) { } #[post("/a//hi//hey")] -fn guard_3(id: i32, name: String, cookies: Cookies) { } +fn guard_3(id: i32, name: String, cookies: Cookies<'_>) { } #[post("/", data = "")] fn no_uri_display_okay(id: i32, form: Form) { } @@ -70,7 +70,7 @@ fn complex<'r>( query: Form>, user: Form>, bar: &RawStr, - cookies: Cookies + cookies: Cookies<'_> ) { } #[post("/a/")] @@ -80,7 +80,7 @@ fn segments(path: PathBuf) { } fn param_and_segments(path: PathBuf, id: usize) { } #[post("/a//then/")] -fn guarded_segments(cookies: Cookies, path: PathBuf, id: usize) { } +fn guarded_segments(cookies: Cookies<'_>, path: PathBuf, id: usize) { } macro assert_uri_eq($($uri:expr => $expected:expr,)+) { $(assert_eq!($uri, Origin::parse($expected).expect("valid origin URI"));)+ @@ -332,9 +332,9 @@ mod typed_uris { fn check_simple_scoped() { assert_uri_eq! { uri!(simple: id = 100) => "/typed_uris/100", - uri!(::simple: id = 100) => "/100", - uri!("/mount", ::simple: id = 100) => "/mount/100", - uri!(::simple2: id = 100, name = "hello") => "/100/hello", + uri!(crate::simple: id = 100) => "/100", + uri!("/mount", crate::simple: id = 100) => "/mount/100", + uri!(crate::simple2: id = 100, name = "hello") => "/100/hello", } } @@ -348,7 +348,7 @@ mod typed_uris { fn check_deep_scoped() { assert_uri_eq! { uri!(super::simple: id = 100) => "/typed_uris/100", - uri!(::simple: id = 100) => "/100", + uri!(crate::simple: id = 100) => "/100", } } } @@ -365,7 +365,7 @@ fn optionals( foo: Option, bar: Result, q1: Result, - rest: Option> + rest: Option>> ) { } #[test] diff --git a/core/codegen/tests/ui-fail/responder-types.rs b/core/codegen/tests/ui-fail/responder-types.rs index c6eb14ddd4..14e73fda51 100644 --- a/core/codegen/tests/ui-fail/responder-types.rs +++ b/core/codegen/tests/ui-fail/responder-types.rs @@ -27,7 +27,7 @@ struct Thing3 { #[derive(Responder)] struct Thing4 { thing: String, - other: ::rocket::http::ContentType, + other: rocket::http::ContentType, then: String, //~^ ERROR Header } diff --git a/core/codegen/tests/uri_display.rs b/core/codegen/tests/uri_display.rs index f8a4627c98..fd233ef629 100644 --- a/core/codegen/tests/uri_display.rs +++ b/core/codegen/tests/uri_display.rs @@ -7,7 +7,7 @@ use rocket::http::uri::{UriDisplay, Query, Path}; macro_rules! assert_uri_display_query { ($v:expr, $s:expr) => ( - let uri_string = format!("{}", &$v as &UriDisplay); + let uri_string = format!("{}", &$v as &dyn UriDisplay); assert_eq!(uri_string, $s); ) } @@ -117,7 +117,7 @@ fn uri_display_bam() { macro_rules! assert_uri_display_path { ($v:expr, $s:expr) => ( - let uri_string = format!("{}", &$v as &UriDisplay); + let uri_string = format!("{}", &$v as &dyn UriDisplay); assert_eq!(uri_string, $s); ) } diff --git a/core/http/Cargo.toml b/core/http/Cargo.toml index 3f440efdea..9a2241b920 100644 --- a/core/http/Cargo.toml +++ b/core/http/Cargo.toml @@ -12,6 +12,7 @@ readme = "../../README.md" keywords = ["rocket", "web", "framework", "http"] license = "MIT/Apache-2.0" categories = ["web-programming"] +edition = "2018" [features] default = [] diff --git a/core/http/src/accept.rs b/core/http/src/accept.rs index 07fc9a74bf..545f51735e 100644 --- a/core/http/src/accept.rs +++ b/core/http/src/accept.rs @@ -4,9 +4,9 @@ use std::fmt; use smallvec::SmallVec; -use {Header, MediaType}; -use ext::IntoCollection; -use parse::parse_accept; +use crate::{Header, MediaType}; +use crate::ext::IntoCollection; +use crate::parse::parse_accept; /// A `MediaType` with an associated quality value. #[derive(Debug, Clone, PartialEq)] @@ -88,7 +88,7 @@ pub enum AcceptParams { Dynamic(SmallVec<[QMediaType; 1]>) } -impl ::pear::parsers::Collection for AcceptParams { +impl pear::parsers::Collection for AcceptParams { type Item = QMediaType; fn new() -> Self { @@ -130,7 +130,7 @@ impl PartialEq for AcceptParams { /// [`Request::accept()`] method. The [`preferred()`] method can be used to /// retrieve the client's preferred media type. /// -/// [`Request::accept`]: ::rocket::Request::accept() +/// [`Request::accept`]: rocket::Request::accept() /// [`preferred()`]: Accept::preferred() /// /// An `Accept` type with a single, common media type can be easily constructed @@ -353,7 +353,7 @@ impl Accept { } impl fmt::Display for Accept { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for (i, media_type) in self.iter().enumerate() { if i >= 1 { write!(f, ", {}", media_type.0)?; @@ -387,7 +387,7 @@ impl Into> for Accept { #[cfg(test)] mod test { - use {Accept, MediaType}; + use crate::{Accept, MediaType}; macro_rules! assert_preference { ($string:expr, $expect:expr) => ( diff --git a/core/http/src/content_type.rs b/core/http/src/content_type.rs index d7ca7bf270..be8f881f3d 100644 --- a/core/http/src/content_type.rs +++ b/core/http/src/content_type.rs @@ -3,10 +3,10 @@ use std::ops::Deref; use std::str::FromStr; use std::fmt; -use header::Header; -use media_type::{MediaType, Source}; -use ext::IntoCollection; -use hyper::mime::Mime; +use crate::header::Header; +use crate::media_type::{MediaType, Source}; +use crate::ext::IntoCollection; +use crate::hyper::mime::Mime; /// Representation of HTTP Content-Types. /// @@ -350,7 +350,7 @@ impl fmt::Display for ContentType { /// assert_eq!(ct, "application/json"); /// ``` #[inline(always)] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } diff --git a/core/http/src/cookies.rs b/core/http/src/cookies.rs index 31fdadb221..a66acce836 100644 --- a/core/http/src/cookies.rs +++ b/core/http/src/cookies.rs @@ -1,7 +1,7 @@ use std::fmt; use std::cell::RefMut; -use Header; +use crate::Header; use cookie::Delta; #[doc(hidden)] pub use self::key::*; @@ -40,7 +40,7 @@ mod key { /// can be added or removed via the [`add()`], [`add_private()`], [`remove()`], /// and [`remove_private()`] methods. /// -/// [`Request::cookies()`]: ::rocket::Request::cookies() +/// [`Request::cookies()`]: rocket::Request::cookies() /// [`get()`]: #method.get /// [`get_private()`]: #method.get_private /// [`add()`]: #method.add @@ -84,10 +84,10 @@ mod key { /// // In practice, we'd probably fetch the user from the database. /// struct User(usize); /// -/// impl<'a, 'r> FromRequest<'a, 'r> for User { +/// impl FromRequest<'_, '_> for User { /// type Error = !; /// -/// fn from_request(request: &'a Request<'r>) -> request::Outcome { +/// fn from_request(request: &Request<'_>) -> request::Outcome { /// request.cookies() /// .get_private("user_id") /// .and_then(|cookie| cookie.value().parse().ok()) @@ -260,7 +260,7 @@ impl<'a> Cookies<'a> { /// WARNING: This is unstable! Do not use this method outside of Rocket! #[inline] #[doc(hidden)] - pub fn delta(&self) -> Delta { + pub fn delta(&self) -> Delta<'_> { match *self { Cookies::Jarred(ref jar, _) => jar.delta(), Cookies::Empty(ref jar) => jar.delta() @@ -269,7 +269,7 @@ impl<'a> Cookies<'a> { } #[cfg(feature = "private-cookies")] -impl<'a> Cookies<'a> { +impl Cookies<'_> { /// Returns a reference to the `Cookie` inside this collection with the name /// `name` and authenticates and decrypts the cookie's value, returning a /// `Cookie` with the decrypted value. If the cookie cannot be found, or the @@ -362,7 +362,7 @@ impl<'a> Cookies<'a> { } if cookie.expires().is_none() { - cookie.set_expires(::time::now() + ::time::Duration::weeks(1)); + cookie.set_expires(time::now() + time::Duration::weeks(1)); } if cookie.same_site().is_none() { @@ -400,8 +400,8 @@ impl<'a> Cookies<'a> { } } -impl<'a> fmt::Debug for Cookies<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +impl fmt::Debug for Cookies<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Cookies::Jarred(ref jar, _) => write!(f, "{:?}", jar), Cookies::Empty(ref jar) => write!(f, "{:?}", jar) @@ -409,14 +409,14 @@ impl<'a> fmt::Debug for Cookies<'a> { } } -impl<'c> From> for Header<'static> { - fn from(cookie: Cookie) -> Header<'static> { +impl From> for Header<'static> { + fn from(cookie: Cookie<'_>) -> Header<'static> { Header::new("Set-Cookie", cookie.encoded().to_string()) } } -impl<'a, 'c> From<&'a Cookie<'c>> for Header<'static> { - fn from(cookie: &Cookie) -> Header<'static> { +impl From<&Cookie<'_>> for Header<'static> { + fn from(cookie: &Cookie<'_>) -> Header<'static> { Header::new("Set-Cookie", cookie.encoded().to_string()) } } diff --git a/core/http/src/ext.rs b/core/http/src/ext.rs index a37797e90a..1f5eb5b188 100644 --- a/core/http/src/ext.rs +++ b/core/http/src/ext.rs @@ -41,7 +41,7 @@ impl IntoCollection for Vec { macro_rules! impl_for_slice { ($($size:tt)*) => ( - impl<'a, T: Clone> IntoCollection for &'a [T $($size)*] { + impl IntoCollection for &[T $($size)*] { #[inline(always)] fn into_collection>(self) -> SmallVec { self.iter().cloned().collect() @@ -90,7 +90,7 @@ impl IntoOwned for Option { } } -impl<'a, B: 'static + ToOwned + ?Sized> IntoOwned for Cow<'a, B> { +impl IntoOwned for Cow<'_, B> { type Owned = Cow<'static, B>; #[inline(always)] @@ -104,7 +104,7 @@ use std::path::Path; // Outside of http, this is used by a test. #[doc(hidden)] pub trait Normalize { - fn normalized_str(&self) -> Cow; + fn normalized_str(&self) -> Cow<'_, str>; } impl> Normalize for T { @@ -114,7 +114,7 @@ impl> Normalize for T { } #[cfg(not(windows))] - fn normalized_str(&self) -> Cow { + fn normalized_str(&self) -> Cow<'_, str> { self.as_ref().to_string_lossy() } } diff --git a/core/http/src/header.rs b/core/http/src/header.rs index dd52da63e9..c295422304 100644 --- a/core/http/src/header.rs +++ b/core/http/src/header.rs @@ -3,7 +3,7 @@ use std::fmt; use indexmap::IndexMap; -use uncased::{Uncased, UncasedStr}; +use crate::uncased::{Uncased, UncasedStr}; /// Simple representation of an HTTP header. #[derive(Debug, Clone, Hash, PartialEq, Eq)] @@ -17,8 +17,9 @@ pub struct Header<'h> { impl<'h> Header<'h> { /// Constructs a new header. This method should be used rarely and only for /// non-standard headers. Instead, prefer to use the `Into
` - /// implementations of many types, including [`ContentType`] and all of the - /// headers in [`http::hyper::header`](hyper::header). + /// implementations of many types, including + /// [`ContentType`](crate::ContentType) and all of the headers in + /// [`http::hyper::header`](hyper::header). /// /// # Examples /// @@ -104,9 +105,9 @@ impl<'h> Header<'h> { } } -impl<'h> fmt::Display for Header<'h> { +impl fmt::Display for Header<'_> { #[inline(always)] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}: {}", self.name, self.value) } } @@ -222,7 +223,7 @@ impl<'h> HeaderMap<'h> { /// assert_eq!(values.next(), None); /// ``` #[inline] - pub fn get<'a>(&'a self, name: &str) -> impl Iterator { + pub fn get(&self, name: &str) -> impl Iterator { self.headers .get(UncasedStr::new(name)) .into_iter() @@ -520,7 +521,7 @@ impl<'h> HeaderMap<'h> { /// ``` #[inline(always)] pub fn remove_all(&mut self) -> Vec> { - let old_map = ::std::mem::replace(self, HeaderMap::new()); + let old_map = std::mem::replace(self, HeaderMap::new()); old_map.into_iter().collect() } @@ -560,7 +561,7 @@ impl<'h> HeaderMap<'h> { /// } /// } /// ``` - pub fn iter(&self) -> impl Iterator { + pub fn iter(&self) -> impl Iterator> { self.headers.iter().flat_map(|(key, values)| { values.iter().map(move |val| { Header::new(key.as_str(), &**val) diff --git a/core/http/src/hyper.rs b/core/http/src/hyper.rs index 12902e92a2..b56e41166a 100644 --- a/core/http/src/hyper.rs +++ b/core/http/src/hyper.rs @@ -4,40 +4,38 @@ //! These types will, with certainty, be removed with time, but they reside here //! while necessary. -extern crate hyper; +#[doc(hidden)] pub use hyper::server::Request as Request; +#[doc(hidden)] pub use hyper::server::Response as Response; +#[doc(hidden)] pub use hyper::server::Server as Server; +#[doc(hidden)] pub use hyper::server::Handler as Handler; -#[doc(hidden)] pub use self::hyper::server::Request as Request; -#[doc(hidden)] pub use self::hyper::server::Response as Response; -#[doc(hidden)] pub use self::hyper::server::Server as Server; -#[doc(hidden)] pub use self::hyper::server::Handler as Handler; +#[doc(hidden)] pub use hyper::net; -#[doc(hidden)] pub use self::hyper::net; +#[doc(hidden)] pub use hyper::method::Method; +#[doc(hidden)] pub use hyper::status::StatusCode; +#[doc(hidden)] pub use hyper::error::Error; +#[doc(hidden)] pub use hyper::uri::RequestUri; +#[doc(hidden)] pub use hyper::http::h1; +#[doc(hidden)] pub use hyper::buffer; -#[doc(hidden)] pub use self::hyper::method::Method; -#[doc(hidden)] pub use self::hyper::status::StatusCode; -#[doc(hidden)] pub use self::hyper::error::Error; -#[doc(hidden)] pub use self::hyper::uri::RequestUri; -#[doc(hidden)] pub use self::hyper::http::h1; -#[doc(hidden)] pub use self::hyper::buffer; +pub use hyper::mime; -pub use self::hyper::mime; - -/// Type alias to `self::hyper::Response<'a, self::hyper::net::Fresh>`. +/// Type alias to `hyper::Response<'a, hyper::net::Fresh>`. #[doc(hidden)] pub type FreshResponse<'a> = self::Response<'a, self::net::Fresh>; /// Reexported Hyper header types. pub mod header { - use Header; + use crate::Header; - use super::hyper::header::Header as HyperHeaderTrait; + use hyper::header::Header as HyperHeaderTrait; macro_rules! import_hyper_items { - ($($item:ident),*) => ($(pub use super::hyper::header::$item;)*) + ($($item:ident),*) => ($(pub use hyper::header::$item;)*) } macro_rules! import_hyper_headers { ($($name:ident),*) => ($( - impl ::std::convert::From for Header<'static> { + impl std::convert::From for Header<'static> { fn from(header: self::$name) -> Header<'static> { Header::new($name::header_name(), header.to_string()) } diff --git a/core/http/src/lib.rs b/core/http/src/lib.rs index db6c1fac6c..51845708bd 100644 --- a/core/http/src/lib.rs +++ b/core/http/src/lib.rs @@ -4,6 +4,8 @@ #![feature(doc_cfg)] #![recursion_limit="512"] +#![warn(rust_2018_idioms)] + //! Types that map to concepts in HTTP. //! //! This module exports types that map to HTTP concepts or to the underlying @@ -13,13 +15,6 @@ //! [#17]: https://github.com/SergioBenitez/Rocket/issues/17 #[macro_use] extern crate pear; -extern crate percent_encoding; -extern crate smallvec; -extern crate cookie; -extern crate time; -extern crate indexmap; -extern crate state; -extern crate unicode_xid; pub mod hyper; pub mod uri; @@ -54,20 +49,20 @@ pub mod private { // We need to export these for codegen, but otherwise it's unnecessary. // TODO: Expose a `const fn` from ContentType when possible. (see RFC#1817) // FIXME(rustc): These show up in the rexported module. - pub use parse::Indexed; - pub use media_type::{MediaParams, Source}; + pub use crate::parse::Indexed; + pub use crate::media_type::{MediaParams, Source}; pub use smallvec::{SmallVec, Array}; // This one we need to expose for core. - pub use cookies::{Key, CookieJar}; + pub use crate::cookies::{Key, CookieJar}; } -pub use method::Method; -pub use content_type::ContentType; -pub use accept::{Accept, QMediaType}; -pub use status::{Status, StatusClass}; -pub use header::{Header, HeaderMap}; -pub use raw_str::RawStr; +pub use crate::method::Method; +pub use crate::content_type::ContentType; +pub use crate::accept::{Accept, QMediaType}; +pub use crate::status::{Status, StatusClass}; +pub use crate::header::{Header, HeaderMap}; +pub use crate::raw_str::RawStr; -pub use media_type::MediaType; -pub use cookies::{Cookie, SameSite, Cookies}; +pub use crate::media_type::MediaType; +pub use crate::cookies::{Cookie, SameSite, Cookies}; diff --git a/core/http/src/media_type.rs b/core/http/src/media_type.rs index 7b324ccf78..4d3ac5fbf3 100644 --- a/core/http/src/media_type.rs +++ b/core/http/src/media_type.rs @@ -3,9 +3,9 @@ use std::str::FromStr; use std::fmt; use std::hash::{Hash, Hasher}; -use ext::IntoCollection; -use uncased::{uncased_eq, UncasedStr}; -use parse::{Indexed, IndexedString, parse_media_type}; +use crate::ext::IntoCollection; +use crate::uncased::{uncased_eq, UncasedStr}; +use crate::parse::{Indexed, IndexedString, parse_media_type}; use smallvec::SmallVec; @@ -22,7 +22,7 @@ pub enum MediaParams { Dynamic(SmallVec<[(IndexedString, IndexedString); 2]>) } -impl ::pear::parsers::Collection for MediaParams { +impl pear::parsers::Collection for MediaParams { type Item = (IndexedString, IndexedString); fn new() -> Self { @@ -60,11 +60,12 @@ impl Source { /// # Usage /// /// A `MediaType` should rarely be used directly. Instead, one is typically used -/// indirectly via types like [`Accept`] and [`ContentType`], which internally -/// contain `MediaType`s. Nonetheless, a `MediaType` can be created via the -/// [`MediaType::new()`], [`MediaType::with_params()`], and -/// [`MediaType::from_extension`()] methods. The preferred method, however, is -/// to create a `MediaType` via an associated constant. +/// indirectly via types like [`Accept`](crate::Accept) and +/// [`ContentType`](crate::ContentType), which internally contain `MediaType`s. +/// Nonetheless, a `MediaType` can be created via the [`MediaType::new()`], +/// [`MediaType::with_params()`], and [`MediaType::from_extension`()] methods. +/// The preferred method, however, is to create a `MediaType` via an associated +/// constant. /// /// ## Example /// @@ -533,7 +534,7 @@ impl Hash for MediaType { impl fmt::Display for MediaType { #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Source::Known(src) = self.source { src.fmt(f) } else { diff --git a/core/http/src/method.rs b/core/http/src/method.rs index 78a1fe6eb6..ce83d67a29 100644 --- a/core/http/src/method.rs +++ b/core/http/src/method.rs @@ -1,7 +1,7 @@ use std::fmt; use std::str::FromStr; -use {hyper, uncased::uncased_eq}; +use crate::{hyper, uncased::uncased_eq}; use self::Method::*; @@ -116,7 +116,7 @@ impl FromStr for Method { impl fmt::Display for Method { #[inline(always)] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.as_str().fmt(f) } } diff --git a/core/http/src/parse/accept.rs b/core/http/src/parse/accept.rs index 2b42ed57fb..aceb84c189 100644 --- a/core/http/src/parse/accept.rs +++ b/core/http/src/parse/accept.rs @@ -1,12 +1,12 @@ use pear::parser; use pear::parsers::*; -use {Accept, QMediaType}; -use parse::checkers::is_whitespace; -use parse::media_type::media_type; +use crate::{Accept, QMediaType}; +use crate::parse::checkers::is_whitespace; +use crate::parse::media_type::media_type; -type Input<'a> = ::parse::IndexedInput<'a, str>; -type Result<'a, T> = ::pear::Result>; +type Input<'a> = crate::parse::IndexedInput<'a, str>; +type Result<'a, T> = pear::Result>; #[parser] fn weighted_media_type<'a>(input: &mut Input<'a>) -> Result<'a, QMediaType> { @@ -29,13 +29,13 @@ fn accept<'a>(input: &mut Input<'a>) -> Result<'a, Accept> { Accept(series(false, ',', is_whitespace, weighted_media_type)?) } -pub fn parse_accept(input: &str) -> Result { +pub fn parse_accept(input: &str) -> Result<'_, Accept> { parse!(accept: &mut input.into()) } #[cfg(test)] mod test { - use MediaType; + use crate::MediaType; use super::parse_accept; macro_rules! assert_parse { diff --git a/core/http/src/parse/checkers.rs b/core/http/src/parse/checkers.rs index 2658552995..ae9d21ed8e 100644 --- a/core/http/src/parse/checkers.rs +++ b/core/http/src/parse/checkers.rs @@ -6,7 +6,7 @@ pub fn is_whitespace(byte: char) -> bool { #[inline] pub fn is_valid_token(c: char) -> bool { match c { - '0'...'9' | 'A'...'Z' | '^'...'~' | '#'...'\'' + '0'..='9' | 'A'..='Z' | '^'..='~' | '#'..='\'' | '!' | '*' | '+' | '-' | '.' => true, _ => false } diff --git a/core/http/src/parse/indexed.rs b/core/http/src/parse/indexed.rs index 7b028f7036..95e0351ee5 100644 --- a/core/http/src/parse/indexed.rs +++ b/core/http/src/parse/indexed.rs @@ -6,7 +6,7 @@ use std::fmt::{self, Debug}; use pear::{Input, Length}; -use ext::IntoOwned; +use crate::ext::IntoOwned; pub type IndexedString = Indexed<'static, str>; pub type IndexedStr<'a> = Indexed<'a, str>; @@ -31,7 +31,7 @@ impl AsPtr for [u8] { } #[derive(PartialEq)] -pub enum Indexed<'a, T: ?Sized + ToOwned + 'a> { +pub enum Indexed<'a, T: ?Sized + ToOwned> { Indexed(usize, usize), Concrete(Cow<'a, T>) } @@ -72,7 +72,7 @@ impl<'a, T: ?Sized + ToOwned + 'a> Indexed<'a, T> { } } -impl<'a, T: 'static + ?Sized + ToOwned> IntoOwned for Indexed<'a, T> { +impl IntoOwned for Indexed<'_, T> { type Owned = Indexed<'static, T>; fn into_owned(self) -> Indexed<'static, T> { @@ -154,7 +154,7 @@ impl<'a, T: ?Sized + ToOwned + 'a> Indexed<'a, T> /// /// Panics if `self` is an indexed string and `string` is None. // pub fn to_source(&self, source: Option<&'a T>) -> &T { - pub fn from_cow_source<'s>(&'s self, source: &'s Option>) -> &'s T { + pub fn from_cow_source<'s>(&'s self, source: &'s Option>) -> &'s T { if self.is_indexed() && source.is_none() { panic!("Cannot convert indexed str to str without base string!") } @@ -196,7 +196,7 @@ impl<'a, T: ToOwned + ?Sized + 'a> Clone for Indexed<'a, T> { impl<'a, T: ?Sized + 'a> Debug for Indexed<'a, T> where T: ToOwned + Debug, T::Owned: Debug { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Indexed::Indexed(a, b) => fmt::Debug::fmt(&(a, b), f), Indexed::Concrete(ref cow) => fmt::Debug::fmt(cow, f), @@ -215,7 +215,7 @@ impl<'a, T: ?Sized + Length + ToOwned + 'a> Length for Indexed<'a, T> { } #[derive(Debug)] -pub struct IndexedInput<'a, T: ?Sized + 'a> { +pub struct IndexedInput<'a, T: ?Sized> { source: &'a T, current: &'a T } @@ -234,8 +234,8 @@ impl<'a, T: ToOwned + ?Sized + 'a> IndexedInput<'a, T> { } } -impl<'a> IndexedInput<'a, [u8]> { - pub fn backtrack(&mut self, n: usize) -> ::pear::Result<(), Self> { +impl IndexedInput<'_, [u8]> { + pub fn backtrack(&mut self, n: usize) -> pear::Result<(), Self> { let source_addr = self.source.as_ptr() as usize; let current_addr = self.current.as_ptr() as usize; if current_addr > n && (current_addr - n) >= source_addr { @@ -323,8 +323,8 @@ pub struct Context { pub string: String } -impl ::std::fmt::Display for Context { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +impl std::fmt::Display for Context { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { const LIMIT: usize = 7; write!(f, "[{}:]", self.offset)?; diff --git a/core/http/src/parse/media_type.rs b/core/http/src/parse/media_type.rs index 35a419ee6c..18a3e5cd1a 100644 --- a/core/http/src/parse/media_type.rs +++ b/core/http/src/parse/media_type.rs @@ -3,12 +3,12 @@ use std::borrow::Cow; use pear::{parser, switch}; use pear::parsers::*; -use media_type::{MediaType, Source}; -use parse::checkers::{is_whitespace, is_valid_token}; -use parse::IndexedStr; +use crate::media_type::{MediaType, Source}; +use crate::parse::checkers::{is_whitespace, is_valid_token}; +use crate::parse::IndexedStr; -type Input<'a> = ::parse::IndexedInput<'a, str>; -type Result<'a, T> = ::pear::Result>; +type Input<'a> = crate::parse::IndexedInput<'a, str>; +type Result<'a, T> = pear::Result>; #[parser] fn quoted_string<'a>(input: &mut Input<'a>) -> Result<'a, IndexedStr<'a>> { @@ -54,13 +54,13 @@ pub fn media_type<'a>(input: &mut Input<'a>) -> Result<'a, MediaType> { } } -pub fn parse_media_type(input: &str) -> Result { +pub fn parse_media_type(input: &str) -> Result<'_, MediaType> { parse!(media_type: &mut input.into()) } #[cfg(test)] mod test { - use MediaType; + use crate::MediaType; use super::parse_media_type; macro_rules! assert_no_parse { diff --git a/core/http/src/parse/uri/error.rs b/core/http/src/parse/uri/error.rs index 083310e859..7ca02b70cd 100644 --- a/core/http/src/parse/uri/error.rs +++ b/core/http/src/parse/uri/error.rs @@ -2,9 +2,9 @@ use std::fmt; use std::borrow::Cow; use pear::{ParseErr, Expected}; -use parse::indexed::Context; -use parse::uri::RawInput; -use ext::IntoOwned; +use crate::parse::indexed::Context; +use crate::parse::uri::RawInput; +use crate::ext::IntoOwned; /// Error emitted on URI parse failure. /// @@ -58,7 +58,7 @@ impl<'a> Error<'a> { } impl fmt::Display for Or { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Or::A(left) => write!(f, "'{}'", left), Or::B(right) => write!(f, "non-ASCII byte {}", right), @@ -66,8 +66,8 @@ impl fmt::Display for Or { } } -impl<'a> fmt::Display for Error<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +impl fmt::Display for Error<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // This relies on specialization of the `Display` impl for `Expected`. write!(f, "{}", self.expected)?; @@ -79,7 +79,7 @@ impl<'a> fmt::Display for Error<'a> { } } -impl<'a> IntoOwned for Error<'a> { +impl IntoOwned for Error<'_> { type Owned = Error<'static>; fn into_owned(self) -> Self::Owned { @@ -90,7 +90,7 @@ impl<'a> IntoOwned for Error<'a> { #[cfg(test)] mod tests { - use parse::uri::origin_from_str; + use crate::parse::uri::origin_from_str; macro_rules! check_err { ($url:expr => $error:expr) => {{ diff --git a/core/http/src/parse/uri/mod.rs b/core/http/src/parse/uri/mod.rs index 66f48c4e88..33f0066143 100644 --- a/core/http/src/parse/uri/mod.rs +++ b/core/http/src/parse/uri/mod.rs @@ -4,8 +4,8 @@ mod tables; #[cfg(test)] mod tests; -use uri::{Uri, Origin, Absolute, Authority}; -use parse::indexed::IndexedInput; +use crate::uri::{Uri, Origin, Absolute, Authority}; +use crate::parse::indexed::IndexedInput; use self::parser::{uri, origin, authority_only, absolute_only, rocket_route_origin}; crate use self::tables::is_pchar; @@ -14,31 +14,31 @@ pub use self::error::Error; type RawInput<'a> = IndexedInput<'a, [u8]>; #[inline] -pub fn from_str(string: &str) -> Result { +pub fn from_str(string: &str) -> Result, Error<'_>> { parse!(uri: &mut RawInput::from(string.as_bytes())) .map_err(|e| Error::from(string, e)) } #[inline] -pub fn origin_from_str(string: &str) -> Result { +pub fn origin_from_str(string: &str) -> Result, Error<'_>> { parse!(origin: &mut RawInput::from(string.as_bytes())) .map_err(|e| Error::from(string, e)) } #[inline] -pub fn route_origin_from_str(string: &str) -> Result { +pub fn route_origin_from_str(string: &str) -> Result, Error<'_>> { parse!(rocket_route_origin: &mut RawInput::from(string.as_bytes())) .map_err(|e| Error::from(string, e)) } #[inline] -pub fn authority_from_str(string: &str) -> Result { +pub fn authority_from_str(string: &str) -> Result, Error<'_>> { parse!(authority_only: &mut RawInput::from(string.as_bytes())) .map_err(|e| Error::from(string, e)) } #[inline] -pub fn absolute_from_str(string: &str) -> Result { +pub fn absolute_from_str(string: &str) -> Result, Error<'_>> { parse!(absolute_only: &mut RawInput::from(string.as_bytes())) .map_err(|e| Error::from(string, e)) } diff --git a/core/http/src/parse/uri/parser.rs b/core/http/src/parse/uri/parser.rs index a55b86df4e..dbcc5d8034 100644 --- a/core/http/src/parse/uri/parser.rs +++ b/core/http/src/parse/uri/parser.rs @@ -1,12 +1,12 @@ use pear::parsers::*; use pear::{parser, switch}; -use uri::{Uri, Origin, Authority, Absolute, Host}; -use parse::uri::tables::{is_reg_name_char, is_pchar, is_pchar_or_rchar}; -use parse::uri::RawInput; -use parse::IndexedBytes; +use crate::uri::{Uri, Origin, Authority, Absolute, Host}; +use crate::parse::uri::tables::{is_reg_name_char, is_pchar, is_pchar_or_rchar}; +use crate::parse::uri::RawInput; +use crate::parse::IndexedBytes; -type Result<'a, T> = ::pear::Result>; +type Result<'a, T> = pear::Result>; #[parser] crate fn uri<'a>(input: &mut RawInput<'a>) -> Result<'a, Uri<'a>> { diff --git a/core/http/src/parse/uri/tests.rs b/core/http/src/parse/uri/tests.rs index 86bd580adb..71b262dc74 100644 --- a/core/http/src/parse/uri/tests.rs +++ b/core/http/src/parse/uri/tests.rs @@ -1,6 +1,6 @@ -use uri::{Uri, Origin, Authority, Absolute}; -use parse::uri::*; -use uri::Host::*; +use crate::uri::{Uri, Origin, Authority, Absolute}; +use crate::parse::uri::*; +use crate::uri::Host::*; macro_rules! assert_parse_eq { ($($from:expr => $to:expr),+) => ( diff --git a/core/http/src/raw_str.rs b/core/http/src/raw_str.rs index ebda863f9d..2fe6f9f50f 100644 --- a/core/http/src/raw_str.rs +++ b/core/http/src/raw_str.rs @@ -5,7 +5,7 @@ use std::cmp::Ordering; use std::str::Utf8Error; use std::fmt; -use uncased::UncasedStr; +use crate::uncased::UncasedStr; /// A reference to a string inside of a raw HTTP message. /// @@ -47,8 +47,8 @@ use uncased::UncasedStr; /// encounter an `&RawStr` as a parameter via [`FromParam`] or as a form value /// via [`FromFormValue`]. /// -/// [`FromParam`]: ::rocket::request::FromParam -/// [`FromFormValue`]: ::rocket::request::FromFormValue +/// [`FromParam`]: rocket::request::FromParam +/// [`FromFormValue`]: rocket::request::FromFormValue #[repr(transparent)] #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct RawStr(str); @@ -98,13 +98,13 @@ impl RawStr { /// use rocket::http::RawStr; /// /// // Note: Rocket should never hand you a bad `&RawStr`. - /// let bad_str = unsafe { ::std::str::from_utf8_unchecked(b"a=\xff") }; + /// let bad_str = unsafe { std::str::from_utf8_unchecked(b"a=\xff") }; /// let bad_raw_str = RawStr::from_str(bad_str); /// assert!(bad_raw_str.percent_decode().is_err()); /// ``` #[inline(always)] - pub fn percent_decode(&self) -> Result, Utf8Error> { - ::percent_encoding::percent_decode(self.as_bytes()).decode_utf8() + pub fn percent_decode(&self) -> Result, Utf8Error> { + percent_encoding::percent_decode(self.as_bytes()).decode_utf8() } /// Returns a percent-decoded version of the string. Any invalid UTF-8 @@ -131,13 +131,13 @@ impl RawStr { /// use rocket::http::RawStr; /// /// // Note: Rocket should never hand you a bad `&RawStr`. - /// let bad_str = unsafe { ::std::str::from_utf8_unchecked(b"a=\xff") }; + /// let bad_str = unsafe { std::str::from_utf8_unchecked(b"a=\xff") }; /// let bad_raw_str = RawStr::from_str(bad_str); /// assert_eq!(bad_raw_str.percent_decode_lossy(), "a=�"); /// ``` #[inline(always)] - pub fn percent_decode_lossy(&self) -> Cow { - ::percent_encoding::percent_decode(self.as_bytes()).decode_utf8_lossy() + pub fn percent_decode_lossy(&self) -> Cow<'_, str> { + percent_encoding::percent_decode(self.as_bytes()).decode_utf8_lossy() } /// Returns a URL-decoded version of the string. This is identical to @@ -193,7 +193,7 @@ impl RawStr { /// use rocket::http::RawStr; /// /// // Note: Rocket should never hand you a bad `&RawStr`. - /// let bad_str = unsafe { ::std::str::from_utf8_unchecked(b"a+b=\xff") }; + /// let bad_str = unsafe { std::str::from_utf8_unchecked(b"a+b=\xff") }; /// let bad_raw_str = RawStr::from_str(bad_str); /// assert_eq!(bad_raw_str.url_decode_lossy(), "a b=�"); /// ``` @@ -245,7 +245,7 @@ impl RawStr { /// let escaped = raw_str.html_escape(); /// assert_eq!(escaped, "大阪"); /// ``` - pub fn html_escape(&self) -> Cow { + pub fn html_escape(&self) -> Cow<'_, str> { let mut escaped = false; let mut allocated = Vec::new(); // this is allocation free for c in self.as_bytes() { @@ -373,7 +373,7 @@ impl PartialEq for RawStr { } } -impl<'a> PartialEq for &'a RawStr { +impl PartialEq for &'_ RawStr { #[inline(always)] fn eq(&self, other: &String) -> bool { self.as_str() == other.as_str() @@ -426,7 +426,7 @@ impl DerefMut for RawStr { impl fmt::Display for RawStr { #[inline(always)] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } diff --git a/core/http/src/route.rs b/core/http/src/route.rs index 843d2c5bb0..b24c55844b 100644 --- a/core/http/src/route.rs +++ b/core/http/src/route.rs @@ -1,10 +1,11 @@ use std::borrow::Cow; use std::marker::PhantomData; + use unicode_xid::UnicodeXID; -use ext::IntoOwned; -use uri::{Origin, UriPart, Path, Query}; -use uri::encoding::unsafe_percent_encode; +use crate::ext::IntoOwned; +use crate::uri::{Origin, UriPart, Path, Query}; +use crate::uri::encoding::unsafe_percent_encode; use self::Error::*; @@ -32,7 +33,7 @@ pub struct RouteSegment<'a, P: UriPart> { _part: PhantomData

, } -impl<'a, P: UriPart + 'static> IntoOwned for RouteSegment<'a, P> { +impl IntoOwned for RouteSegment<'_, P> { type Owned = RouteSegment<'static, P>; #[inline] @@ -86,7 +87,7 @@ fn is_valid_ident(string: &str) -> bool { } impl<'a, P: UriPart> RouteSegment<'a, P> { - pub fn parse_one(segment: &'a str) -> Result { + pub fn parse_one(segment: &'a str) -> Result> { let (string, index) = (segment.into(), None); // Check if this is a dynamic param. If so, check its well-formedness. @@ -129,7 +130,7 @@ impl<'a, P: UriPart> RouteSegment<'a, P> { pub fn parse_many( string: &'a str, - ) -> impl Iterator> { + ) -> impl Iterator> { let mut last_multi_seg: Option<&str> = None; string.split(P::DELIMITER) .filter(|s| !s.is_empty()) @@ -151,13 +152,13 @@ impl<'a, P: UriPart> RouteSegment<'a, P> { } impl<'a> RouteSegment<'a, Path> { - pub fn parse(uri: &'a Origin) -> impl Iterator> { + pub fn parse(uri: &'a Origin<'_>) -> impl Iterator> { Self::parse_many(uri.path()) } } impl<'a> RouteSegment<'a, Query> { - pub fn parse(uri: &'a Origin) -> Option>> { + pub fn parse(uri: &'a Origin<'_>) -> Option>> { uri.query().map(|q| Self::parse_many(q)) } } diff --git a/core/http/src/status.rs b/core/http/src/status.rs index b1a1986224..6e32db4363 100644 --- a/core/http/src/status.rs +++ b/core/http/src/status.rs @@ -273,7 +273,7 @@ impl Status { impl fmt::Display for Status { #[inline(always)] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} {}", self.code, self.reason) } } diff --git a/core/http/src/tls.rs b/core/http/src/tls.rs index 63931ca3d0..b0311be862 100644 --- a/core/http/src/tls.rs +++ b/core/http/src/tls.rs @@ -1,5 +1,2 @@ -extern crate rustls; -extern crate hyper_sync_rustls; - -pub use self::hyper_sync_rustls::{util, WrappedStream, ServerSession, TlsServer}; -pub use self::rustls::{Certificate, PrivateKey}; +pub use hyper_sync_rustls::{util, WrappedStream, ServerSession, TlsServer}; +pub use rustls::{Certificate, PrivateKey}; diff --git a/core/http/src/uncased.rs b/core/http/src/uncased.rs index b81a7b1302..ee9d7ac26d 100644 --- a/core/http/src/uncased.rs +++ b/core/http/src/uncased.rs @@ -107,14 +107,14 @@ impl PartialEq for str { } } -impl<'a> PartialEq<&'a str> for UncasedStr { +impl PartialEq<&str> for UncasedStr { #[inline(always)] - fn eq(&self, other: & &'a str) -> bool { + fn eq(&self, other: &&str) -> bool { self.0.eq_ignore_ascii_case(other) } } -impl<'a> PartialEq for &'a str { +impl PartialEq for &str { #[inline(always)] fn eq(&self, other: &UncasedStr) -> bool { other.0.eq_ignore_ascii_case(self) @@ -156,7 +156,7 @@ impl Ord for UncasedStr { impl fmt::Display for UncasedStr { #[inline(always)] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } @@ -233,7 +233,7 @@ impl<'s> Uncased<'s> { } } -impl<'a> Deref for Uncased<'a> { +impl Deref for Uncased<'_> { type Target = UncasedStr; #[inline(always)] @@ -242,14 +242,14 @@ impl<'a> Deref for Uncased<'a> { } } -impl<'a> AsRef for Uncased<'a>{ +impl AsRef for Uncased<'_>{ #[inline(always)] fn as_ref(&self) -> &UncasedStr { UncasedStr::new(self.string.borrow()) } } -impl<'a> Borrow for Uncased<'a> { +impl Borrow for Uncased<'_> { #[inline(always)] fn borrow(&self) -> &UncasedStr { self.as_str().into() @@ -284,64 +284,64 @@ impl<'s, 'c: 's, T: Into>> From for Uncased<'s> { } } -impl<'a, 'b> PartialOrd> for Uncased<'a> { +impl<'b> PartialOrd> for Uncased<'_> { #[inline(always)] fn partial_cmp(&self, other: &Uncased<'b>) -> Option { self.as_ref().partial_cmp(other.as_ref()) } } -impl<'a> Ord for Uncased<'a> { +impl Ord for Uncased<'_> { fn cmp(&self, other: &Self) -> Ordering { self.as_ref().cmp(other.as_ref()) } } -impl<'s> fmt::Display for Uncased<'s> { +impl fmt::Display for Uncased<'_> { #[inline(always)] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.string.fmt(f) } } -impl<'a, 'b> PartialEq> for Uncased<'a> { +impl<'b> PartialEq> for Uncased<'_> { #[inline(always)] fn eq(&self, other: &Uncased<'b>) -> bool { self.as_ref().eq(other.as_ref()) } } -impl<'a> PartialEq for Uncased<'a> { +impl PartialEq for Uncased<'_> { #[inline(always)] fn eq(&self, other: &str) -> bool { self.as_ref().eq(other) } } -impl<'b> PartialEq> for str { +impl PartialEq> for str { #[inline(always)] - fn eq(&self, other: &Uncased<'b>) -> bool { + fn eq(&self, other: &Uncased<'_>) -> bool { other.as_ref().eq(self) } } -impl<'a, 'b> PartialEq<&'b str> for Uncased<'a> { +impl<'b> PartialEq<&'b str> for Uncased<'_> { #[inline(always)] fn eq(&self, other: & &'b str) -> bool { self.as_ref().eq(other) } } -impl<'a, 'b> PartialEq> for &'a str { +impl<'b> PartialEq> for &str { #[inline(always)] fn eq(&self, other: &Uncased<'b>) -> bool { other.as_ref().eq(self) } } -impl<'s> Eq for Uncased<'s> { } +impl Eq for Uncased<'_> { } -impl<'s> Hash for Uncased<'s> { +impl Hash for Uncased<'_> { #[inline(always)] fn hash(&self, hasher: &mut H) { self.as_ref().hash(hasher) diff --git a/core/http/src/uri/absolute.rs b/core/http/src/uri/absolute.rs index 73770c64fe..b059a280c7 100644 --- a/core/http/src/uri/absolute.rs +++ b/core/http/src/uri/absolute.rs @@ -1,9 +1,9 @@ use std::borrow::Cow; use std::fmt::{self, Display}; -use ext::IntoOwned; -use parse::{Indexed, IndexedStr}; -use uri::{Authority, Origin, Error, as_utf8_unchecked}; +use crate::ext::IntoOwned; +use crate::parse::{Indexed, IndexedStr}; +use crate::uri::{Authority, Origin, Error, as_utf8_unchecked}; /// A URI with a scheme, authority, path, and query: /// `http://user:pass@domain.com:4444/path?query`. @@ -29,7 +29,7 @@ pub struct Absolute<'a> { origin: Option>, } -impl<'a> IntoOwned for Absolute<'a> { +impl IntoOwned for Absolute<'_> { type Owned = Absolute<'static>; fn into_owned(self) -> Self::Owned { @@ -85,7 +85,7 @@ impl<'a> Absolute<'a> { /// assert_eq!(uri.origin(), None); /// ``` pub fn parse(string: &'a str) -> Result, Error<'a>> { - ::parse::uri::absolute_from_str(string) + crate::parse::uri::absolute_from_str(string) } /// Returns the scheme part of the absolute URI. @@ -149,7 +149,7 @@ impl<'a> Absolute<'a> { } } -impl<'a, 'b> PartialEq> for Absolute<'a> { +impl<'b> PartialEq> for Absolute<'_> { fn eq(&self, other: &Absolute<'b>) -> bool { self.scheme() == other.scheme() && self.authority() == other.authority() @@ -157,8 +157,8 @@ impl<'a, 'b> PartialEq> for Absolute<'a> { } } -impl<'a> Display for Absolute<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +impl Display for Absolute<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.scheme())?; match self.authority { Some(ref authority) => write!(f, "://{}", authority)?, diff --git a/core/http/src/uri/authority.rs b/core/http/src/uri/authority.rs index c95b5ad306..7bdcc8dd6a 100644 --- a/core/http/src/uri/authority.rs +++ b/core/http/src/uri/authority.rs @@ -1,9 +1,9 @@ use std::fmt::{self, Display}; use std::borrow::Cow; -use ext::IntoOwned; -use parse::{Indexed, IndexedStr}; -use uri::{as_utf8_unchecked, Error}; +use crate::ext::IntoOwned; +use crate::parse::{Indexed, IndexedStr}; +use crate::uri::{as_utf8_unchecked, Error}; /// A URI with an authority only: `user:pass@host:8000`. /// @@ -41,7 +41,7 @@ impl IntoOwned for Host { } } -impl<'a> IntoOwned for Authority<'a> { +impl IntoOwned for Authority<'_> { type Owned = Authority<'static>; fn into_owned(self) -> Authority<'static> { @@ -102,7 +102,7 @@ impl<'a> Authority<'a> { /// Authority::parse("http://google.com").expect_err("invalid authority"); /// ``` pub fn parse(string: &'a str) -> Result, Error<'a>> { - ::parse::uri::authority_from_str(string) + crate::parse::uri::authority_from_str(string) } /// Returns the user info part of the authority URI, if there is one. @@ -171,7 +171,7 @@ impl<'a> Authority<'a> { } } -impl<'a, 'b> PartialEq> for Authority<'a> { +impl<'b> PartialEq> for Authority<'_> { fn eq(&self, other: &Authority<'b>) -> bool { self.user_info() == other.user_info() && self.host() == other.host() @@ -180,8 +180,8 @@ impl<'a, 'b> PartialEq> for Authority<'a> { } } -impl<'a> Display for Authority<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +impl Display for Authority<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(user_info) = self.user_info() { write!(f, "{}@", user_info)?; } diff --git a/core/http/src/uri/encoding.rs b/core/http/src/uri/encoding.rs index 74422c51ea..c08d96cf06 100644 --- a/core/http/src/uri/encoding.rs +++ b/core/http/src/uri/encoding.rs @@ -3,8 +3,8 @@ use std::borrow::Cow; use percent_encoding::{EncodeSet, utf8_percent_encode}; -use uri::{UriPart, Path, Query}; -use parse::uri::is_pchar; +use crate::uri::{UriPart, Path, Query}; +use crate::parse::uri::is_pchar; #[derive(Clone, Copy)] #[allow(non_camel_case_types)] @@ -62,7 +62,7 @@ impl EncodeSet for DEFAULT_ENCODE_SET { } } -crate fn unsafe_percent_encode(string: &str) -> Cow { +crate fn unsafe_percent_encode(string: &str) -> Cow<'_, str> { match P::DELIMITER { '/' => percent_encode::>(string), '&' => percent_encode::>(string), @@ -70,6 +70,6 @@ crate fn unsafe_percent_encode(string: &str) -> Cow { } } -crate fn percent_encode(string: &str) -> Cow { +crate fn percent_encode(string: &str) -> Cow<'_, str> { utf8_percent_encode(string, S::default()).into() } diff --git a/core/http/src/uri/formatter.rs b/core/http/src/uri/formatter.rs index 47ea195139..bdf4244e46 100644 --- a/core/http/src/uri/formatter.rs +++ b/core/http/src/uri/formatter.rs @@ -3,7 +3,7 @@ use std::marker::PhantomData; use smallvec::SmallVec; -use uri::{UriPart, Path, Query, UriDisplay, Origin}; +use crate::uri::{UriPart, Path, Query, UriDisplay, Origin}; /// A struct used to format strings for [`UriDisplay`]. /// @@ -16,9 +16,9 @@ use uri::{UriPart, Path, Query, UriDisplay, Origin}; /// formatting parameters in the query part of the URI. The /// [`write_named_value()`] method is only available to `UriDisplay`. /// -/// [`UriPart`]: uri::UriPart -/// [`Path`]: uri::Path -/// [`Query`]: uri::Query +/// [`UriPart`]: crate::uri::UriPart +/// [`Path`]: crate::uri::Path +/// [`Query`]: crate::uri::Query /// /// # Overview /// @@ -39,9 +39,9 @@ use uri::{UriPart, Path, Query, UriDisplay, Origin}; /// calls `write_named_vlaue()`, the nested names are joined by a `.`, /// written out followed by a `=`, followed by the value. /// -/// [`UriDisplay`]: uri::UriDisplay -/// [`UriDisplay::fmt()`]: uri::UriDisplay::fmt() -/// [`write_named_value()`]: uri::Formatter::write_named_value() +/// [`UriDisplay`]: crate::uri::UriDisplay +/// [`UriDisplay::fmt()`]: crate::uri::UriDisplay::fmt() +/// [`write_named_value()`]: crate::uri::Formatter::write_named_value() /// /// # Usage /// @@ -59,7 +59,7 @@ use uri::{UriPart, Path, Query, UriDisplay, Origin}; /// called, after a call to `write_named_value` or `write_value`, or after a /// call to [`refresh()`]. /// -/// [`refresh()`]: uri::Formatter::refresh() +/// [`refresh()`]: crate::uri::Formatter::refresh() /// /// # Example /// @@ -146,8 +146,8 @@ use uri::{UriPart, Path, Query, UriDisplay, Origin}; /// assert_eq!(uri_string, "number=42+47"); /// ``` /// -/// [`write_value()`]: uri::Formatter::write_value() -/// [`write_raw()`]: uri::Formatter::write_raw() +/// [`write_value()`]: crate::uri::Formatter::write_value() +/// [`write_raw()`]: crate::uri::Formatter::write_raw() pub struct Formatter<'i, P: UriPart> { prefixes: SmallVec<[&'static str; 3]>, inner: &'i mut (dyn Write + 'i), @@ -330,7 +330,7 @@ impl<'i, P: UriPart> Formatter<'i, P> { } } -impl<'i> Formatter<'i, Query> { +impl Formatter<'_, Query> { fn with_prefix(&mut self, prefix: &str, f: F) -> fmt::Result where F: FnOnce(&mut Self) -> fmt::Result { @@ -347,7 +347,7 @@ impl<'i> Formatter<'i, Query> { // // Said succinctly: this `prefixes` stack shadows a subset of the // `with_prefix` stack precisely, making it reachable to other code. - let prefix: &'static str = unsafe { ::std::mem::transmute(prefix) }; + let prefix: &'static str = unsafe { std::mem::transmute(prefix) }; self.prefixes.push(prefix); let result = f(self); @@ -392,7 +392,7 @@ impl<'i> Formatter<'i, Query> { } } -impl<'i, P: UriPart> fmt::Write for Formatter<'i, P> { +impl fmt::Write for Formatter<'_, P> { fn write_str(&mut self, s: &str) -> fmt::Result { self.write_raw(s) } @@ -421,7 +421,7 @@ pub struct UriArguments<'a> { } // Used by code generation. -impl<'a> UriArguments<'a> { +impl UriArguments<'_> { #[doc(hidden)] pub fn into_origin(self) -> Origin<'static> { use std::borrow::Cow; diff --git a/core/http/src/uri/from_uri_param.rs b/core/http/src/uri/from_uri_param.rs index 4586a60415..2d1d3d51d7 100644 --- a/core/http/src/uri/from_uri_param.rs +++ b/core/http/src/uri/from_uri_param.rs @@ -1,7 +1,7 @@ use std::path::{Path, PathBuf}; -use RawStr; -use uri::{self, UriPart, UriDisplay}; +use crate::RawStr; +use crate::uri::{self, UriPart, UriDisplay}; /// Conversion trait for parameters used in [`uri!`] invocations. /// @@ -136,7 +136,7 @@ use uri::{self, UriPart, UriDisplay}; /// nickname: String, /// } /// -/// impl<'a> UriDisplay for User<'a> { +/// impl UriDisplay for User<'_> { /// fn fmt(&self, f: &mut Formatter) -> fmt::Result { /// f.write_named_value("name", &self.name)?; /// f.write_named_value("nickname", &self.nickname) @@ -165,7 +165,7 @@ use uri::{self, UriPart, UriDisplay}; /// # #[derive(FromForm)] /// # struct User<'a> { name: &'a RawStr, nickname: String, } /// # -/// # impl<'a> UriDisplay for User<'a> { +/// # impl UriDisplay for User<'_> { /// # fn fmt(&self, f: &mut Formatter) -> fmt::Result { /// # f.write_named_value("name", &self.name)?; /// # f.write_named_value("nickname", &self.nickname) @@ -187,17 +187,17 @@ use uri::{self, UriPart, UriDisplay}; /// assert_eq!(uri.query(), Some("name=Robert%20Mike&nickname=Bob")); /// ``` /// -/// [`uri!`]: ::rocket_codegen::uri -/// [`UriDisplay`]: uri::UriDisplay -/// [`FromUriParam::Target`]: uri::FromUriParam::Target -/// [`Path`]: uri::Path +/// [`uri!`]: rocket_codegen::uri +/// [`UriDisplay`]: crate::uri::UriDisplay +/// [`FromUriParam::Target`]: crate::uri::FromUriParam::Target +/// [`Path`]: crate::uri::Path pub trait FromUriParam { /// The resulting type of this conversion. type Target: UriDisplay

; /// Converts a value of type `T` into a value of type `Self::Target`. The /// resulting value of type `Self::Target` will be rendered into a URI using - /// its [`UriDisplay`](uri::UriDisplay) implementation. + /// its [`UriDisplay`](crate::uri::UriDisplay) implementation. fn from_uri_param(param: T) -> Self::Target; } @@ -277,9 +277,9 @@ macro_rules! impl_conversion_ref { /// * Example: `impl_from_uri_param_identity!([Path] ('a) MyType<'a>);` /// * Generates: `impl<'a> FromUriParam for MyType<'a> { ... }` /// -/// [`FromUriParam`]: uri::FromUriParam -/// [`Path`]: uri::Path -/// [`Query`]: uri::Query +/// [`FromUriParam`]: crate::uri::FromUriParam +/// [`Path`]: crate::uri::Path +/// [`Query`]: crate::uri::Query #[macro_export(local_inner_macros)] macro_rules! impl_from_uri_param_identity { ($(($($l:tt)*) $T:ty),*) => ($( impl_conversion_ref!(($($l)*) $T => $T); )*); diff --git a/core/http/src/uri/mod.rs b/core/http/src/uri/mod.rs index 89c8105087..029317994a 100644 --- a/core/http/src/uri/mod.rs +++ b/core/http/src/uri/mod.rs @@ -11,7 +11,7 @@ mod segments; crate mod encoding; -pub use parse::uri::Error; +pub use crate::parse::uri::Error; pub use self::uri::*; pub use self::authority::*; @@ -48,10 +48,10 @@ mod private { /// approach enables succinct, type-checked generic implementations of these /// items. /// -/// [`Query`]: uri::Query -/// [`Path`]: uri::Path -/// [`UriDisplay`]: uri::UriDisplay -/// [`Formatter`]: uri::Formatter +/// [`Query`]: crate::uri::Query +/// [`Path`]: crate::uri::Path +/// [`UriDisplay`]: crate::uri::UriDisplay +/// [`Formatter`]: crate::uri::Formatter pub trait UriPart: private::Sealed { const DELIMITER: char; } @@ -66,7 +66,7 @@ pub trait UriPart: private::Sealed { /// ^------------------ Path /// ``` /// -/// [`UriPart`]: uri::UriPart +/// [`UriPart`]: crate::uri::UriPart #[derive(Debug, Clone, Copy)] pub enum Path { } @@ -79,7 +79,7 @@ pub enum Path { } /// ^-------------- Query /// ``` /// -/// [`UriPart`]: uri::UriPart +/// [`UriPart`]: crate::uri::UriPart #[derive(Debug, Clone, Copy)] pub enum Query { } diff --git a/core/http/src/uri/origin.rs b/core/http/src/uri/origin.rs index 51254d154a..688151a5f0 100644 --- a/core/http/src/uri/origin.rs +++ b/core/http/src/uri/origin.rs @@ -1,9 +1,9 @@ use std::fmt::{self, Display}; use std::borrow::Cow; -use ext::IntoOwned; -use parse::{Indexed, IndexedStr}; -use uri::{as_utf8_unchecked, Error, Segments}; +use crate::ext::IntoOwned; +use crate::parse::{Indexed, IndexedStr}; +use crate::uri::{as_utf8_unchecked, Error, Segments}; use state::Storage; @@ -63,7 +63,7 @@ use state::Storage; /// # } /// ``` /// -/// The [`Origin::to_normalized()`](uri::Origin::to_normalized()) method can be +/// The [`Origin::to_normalized()`](crate::uri::Origin::to_normalized()) method can be /// used to normalize any `Origin`: /// /// ```rust @@ -91,13 +91,13 @@ pub struct Origin<'a> { crate segment_count: Storage, } -impl<'a, 'b> PartialEq> for Origin<'a> { +impl<'b> PartialEq> for Origin<'_> { fn eq(&self, other: &Origin<'b>) -> bool { self.path() == other.path() && self.query() == other.query() } } -impl<'a> IntoOwned for Origin<'a> { +impl IntoOwned for Origin<'_> { type Owned = Origin<'static>; fn into_owned(self) -> Origin<'static> { @@ -166,7 +166,7 @@ impl<'a> Origin<'a> { /// Origin::parse("foo bar").expect_err("invalid URI"); /// ``` pub fn parse(string: &'a str) -> Result, Error<'a>> { - ::parse::uri::origin_from_str(string) + crate::parse::uri::origin_from_str(string) } // Parses an `Origin` that may contain `<` or `>` characters which are @@ -174,12 +174,12 @@ impl<'a> Origin<'a> { // this outside of Rocket! #[doc(hidden)] pub fn parse_route(string: &'a str) -> Result, Error<'a>> { - ::parse::uri::route_origin_from_str(string) + crate::parse::uri::route_origin_from_str(string) } /// Parses the string `string` into an `Origin`. Parsing will never /// allocate. This method should be used instead of - /// [`Origin::parse()`](uri::Origin::parse()) when the source URI is already + /// [`Origin::parse()`](crate::uri::Origin::parse()) when the source URI is already /// a `String`. Returns an `Error` if `string` is not a valid origin URI. /// /// # Example @@ -270,7 +270,7 @@ impl<'a> Origin<'a> { /// assert!(normalized.is_normalized()); /// assert_eq!(normalized, Origin::parse("/a/b/c/d").unwrap()); /// ``` - pub fn to_normalized(&self) -> Origin { + pub fn to_normalized(&self) -> Origin<'_> { if self.is_normalized() { Origin::new(self.path(), self.query()) } else { @@ -403,7 +403,7 @@ impl<'a> Origin<'a> { /// } /// ``` #[inline(always)] - pub fn segments(&self) -> Segments { + pub fn segments(&self) -> Segments<'_> { Segments(self.path()) } @@ -440,8 +440,8 @@ impl<'a> Origin<'a> { } } -impl<'a> Display for Origin<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +impl Display for Origin<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.path())?; if let Some(q) = self.query() { write!(f, "?{}", q)?; @@ -482,7 +482,7 @@ mod tests { #[test] fn send_and_sync() { fn assert() {}; - assert::(); + assert::>(); } #[test] diff --git a/core/http/src/uri/segments.rs b/core/http/src/uri/segments.rs index 05919392e0..5d91f7abe1 100644 --- a/core/http/src/uri/segments.rs +++ b/core/http/src/uri/segments.rs @@ -1,7 +1,7 @@ use std::path::PathBuf; use std::str::Utf8Error; -use uri::Uri; +use crate::uri::Uri; /// Iterator over the segments of an absolute URI path. Skips empty segments. /// @@ -40,7 +40,7 @@ pub enum SegmentError { BadEnd(char), } -impl<'a> Segments<'a> { +impl Segments<'_> { /// Creates a `PathBuf` from a `Segments` iterator. The returned `PathBuf` /// is percent-decoded. If a segment is equal to "..", the previous segment /// (if any) is skipped. diff --git a/core/http/src/uri/uri.rs b/core/http/src/uri/uri.rs index 190818e257..bb61177ef7 100644 --- a/core/http/src/uri/uri.rs +++ b/core/http/src/uri/uri.rs @@ -4,10 +4,10 @@ use std::borrow::Cow; use std::str::Utf8Error; use std::convert::TryFrom; -use ext::IntoOwned; -use parse::Indexed; -use uri::{Origin, Authority, Absolute, Error}; -use uri::encoding::{percent_encode, DEFAULT_ENCODE_SET}; +use crate::ext::IntoOwned; +use crate::parse::Indexed; +use crate::uri::{Origin, Authority, Absolute, Error}; +use crate::uri::encoding::{percent_encode, DEFAULT_ENCODE_SET}; /// An `enum` encapsulating any of the possible URI variants. /// @@ -19,7 +19,7 @@ use uri::encoding::{percent_encode, DEFAULT_ENCODE_SET}; /// /// Nevertheless, the `Uri` type is typically enountered as a conversion target. /// In particular, you will likely see generic bounds of the form: `T: -/// TryInto` (for instance, in [`Redirect`](::rocket::response::Redirect) +/// TryInto` (for instance, in [`Redirect`](rocket::response::Redirect) /// methods). This means that you can provide any type `T` that implements /// `TryInto`, or, equivalently, any type `U` for which `Uri` implements /// `TryFrom` or `From`. These include `&str` and `String`, [`Origin`], @@ -41,13 +41,13 @@ use uri::encoding::{percent_encode, DEFAULT_ENCODE_SET}; /// methods: [`Uri::percent_encode()`], [`Uri::percent_decode()`], and /// [`Uri::percent_decode_lossy()`]. /// -/// [`Origin`]: uri::Origin -/// [`Authority`]: uri::Authority -/// [`Absolute`]: uri::Absolute -/// [`Uri::parse()`]: uri::Uri::parse() -/// [`Uri::percent_encode()`]: uri::Uri::percent_encode() -/// [`Uri::percent_decode()`]: uri::Uri::percent_decode() -/// [`Uri::percent_decode_lossy()`]: uri::Uri::percent_decode_lossy() +/// [`Origin`]: crate::uri::Origin +/// [`Authority`]: crate::uri::Authority +/// [`Absolute`]: crate::uri::Absolute +/// [`Uri::parse()`]: crate::uri::Uri::parse() +/// [`Uri::percent_encode()`]: crate::uri::Uri::percent_encode() +/// [`Uri::percent_decode()`]: crate::uri::Uri::percent_decode() +/// [`Uri::percent_decode_lossy()`]: crate::uri::Uri::percent_decode_lossy() #[derive(Debug, PartialEq, Clone)] pub enum Uri<'a> { /// An origin URI. @@ -90,8 +90,8 @@ impl<'a> Uri<'a> { /// // Invalid URIs fail to parse. /// Uri::parse("foo bar").expect_err("invalid URI"); /// ``` - pub fn parse(string: &'a str) -> Result, Error> { - ::parse::uri::from_str(string) + pub fn parse(string: &'a str) -> Result, Error<'_>> { + crate::parse::uri::from_str(string) } /// Returns the internal instance of `Origin` if `self` is a `Uri::Origin`. @@ -172,7 +172,7 @@ impl<'a> Uri<'a> { /// let encoded = Uri::percent_encode("hello?a=hi"); /// assert_eq!(encoded, "hello%3Fa%3D%3Cb%3Ehi%3C%2Fb%3E"); /// ``` - pub fn percent_encode(string: &str) -> Cow { + pub fn percent_encode(string: &str) -> Cow<'_, str> { percent_encode::(string) } @@ -188,8 +188,8 @@ impl<'a> Uri<'a> { /// let decoded = Uri::percent_decode("/Hello%2C%20world%21".as_bytes()); /// assert_eq!(decoded.unwrap(), "/Hello, world!"); /// ``` - pub fn percent_decode(string: &[u8]) -> Result, Utf8Error> { - let decoder = ::percent_encoding::percent_decode(string); + pub fn percent_decode(string: &[u8]) -> Result, Utf8Error> { + let decoder = percent_encoding::percent_decode(string); decoder.decode_utf8() } @@ -206,15 +206,15 @@ impl<'a> Uri<'a> { /// let decoded = Uri::percent_decode_lossy("/Hello%2C%20world%21".as_bytes()); /// assert_eq!(decoded, "/Hello, world!"); /// ``` - pub fn percent_decode_lossy(string: &[u8]) -> Cow { - let decoder = ::percent_encoding::percent_decode(string); + pub fn percent_decode_lossy(string: &[u8]) -> Cow<'_, str> { + let decoder = percent_encoding::percent_decode(string); decoder.decode_utf8_lossy() } } -crate unsafe fn as_utf8_unchecked(input: Cow<[u8]>) -> Cow { +crate unsafe fn as_utf8_unchecked(input: Cow<'_, [u8]>) -> Cow<'_, str> { match input { - Cow::Borrowed(bytes) => Cow::Borrowed(::std::str::from_utf8_unchecked(bytes)), + Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8_unchecked(bytes)), Cow::Owned(bytes) => Cow::Owned(String::from_utf8_unchecked(bytes)) } } @@ -240,7 +240,7 @@ impl TryFrom for Uri<'static> { } } -impl<'a> IntoOwned for Uri<'a> { +impl IntoOwned for Uri<'_> { type Owned = Uri<'static>; fn into_owned(self) -> Uri<'static> { @@ -253,8 +253,8 @@ impl<'a> IntoOwned for Uri<'a> { } } -impl<'a> Display for Uri<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +impl Display for Uri<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Uri::Origin(ref origin) => write!(f, "{}", origin), Uri::Authority(ref authority) => write!(f, "{}", authority), diff --git a/core/http/src/uri/uri_display.rs b/core/http/src/uri/uri_display.rs index fb81939f04..408d75e7d7 100644 --- a/core/http/src/uri/uri_display.rs +++ b/core/http/src/uri/uri_display.rs @@ -1,8 +1,8 @@ use std::{fmt, path}; use std::borrow::Cow; -use RawStr; -use uri::{Uri, UriPart, Path, Query, Formatter}; +use crate::RawStr; +use crate::uri::{Uri, UriPart, Path, Query, Formatter}; /// Trait implemented by types that can be displayed as part of a URI in /// [`uri!`]. @@ -44,9 +44,9 @@ use uri::{Uri, UriPart, Path, Query, Formatter}; /// # { fn fmt(&self, f: &mut Formatter

) -> fmt::Result { Ok(()) } } /// ``` /// -/// [`UriPart`]: uri::UriPart -/// [`Path`]: uri::Path -/// [`Query`]: uri::Query +/// [`UriPart`]: crate::uri::UriPart +/// [`Path`]: crate::uri::Path +/// [`Query`]: crate::uri::Query /// /// # Code Generation /// @@ -168,7 +168,7 @@ use uri::{Uri, UriPart, Path, Query, Formatter}; /// If the `Result` is `Ok`, uses the implementation of `UriDisplay` for /// `T`. Otherwise, nothing is rendered. /// -/// [`FromUriParam`]: uri::FromUriParam +/// [`FromUriParam`]: crate::uri::FromUriParam /// /// # Deriving /// @@ -204,15 +204,15 @@ use uri::{Uri, UriPart, Path, Query, Formatter}; /// [`Formatter::write_value()`] for every unnamed field. See the [`UriDisplay` /// derive] documentation for full details. /// -/// [`Ignorable`]: uri::Ignorable +/// [`Ignorable`]: crate::uri::Ignorable /// [`UriDisplay` derive]: ../../../rocket_codegen/derive.UriDisplay.html -/// [`Formatter::write_named_value()`]: uri::Formatter::write_named_value() -/// [`Formatter::write_value()`]: uri::Formatter::write_value() +/// [`Formatter::write_named_value()`]: crate::uri::Formatter::write_named_value() +/// [`Formatter::write_value()`]: crate::uri::Formatter::write_value() /// /// # Implementing /// /// Implementing `UriDisplay` is similar to implementing -/// [`Display`](::std::fmt::Display) with the caveat that extra care must be +/// [`Display`](std::fmt::Display) with the caveat that extra care must be /// taken to ensure that the written string is URI-safe. As mentioned before, in /// practice, this means that the string must either be percent-encoded or /// consist only of characters that are alphanumeric, "-", ".", "_", or "~". @@ -221,7 +221,7 @@ use uri::{Uri, UriPart, Path, Query, Formatter}; /// existing implementations of `UriDisplay` as much as possible. In the example /// below, for instance, `Name`'s implementation defers to `String`'s /// implementation. To percent-encode a string, use -/// [`Uri::percent_encode()`](uri::Uri::percent_encode()). +/// [`Uri::percent_encode()`](crate::uri::Uri::percent_encode()). /// /// ## Example /// @@ -291,13 +291,13 @@ use uri::{Uri, UriPart, Path, Query, Formatter}; /// ``` pub trait UriDisplay { /// Formats `self` in a URI-safe manner using the given formatter. - fn fmt(&self, f: &mut Formatter

) -> fmt::Result; + fn fmt(&self, f: &mut Formatter<'_, P>) -> fmt::Result; } -impl<'a, P: UriPart> fmt::Display for &'a UriDisplay

{ +impl fmt::Display for &dyn UriDisplay

{ #[inline(always)] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - UriDisplay::fmt(*self, &mut >::new(f)) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + UriDisplay::fmt(*self, &mut >::new(f)) } } @@ -306,14 +306,14 @@ impl<'a, P: UriPart> fmt::Display for &'a UriDisplay

{ /// Percent-encodes the raw string. impl UriDisplay

for str { #[inline(always)] - fn fmt(&self, f: &mut Formatter

) -> fmt::Result { + fn fmt(&self, f: &mut Formatter<'_, P>) -> fmt::Result { f.write_raw(&Uri::percent_encode(self)) } } /// Percent-encodes each segment in the path and normalizes separators. impl UriDisplay for path::Path { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { + fn fmt(&self, f: &mut Formatter<'_, Path>) -> fmt::Result { use std::path::Component; for component in self.components() { @@ -332,7 +332,7 @@ macro_rules! impl_with_display { /// This implementation is identical to the `Display` implementation. impl UriDisplay

for $T { #[inline(always)] - fn fmt(&self, f: &mut Formatter

) -> fmt::Result { + fn fmt(&self, f: &mut Formatter<'_, P>) -> fmt::Result { use std::fmt::Write; write!(f, "{}", self) } @@ -355,7 +355,7 @@ impl_with_display! { /// Percent-encodes the raw string. Defers to `str`. impl UriDisplay

for RawStr { #[inline(always)] - fn fmt(&self, f: &mut Formatter

) -> fmt::Result { + fn fmt(&self, f: &mut Formatter<'_, P>) -> fmt::Result { self.as_str().fmt(f) } } @@ -363,15 +363,15 @@ impl UriDisplay

for RawStr { /// Percent-encodes the raw string. Defers to `str`. impl UriDisplay

for String { #[inline(always)] - fn fmt(&self, f: &mut Formatter

) -> fmt::Result { + fn fmt(&self, f: &mut Formatter<'_, P>) -> fmt::Result { self.as_str().fmt(f) } } /// Percent-encodes the raw string. Defers to `str`. -impl<'a, P: UriPart> UriDisplay

for Cow<'a, str> { +impl UriDisplay

for Cow<'_, str> { #[inline(always)] - fn fmt(&self, f: &mut Formatter

) -> fmt::Result { + fn fmt(&self, f: &mut Formatter<'_, P>) -> fmt::Result { self.as_ref().fmt(f) } } @@ -379,23 +379,23 @@ impl<'a, P: UriPart> UriDisplay

for Cow<'a, str> { /// Percent-encodes each segment in the path and normalizes separators. impl UriDisplay for path::PathBuf { #[inline(always)] - fn fmt(&self, f: &mut Formatter) -> fmt::Result { + fn fmt(&self, f: &mut Formatter<'_, Path>) -> fmt::Result { self.as_path().fmt(f) } } /// Defers to the `UriDisplay

` implementation for `T`. -impl<'a, P: UriPart, T: UriDisplay

+ ?Sized> UriDisplay

for &'a T { +impl + ?Sized> UriDisplay

for &T { #[inline(always)] - fn fmt(&self, f: &mut Formatter

) -> fmt::Result { + fn fmt(&self, f: &mut Formatter<'_, P>) -> fmt::Result { UriDisplay::fmt(*self, f) } } /// Defers to the `UriDisplay

` implementation for `T`. -impl<'a, P: UriPart, T: UriDisplay

+ ?Sized> UriDisplay

for &'a mut T { +impl + ?Sized> UriDisplay

for &mut T { #[inline(always)] - fn fmt(&self, f: &mut Formatter

) -> fmt::Result { + fn fmt(&self, f: &mut Formatter<'_, P>) -> fmt::Result { UriDisplay::fmt(*self, f) } } @@ -403,7 +403,7 @@ impl<'a, P: UriPart, T: UriDisplay

+ ?Sized> UriDisplay

for &'a mut T { /// Defers to the `UriDisplay` implementation for `T`. impl> UriDisplay for Option { #[inline(always)] - fn fmt(&self, f: &mut Formatter) -> fmt::Result { + fn fmt(&self, f: &mut Formatter<'_, Query>) -> fmt::Result { match self { Some(v) => v.fmt(f), None => Ok(()) @@ -414,7 +414,7 @@ impl> UriDisplay for Option { /// Defers to the `UriDisplay` implementation for `T`. impl, E> UriDisplay for Result { #[inline(always)] - fn fmt(&self, f: &mut Formatter) -> fmt::Result { + fn fmt(&self, f: &mut Formatter<'_, Query>) -> fmt::Result { match self { Ok(v) => v.fmt(f), Err(_) => Ok(()) @@ -469,7 +469,7 @@ pub fn assert_ignorable>() { } #[cfg(test)] mod uri_display_tests { use std::path; - use uri::{FromUriParam, UriDisplay, Query, Path}; + use crate::uri::{FromUriParam, UriDisplay, Query, Path}; macro_rules! uri_display { (<$P:ident, $Target:ty> $source:expr) => ({ @@ -577,7 +577,7 @@ mod uri_display_tests { #[test] fn check_ignorables() { - use uri::assert_ignorable; + use crate::uri::assert_ignorable; assert_ignorable::>(); assert_ignorable::>>(); diff --git a/core/lib/Cargo.toml b/core/lib/Cargo.toml index 11b0487bf4..072a5032c7 100644 --- 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 index ae6fb74460..0f71316dfe 100644 --- 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 index eb6c532ca6..76ccf76046 100644 --- 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 { default_catchers! { diff --git a/core/lib/src/codegen.rs b/core/lib/src/codegen.rs index a8d98f8520..276eea1a32 100644 --- 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 index 536e773cf3..6d60fa225a 100644 --- 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 index a40fe67cf2..99d010c098 100644 --- 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 index 3d4daf4134..2b50cb1cea 100644 --- 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 index b582d2587c..e32e09be36 100644 --- 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 index f26b3bbbaa..e7041c8261 100644 --- 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 index a5a3c6034e..a3120d5535 100644 --- 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 = ::std::result::Result; +pub type Result = std::result::Result; #[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 = Mutex::new(0); } diff --git a/core/lib/src/config/toml_ext.rs b/core/lib/src/config/toml_ext.rs index bf5a61998e..d7a9385969 100644 --- 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 { /// `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 index e755395ed7..e33c76249f 100644 --- 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>, 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 = ""` route parameter as follows: +/// [`FromData`](crate::data::FromData) are used via code generation by +/// specifying the `data = ""` 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 = "")] /// 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 { + crate fn from_hyp(mut body: HyperBodyReader<'_, '_>) -> Result { #[inline(always)] #[cfg(feature = "tls")] - fn concrete_stream(stream: &mut NetworkStream) -> Option { + fn concrete_stream(stream: &mut dyn NetworkStream) -> Option { stream.downcast_ref::() .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 { + fn concrete_stream(stream: &mut dyn NetworkStream) -> Option { stream.downcast_ref::() .map(|s| NetStream::Http(s.clone())) } diff --git a/core/lib/src/data/data_stream.rs b/core/lib/src/data/data_stream.rs index 719e4b3a38..70c41b5ad9 100644 --- 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>, BodyReader>; @@ -11,7 +11,7 @@ pub type InnerStream = Chain>, 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 index a3eb5461c5..41a1fa74f9 100644 --- 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 = outcome::Outcome; -impl<'a, S, E> IntoOutcome for Result { +impl IntoOutcome for Result { 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 = "")] /// 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` and `Option` 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>; + fn transform(request: &Request<'_>, data: Data) -> Transform>; /// 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; + fn from_data(request: &Request<'_>, outcome: Transformed<'a, Self>) -> Outcome; } /// 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> { + fn transform(_: &Request<'_>, data: Data) -> Transform> { Transform::Owned(Success(data)) } #[inline(always)] - fn from_data(_: &Request, outcome: Transformed<'f, Self>) -> Outcome { + fn from_data(_: &Request<'_>, outcome: Transformed<'f, Self>) -> Outcome { 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 = "")] /// 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; + fn from_data(request: &Request<'_>, data: Data) -> Outcome; } 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> { + fn transform(_: &Request<'_>, d: Data) -> Transform> { Transform::Owned(Success(d)) } #[inline(always)] - fn from_data(req: &Request, o: Transformed<'a, Self>) -> Outcome { + fn from_data(req: &Request<'_>, o: Transformed<'a, Self>) -> Outcome { T::from_data(req, o.owned()?) } } @@ -527,12 +527,12 @@ impl<'a, T: FromData<'a> + 'a> FromData<'a> for Result { type Borrowed = T::Borrowed; #[inline(always)] - fn transform(r: &Request, d: Data) -> Transform> { + fn transform(r: &Request<'_>, d: Data) -> Transform> { T::transform(r, d) } #[inline(always)] - fn from_data(r: &Request, o: Transformed<'a, Self>) -> Outcome { + fn from_data(r: &Request<'_>, o: Transformed<'a, Self>) -> Outcome { 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 { type Borrowed = T::Borrowed; #[inline(always)] - fn transform(r: &Request, d: Data) -> Transform> { + fn transform(r: &Request<'_>, d: Data) -> Transform> { T::transform(r, d) } #[inline(always)] - fn from_data(r: &Request, o: Transformed<'a, Self>) -> Outcome { + fn from_data(r: &Request<'_>, o: Transformed<'a, Self>) -> Outcome { 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 { + fn from_data(_: &Request<'_>, data: Data) -> Outcome { let mut string = String::new(); match data.open().read_to_string(&mut string) { Ok(_) => Success(string), @@ -582,7 +582,7 @@ impl FromDataSimple for Vec { type Error = io::Error; #[inline(always)] - fn from_data(_: &Request, data: Data) -> Outcome { + fn from_data(_: &Request<'_>, data: Data) -> Outcome { 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 index c9bdedd7c8..b9a8099cf6 100644 --- 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 index 1b52af1517..1993794e8e 100644 --- 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) } /// 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 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> 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 index e03b900e12..1952b6d4b5 100644 --- 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>>), /// An ad-hoc **request** fairing. Called when a request is received. - Request(Box), + Request(Box, &Data) + Send + Sync + 'static>), /// An ad-hoc **response** fairing. Called when a response is ready to be /// sent to a client. - Response(Box), + Response(Box, &mut Response<'_>) + Send + Sync + 'static>), } impl AdHoc { @@ -104,7 +104,7 @@ impl AdHoc { /// }); /// ``` pub fn on_request(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(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 index 93815f9c90..a0425f1e2d 100644 --- 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>, + all_fairings: Vec>, attach_failures: Vec<&'static str>, // The vectors below hold indices into `all_fairings`. launch: Vec, @@ -19,7 +19,7 @@ impl Fairings { Fairings::default() } - pub fn attach(&mut self, fairing: Box, mut rocket: Rocket) -> Rocket { + pub fn attach(&mut self, fairing: Box, 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) { + fn add(&mut self, fairing: Box) { 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 index a2a91f06e1..0e0a09436a 100644 --- 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 index dbb4c772a9..f11f1c108d 100644 --- 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 { +/// fn from_request(request: &Request<'_>) -> request::Outcome { /// 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 Fairing for ::std::sync::Arc { +impl Fairing for std::sync::Arc { #[inline] fn info(&self) -> Info { (self as &T).info() @@ -428,12 +428,12 @@ impl Fairing for ::std::sync::Arc { } #[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 index 33b930046c..66a4c1a8a2 100644 --- 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, 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`. @@ -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; + fn clone_handler(&self) -> Box; } impl Cloneable for T { #[inline(always)] - fn clone_handler(&self) -> Box { + fn clone_handler(&self) -> Box { Box::new(self.clone()) } } -impl Clone for Box { +impl Clone for Box { #[inline(always)] - fn clone(&self) -> Box { + fn clone(&self) -> Box { self.clone_handler() } } impl 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>(req: &Request, responder: T) -> Outcome<'r> { + pub fn from>(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 index a389a6746a..c20afa19a7 100644 --- 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 index ef69024989..8e7900dd61 100644 --- 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 index 49f681c208..31b8b638b3 100644 --- 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

` 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) -> Self { + pub fn cookies(self, cookies: Vec>) -> 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 index bd31d68155..81e62750e5 100644 --- 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 index e635ccaa26..bbb54370c7 100644 --- 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 { @@ -625,13 +626,13 @@ impl Try for Outcome { } impl fmt::Debug for Outcome { - 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 fmt::Display for Outcome { - 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 index b8f0bf186b..eb683db562 100644 --- 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`]: ::request::Form -/// [`FromForm`]: ::request::FromForm +/// [`FromData`]: crate::data::FromData +/// [`Form`]: 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 index f409d3ae6a..6ac95786fd 100644 --- 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`. 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 { type Borrowed = str; fn transform( - request: &Request, + request: &Request<'_>, data: Data ) -> Transform> { use std::{cmp::min, io::Read}; @@ -214,7 +214,7 @@ impl<'f, T: FromForm<'f>> FromData<'f> for Form { Transform::Borrowed(outcome) } - fn from_data(_: &Request, o: Transformed<'f, Self>) -> Outcome { + fn from_data(_: &Request<'_>, o: Transformed<'f, Self>) -> Outcome { >::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 index 46f9dd3151..ac8141db49 100644 --- 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> + ::std::fmt::Debug +// where T: Into> + 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 index 507cd54a7d..c57a5a068b 100644 --- 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 index c6480c47c5..7802eaf667 100644 --- 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 (`?`) are required to /// implement this trait. diff --git a/core/lib/src/request/form/lenient.rs b/core/lib/src/request/form/lenient.rs index 87697e51ce..4cae348f11 100644 --- 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 { type Owned = String; type Borrowed = str; - fn transform(r: &Request, d: Data) -> Transform> { + fn transform(r: &Request<'_>, d: Data) -> Transform> { >::transform(r, d) } - fn from_data(_: &Request, o: Transformed<'f, Self>) -> Outcome { + fn from_data(_: &Request<'_>, o: Transformed<'f, Self>) -> Outcome { >::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 index 53ec9291b6..6011049981 100644 --- 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 = outcome::Outcome; @@ -82,7 +82,7 @@ impl IntoOutcome for Result { /// * **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` and `Option` to catch `Failure`s and retrieve the error /// value. @@ -186,10 +186,10 @@ impl IntoOutcome for Result { /// 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 { +/// fn from_request(request: &Request<'_>) -> request::Outcome { /// 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 IntoOutcome for Result { /// # 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 { +/// # fn from_request(request: &Request<'_>) -> request::Outcome { /// # 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 { +/// fn from_request(request: &Request<'_>) -> request::Outcome { /// let db = request.guard::()?; /// request.cookies() /// .get_private("user_id") @@ -254,10 +254,10 @@ impl IntoOutcome for Result { /// } /// } /// -/// impl<'a, 'r> FromRequest<'a, 'r> for Admin { +/// impl FromRequest<'_, '_> for Admin { /// type Error = (); /// -/// fn from_request(request: &'a Request<'r>) -> request::Outcome { +/// fn from_request(request: &Request<'_>) -> request::Outcome { /// // This will unconditionally query the database! /// let user = request.guard::()?; /// @@ -296,19 +296,19 @@ impl IntoOutcome for Result { /// # 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 { +/// # fn from_request(request: &Request<'_>) -> request::Outcome { /// # 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 IntoOutcome for Result { /// } /// } /// -/// 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, !> { +/// fn from_request(request: &'a Request<'_>) -> request::Outcome, !> { /// 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; } -impl<'a, 'r> FromRequest<'a, 'r> for Method { +impl FromRequest<'_, '_> for Method { type Error = !; - fn from_request(request: &'a Request<'r>) -> Outcome { + fn from_request(request: &Request<'_>) -> Outcome { 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 { + fn from_request(request: &'a Request<'_>) -> Outcome { 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 { + fn from_request(request: &Request<'r>) -> Outcome { 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 { + fn from_request(request: &'a Request<'_>) -> Outcome { 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 { + fn from_request(request: &'a Request<'_>) -> Outcome { 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 { + fn from_request(request: &'a Request<'_>) -> Outcome { 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 { + fn from_request(request: &Request<'_>) -> Outcome { 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 index 748c994bcb..94a6d43a42 100644 --- 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 index d632636f1d..b64e8dc9d9 100644 --- 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 { + fn from_segments(segments: Segments<'_>) -> Result { segments.into_path_buf(false) } } diff --git a/core/lib/src/request/query.rs b/core/lib/src/request/query.rs index 3ca0a0766b..450d4c5b31 100644 --- 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; +/// # type Result = std::result::Result; /// # -/// # 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 index af6987430c..6a5b06aa82 100644 --- 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(method: Method, uri: &str, f: F) { + pub fn example)>(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 { + pub fn raw_segments(&self, n: usize) -> Option> { 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 + DoubleEndedIterator + Clone> { + ) -> Option> + 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 index be4eb5a596..fdaef1910b 100644 --- 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 { +/// fn from_request(request: &Request<'_>) -> request::Outcome { /// request.guard::>() /// .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, ()> { + fn from_request(req: &Request<'r>) -> request::Outcome, ()> { match req.state.managed.try_get::() { 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 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 index af86787e99..ac21bb41a0 100644 --- 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 index f534d1c4f3..84cb60cb4c 100644 --- a/core/lib/src/response/content.rs +++ b/core/lib/src/response/content.rs @@ -22,9 +22,9 @@ //! let response = content::Html("

Hello, world!

"); //! ``` -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(pub ContentType, pub R); /// delegates the remainder of the response to the wrapped responder. impl<'r, R: Responder<'r>> Responder<'r> for Content { #[inline(always)] - fn respond_to(self, req: &Request) -> Result, Status> { + fn respond_to(self, req: &Request<'_>) -> Result, 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 { - fn respond_to(self, req: &Request) -> Result, Status> { + fn respond_to(self, req: &Request<'_>) -> Result, 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 index f77fea03a0..8bbc4c3960 100644 --- 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 { /// /// [`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 { /// Constructs a new `Flash` message with the given `name`, `msg`, and @@ -194,7 +194,7 @@ impl<'r, R: Responder<'r>> Flash { /// 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 { - fn respond_to(self, req: &Request) -> Result, Status> { + fn respond_to(self, req: &Request<'_>) -> Result, 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 index 4fe734b6dd..d183710868 100644 --- 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, ::http::Status>; +pub type Result<'r> = std::result::Result, crate::http::Status>; diff --git a/core/lib/src/response/named_file.rs b/core/lib/src/response/named_file.rs index 60375abd72..5c98d6aafe 100644 --- 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 { 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 { 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 { self.file().seek(pos) } diff --git a/core/lib/src/response/redirect.rs b/core/lib/src/response/redirect.rs index 127c582066..4fe245f770 100644 --- 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>); @@ -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, Status> { +impl Responder<'_> for Redirect { + fn respond_to(self, _: &Request<'_>) -> Result, 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 index 5e6937e591..f0a83a2fdf 100644 --- 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 { - fn respond_to(self, _: &Request) -> response::Result<'r> { +impl Responder<'_> for Vec { + 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 { } /// 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 { - 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 { /// 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 { - 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 { /// 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 { - 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 index bb081e6e3f..64a2afaa2d 100644 --- 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 Body { } impl fmt::Debug for Body { - 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
`. - /// 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
`. - /// 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, headers: HeaderMap<'r>, - body: Option>>, + body: Option>>, } 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 { + pub fn cookies(&self) -> Vec> { 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
`. 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
`. 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
`. 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> { + pub fn body(&mut self) -> Option> { // 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>> { + pub fn take_body(&mut self) -> Option>> { 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, Status> { + fn respond_to(self, _: &Request<'_>) -> Result, Status> { Ok(self) } } diff --git a/core/lib/src/response/status.rs b/core/lib/src/response/status.rs index 22215f7485..2753e7750d 100644 --- 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(pub String, pub Option); /// 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 { - default fn respond_to(self, req: &Request) -> Result, Status> { + default fn respond_to(self, req: &Request<'_>) -> Result, 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 { /// 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 { - fn respond_to(self, req: &Request) -> Result, Status> { + fn respond_to(self, req: &Request<'_>) -> Result, Status> { let mut hasher = DefaultHasher::default(); let mut build = Response::build(); if let Some(responder) = self.1 { @@ -101,7 +101,7 @@ pub struct Accepted(pub Option); /// 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 { - fn respond_to(self, req: &Request) -> Result, Status> { + fn respond_to(self, req: &Request<'_>) -> Result, 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(pub Option); /// 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 { - fn respond_to(self, req: &Request) -> Result, Status> { + fn respond_to(self, req: &Request<'_>) -> Result, 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(pub R); /// Sets the status code of the response to 404 Not Found. impl<'r, R: Responder<'r>> Responder<'r> for NotFound { - fn respond_to(self, req: &Request) -> Result, Status> { + fn respond_to(self, req: &Request<'_>) -> Result, Status> { Response::build_from(self.0.respond_to(req)?) .status(Status::NotFound) .ok() @@ -192,7 +192,7 @@ pub struct Custom(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 { - fn respond_to(self, req: &Request) -> Result, Status> { + fn respond_to(self, req: &Request<'_>) -> Result, 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 index 58293d5977..84e106cc57 100644 --- 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 Stream { } impl Debug for Stream { - 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 From for Stream { /// 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 { - fn respond_to(self, _: &Request) -> Result, Status> { + fn respond_to(self, _: &Request<'_>) -> Result, Status> { Response::build().chunked_body(self.0, self.1).ok() } } diff --git a/core/lib/src/rocket.rs b/core/lib/src/rocket.rs index 8b2f46ce88..a423ec5192 100644 --- 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` 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 index f9847d8d1c..f3b1aa68d8 100644 --- 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 index d73eee4399..7e666fd5d2 100644 --- 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 index 4856afdc42..0c90848fbc 100644 --- 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, + pub handler: Box, /// 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 { - let path_segments = >::parse(&route.uri) + let path_segments = >::parse(&route.uri) .map(|res| res.map(|s| s.into_owned())) .collect::, _>>()?; - let (query_segments, dyn) = match >::parse(&route.uri) { + let (query_segments, is_dyn) = match >::parse(&route.uri) { Some(results) => { let segments = results.map(|res| res.map(|s| s.into_owned())) .collect::, _>>()?; @@ -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 >::parse(&base) { + for segment in >::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 index 43eaeb493a..e47430c601 100644 --- 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 index 5e81bf795f..a7ec90cac5 100644 --- 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) -> Option<()> { +fn unused(flash: Option>) -> Option<()> { flash.map(|_| ()) } #[get("/use")] -fn used(flash: Option) -> Option { +fn used(flash: Option>) -> Option { flash.map(|flash| flash.msg().into()) } diff --git a/core/lib/tests/mount_point.rs b/core/lib/tests/mount_point.rs index 99d8dd92ad..d5ceaa0d4c 100644 --- 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 index a9ece08523..d0db32d07d 100644 --- 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) -> 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::>().unwrap(); + let counter = req.guard::>().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 index e47bb41c3c..3ad8dae23e 100644 --- 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/")] -fn test(path: Segments) -> String { +fn test(path: Segments<'_>) -> String { path.collect::>().join("/") } #[get("/two/")] -fn two(path: Segments) -> String { +fn two(path: Segments<'_>) -> String { path.collect::>().join("/") } #[get("/one/two/")] -fn one_two(path: Segments) -> String { +fn one_two(path: Segments<'_>) -> String { path.collect::>().join("/") } #[get("/", rank = 2)] -fn none(path: Segments) -> String { +fn none(path: Segments<'_>) -> String { path.collect::>().join("/") } #[get("/static//is/")] -fn dual(user: String, path: Segments) -> String { +fn dual(user: String, path: Segments<'_>) -> String { user + "/is/" + &path.collect::>().join("/") } diff --git a/examples/config/Cargo.toml b/examples/config/Cargo.toml index be32ccdf5e..553a2f53b0 100644 --- a/examples/config/Cargo.toml +++ b/examples/config/Cargo.toml @@ -2,6 +2,7 @@ name = "config" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/config/src/main.rs b/examples/config/src/main.rs index b3719a5e6e..114a6b3356 100644 --- a/examples/config/src/main.rs +++ b/examples/config/src/main.rs @@ -1,5 +1,3 @@ -extern crate rocket; - // This example's illustration is the Rocket.toml file. fn main() { rocket::ignite().launch(); diff --git a/examples/config/tests/common/mod.rs b/examples/config/tests/common/mod.rs index 8535636178..7e51b6e1e0 100644 --- a/examples/config/tests/common/mod.rs +++ b/examples/config/tests/common/mod.rs @@ -7,8 +7,8 @@ use rocket::local::Client; struct LocalConfig(Config); #[get("/check_config")] -fn check_config(config: State) -> Option<()> { - let environment = match ::std::env::var("ROCKET_ENV") { +fn check_config(config: State<'_, LocalConfig>) -> Option<()> { + let environment = match std::env::var("ROCKET_ENV") { Ok(name) => name, Err(_) => return None }; @@ -52,7 +52,7 @@ fn check_config(config: State) -> Option<()> { pub fn test_config(environment: Environment) { // Manually set the config environment variable. Rocket will initialize the // environment in `ignite()`. We'll read this back in the handler to config. - ::std::env::set_var("ROCKET_ENV", environment.to_string()); + std::env::set_var("ROCKET_ENV", environment.to_string()); let rocket = rocket::ignite() .attach(AdHoc::on_attach("Local Config", |rocket| { diff --git a/examples/content_types/Cargo.toml b/examples/content_types/Cargo.toml index 699ed84f1a..d2d05996c4 100644 --- a/examples/content_types/Cargo.toml +++ b/examples/content_types/Cargo.toml @@ -2,6 +2,7 @@ name = "content_types" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/content_types/src/main.rs b/examples/content_types/src/main.rs index fe957a71ae..d62ce5d7ce 100644 --- a/examples/content_types/src/main.rs +++ b/examples/content_types/src/main.rs @@ -2,7 +2,6 @@ #[macro_use] extern crate rocket; #[macro_use] extern crate serde_derive; -extern crate serde_json; #[cfg(test)] mod tests; @@ -42,7 +41,7 @@ fn post_hello(age: u8, name_data: Data) -> io::Result> { } #[catch(404)] -fn not_found(request: &Request) -> content::Html { +fn not_found(request: &Request<'_>) -> content::Html { let html = match request.format() { Some(ref mt) if !mt.is_json() && !mt.is_plain() => { format!("

'{}' requests are not supported.

", mt) diff --git a/examples/content_types/src/tests.rs b/examples/content_types/src/tests.rs index a6865af14d..afe31228fc 100644 --- a/examples/content_types/src/tests.rs +++ b/examples/content_types/src/tests.rs @@ -1,5 +1,3 @@ -use super::rocket; -use super::serde_json; use super::Person; use rocket::http::{Accept, ContentType, Header, MediaType, Method, Status}; use rocket::local::Client; diff --git a/examples/cookies/Cargo.toml b/examples/cookies/Cargo.toml index 142a027338..bcf93e338f 100644 --- a/examples/cookies/Cargo.toml +++ b/examples/cookies/Cargo.toml @@ -2,6 +2,7 @@ name = "cookies" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/cookies/src/main.rs b/examples/cookies/src/main.rs index eb884b9382..3c4871f7fb 100644 --- a/examples/cookies/src/main.rs +++ b/examples/cookies/src/main.rs @@ -1,7 +1,6 @@ #![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; -extern crate rocket_contrib; #[cfg(test)] mod tests; @@ -19,13 +18,13 @@ struct Message { } #[post("/submit", data = "")] -fn submit(mut cookies: Cookies, message: Form) -> Redirect { +fn submit(mut cookies: Cookies<'_>, message: Form) -> Redirect { cookies.add(Cookie::new("message", message.into_inner().message)); Redirect::to("/") } #[get("/")] -fn index(cookies: Cookies) -> Template { +fn index(cookies: Cookies<'_>) -> Template { let cookie = cookies.get("message"); let mut context = HashMap::new(); if let Some(ref cookie) = cookie { diff --git a/examples/errors/Cargo.toml b/examples/errors/Cargo.toml index eab8ece4f1..5e6bd16be5 100644 --- a/examples/errors/Cargo.toml +++ b/examples/errors/Cargo.toml @@ -2,6 +2,7 @@ name = "errors" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/errors/src/main.rs b/examples/errors/src/main.rs index 9693363d29..1004d39712 100644 --- a/examples/errors/src/main.rs +++ b/examples/errors/src/main.rs @@ -12,7 +12,7 @@ fn hello(name: String, age: i8) -> String { } #[catch(404)] -fn not_found(req: &rocket::Request) -> content::Html { +fn not_found(req: &rocket::Request<'_>) -> content::Html { content::Html(format!("

Sorry, but '{}' is not a valid path!

Try visiting /hello/<name>/<age> instead.

", req.uri())) diff --git a/examples/errors/src/tests.rs b/examples/errors/src/tests.rs index 827bc0c6b0..78f4142229 100644 --- a/examples/errors/src/tests.rs +++ b/examples/errors/src/tests.rs @@ -1,4 +1,3 @@ -use super::rocket; use rocket::local::Client; use rocket::http::Status; diff --git a/examples/fairings/Cargo.toml b/examples/fairings/Cargo.toml index 28af205a42..ae92777794 100644 --- a/examples/fairings/Cargo.toml +++ b/examples/fairings/Cargo.toml @@ -2,6 +2,7 @@ name = "fairings" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/fairings/src/main.rs b/examples/fairings/src/main.rs index 0f1c982ff6..cd823e2189 100644 --- a/examples/fairings/src/main.rs +++ b/examples/fairings/src/main.rs @@ -27,7 +27,7 @@ impl Fairing for Counter { } } - fn on_request(&self, request: &mut Request, _: &Data) { + fn on_request(&self, request: &mut Request<'_>, _: &Data) { if request.method() == Method::Get { self.get.fetch_add(1, Ordering::Relaxed); } else if request.method() == Method::Post { @@ -35,7 +35,7 @@ impl Fairing for Counter { } } - fn on_response(&self, request: &Request, response: &mut Response) { + fn on_response(&self, request: &Request<'_>, response: &mut Response<'_>) { if response.status() != Status::NotFound { return } @@ -58,7 +58,7 @@ fn hello() -> &'static str { } #[get("/token")] -fn token(token: State) -> String { +fn token(token: State<'_, Token>) -> String { format!("{}", token.0) } diff --git a/examples/form_kitchen_sink/Cargo.toml b/examples/form_kitchen_sink/Cargo.toml index db7f290aef..c1f999a45a 100644 --- a/examples/form_kitchen_sink/Cargo.toml +++ b/examples/form_kitchen_sink/Cargo.toml @@ -2,6 +2,7 @@ name = "form_kitchen_sink" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/form_kitchen_sink/src/main.rs b/examples/form_kitchen_sink/src/main.rs index 6c017e34f5..f3330af728 100644 --- a/examples/form_kitchen_sink/src/main.rs +++ b/examples/form_kitchen_sink/src/main.rs @@ -28,7 +28,7 @@ struct FormInput<'r> { } #[post("/", data = "")] -fn sink(sink: Result, FormError>) -> String { +fn sink(sink: Result>, FormError<'_>>) -> String { match sink { Ok(form) => format!("{:?}", &*form), Err(FormDataError::Io(_)) => format!("Form input was invalid UTF-8."), diff --git a/examples/form_kitchen_sink/src/tests.rs b/examples/form_kitchen_sink/src/tests.rs index 6c5d4f4a94..cafbe685b7 100644 --- a/examples/form_kitchen_sink/src/tests.rs +++ b/examples/form_kitchen_sink/src/tests.rs @@ -5,7 +5,7 @@ use rocket::local::Client; use rocket::http::ContentType; impl fmt::Display for FormOption { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { FormOption::A => write!(f, "a"), FormOption::B => write!(f, "b"), @@ -23,14 +23,14 @@ fn assert_form_eq(client: &Client, form_str: &str, expected: String) { assert_eq!(res.body_string(), Some(expected)); } -fn assert_valid_form(client: &Client, input: &FormInput) { +fn assert_valid_form(client: &Client, input: &FormInput<'_>) { let f = format!("checkbox={}&number={}&type={}&password={}&textarea={}&select={}", input.checkbox, input.number, input.radio, input.password, input.text_area, input.select); assert_form_eq(client, &f, format!("{:?}", input)); } -fn assert_valid_raw_form(client: &Client, form_str: &str, input: &FormInput) { +fn assert_valid_raw_form(client: &Client, form_str: &str, input: &FormInput<'_>) { assert_form_eq(client, form_str, format!("{:?}", input)); } @@ -176,7 +176,7 @@ fn check_structurally_invalid_forms() { fn check_bad_utf8() { let client = Client::new(rocket()).unwrap(); unsafe { - let bad_str = ::std::str::from_utf8_unchecked(b"a=\xff"); + let bad_str = std::str::from_utf8_unchecked(b"a=\xff"); assert_form_eq(&client, bad_str, "Form input was invalid UTF-8.".into()); } } diff --git a/examples/form_validation/Cargo.toml b/examples/form_validation/Cargo.toml index ed433095dc..ffd3f68745 100644 --- a/examples/form_validation/Cargo.toml +++ b/examples/form_validation/Cargo.toml @@ -2,6 +2,7 @@ name = "form_validation" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/form_validation/src/main.rs b/examples/form_validation/src/main.rs index 580e81700e..e389004a3d 100644 --- a/examples/form_validation/src/main.rs +++ b/examples/form_validation/src/main.rs @@ -51,7 +51,7 @@ impl<'v> FromFormValue<'v> for AdultAge { } #[post("/login", data = "")] -fn login(user: Form) -> Result { +fn login(user: Form>) -> Result { if let Err(e) = user.age { return Err(format!("Age is invalid: {}", e)); } diff --git a/examples/handlebars_templates/Cargo.toml b/examples/handlebars_templates/Cargo.toml index b29c4197b4..cacf6f1466 100644 --- a/examples/handlebars_templates/Cargo.toml +++ b/examples/handlebars_templates/Cargo.toml @@ -2,6 +2,7 @@ name = "handlebars_templates" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/handlebars_templates/src/main.rs b/examples/handlebars_templates/src/main.rs index 759674d63c..5dcac21146 100644 --- a/examples/handlebars_templates/src/main.rs +++ b/examples/handlebars_templates/src/main.rs @@ -2,7 +2,6 @@ #[macro_use] extern crate rocket; #[macro_use] extern crate serde_derive; -extern crate rocket_contrib; #[cfg(test)] mod tests; @@ -10,8 +9,6 @@ use rocket::Request; use rocket::response::Redirect; use rocket_contrib::templates::{Template, handlebars}; -use handlebars::{Helper, Handlebars, Context, RenderContext, Output, HelperResult, JsonRender}; - #[derive(Serialize)] struct TemplateContext { title: &'static str, @@ -47,18 +44,20 @@ fn about() -> Template { } #[catch(404)] -fn not_found(req: &Request) -> Template { +fn not_found(req: &Request<'_>) -> Template { let mut map = std::collections::HashMap::new(); map.insert("path", req.uri().path()); Template::render("error/404", &map) } +use self::handlebars::{Helper, Handlebars, Context, RenderContext, Output, HelperResult, JsonRender}; + fn wow_helper( - h: &Helper, + h: &Helper<'_, '_>, _: &Handlebars, _: &Context, - _: &mut RenderContext, - out: &mut Output + _: &mut RenderContext<'_>, + out: &mut dyn Output ) -> HelperResult { if let Some(param) = h.param(0) { out.write("")?; diff --git a/examples/handlebars_templates/src/tests.rs b/examples/handlebars_templates/src/tests.rs index bc54a82acf..89d159f977 100644 --- a/examples/handlebars_templates/src/tests.rs +++ b/examples/handlebars_templates/src/tests.rs @@ -16,7 +16,7 @@ macro_rules! dispatch { fn test_root() { // Check that the redirect works. for method in &[Get, Head] { - dispatch!(*method, "/", |_: &Client, mut response: LocalResponse| { + dispatch!(*method, "/", |_: &Client, mut response: LocalResponse<'_>| { assert_eq!(response.status(), Status::SeeOther); assert!(response.body().is_none()); @@ -27,8 +27,8 @@ fn test_root() { // Check that other request methods are not accepted (and instead caught). for method in &[Post, Put, Delete, Options, Trace, Connect, Patch] { - dispatch!(*method, "/", |client: &Client, mut response: LocalResponse| { - let mut map = ::std::collections::HashMap::new(); + dispatch!(*method, "/", |client: &Client, mut response: LocalResponse<'_>| { + let mut map = std::collections::HashMap::new(); map.insert("path", "/"); let expected = Template::show(client.rocket(), "error/404", &map).unwrap(); @@ -41,7 +41,7 @@ fn test_root() { #[test] fn test_name() { // Check that the /hello/ route works. - dispatch!(Get, "/hello/Jack%20Daniels", |client: &Client, mut response: LocalResponse| { + dispatch!(Get, "/hello/Jack%20Daniels", |client: &Client, mut response: LocalResponse<'_>| { let context = TemplateContext { title: "Hello", name: Some("Jack Daniels".into()), @@ -58,8 +58,8 @@ fn test_name() { #[test] fn test_404() { // Check that the error catcher works. - dispatch!(Get, "/hello/", |client: &Client, mut response: LocalResponse| { - let mut map = ::std::collections::HashMap::new(); + dispatch!(Get, "/hello/", |client: &Client, mut response: LocalResponse<'_>| { + let mut map = std::collections::HashMap::new(); map.insert("path", "/hello/"); let expected = Template::show(client.rocket(), "error/404", &map).unwrap(); diff --git a/examples/hello_2018/Cargo.toml b/examples/hello_2018/Cargo.toml index 06ae36822f..23dee942c8 100644 --- a/examples/hello_2018/Cargo.toml +++ b/examples/hello_2018/Cargo.toml @@ -2,8 +2,8 @@ name = "hello_2018" version = "0.0.0" workspace = "../../" -publish = false edition = "2018" +publish = false [dependencies] rocket = { path = "../../core/lib" } diff --git a/examples/hello_person/Cargo.toml b/examples/hello_person/Cargo.toml index 76423aaa79..99be046f75 100644 --- a/examples/hello_person/Cargo.toml +++ b/examples/hello_person/Cargo.toml @@ -2,6 +2,7 @@ name = "hello_person" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/hello_person/src/tests.rs b/examples/hello_person/src/tests.rs index e6cd50e2d9..35fd399912 100644 --- a/examples/hello_person/src/tests.rs +++ b/examples/hello_person/src/tests.rs @@ -1,4 +1,3 @@ -use super::rocket; use rocket::local::Client; use rocket::http::Status; diff --git a/examples/hello_world/Cargo.toml b/examples/hello_world/Cargo.toml index 8feb601e37..2c03cf22c9 100644 --- a/examples/hello_world/Cargo.toml +++ b/examples/hello_world/Cargo.toml @@ -2,6 +2,7 @@ name = "hello_world" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/hello_world/src/tests.rs b/examples/hello_world/src/tests.rs index da0b732b9f..80bf4aeb8d 100644 --- a/examples/hello_world/src/tests.rs +++ b/examples/hello_world/src/tests.rs @@ -1,4 +1,3 @@ -use super::rocket; use rocket::local::Client; #[test] diff --git a/examples/json/Cargo.toml b/examples/json/Cargo.toml index 570405f6fd..9605667ac0 100644 --- a/examples/json/Cargo.toml +++ b/examples/json/Cargo.toml @@ -2,6 +2,7 @@ name = "json" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/json/src/main.rs b/examples/json/src/main.rs index f2f6cc17cf..d2823dae2a 100644 --- a/examples/json/src/main.rs +++ b/examples/json/src/main.rs @@ -26,7 +26,7 @@ struct Message { // TODO: This example can be improved by using `route` with multiple HTTP verbs. #[post("/", format = "json", data = "")] -fn new(id: ID, message: Json, map: State) -> JsonValue { +fn new(id: ID, message: Json, map: State<'_, MessageMap>) -> JsonValue { let mut hashmap = map.lock().expect("map lock."); if hashmap.contains_key(&id) { json!({ @@ -40,7 +40,7 @@ fn new(id: ID, message: Json, map: State) -> JsonValue { } #[put("/", format = "json", data = "")] -fn update(id: ID, message: Json, map: State) -> Option { +fn update(id: ID, message: Json, map: State<'_, MessageMap>) -> Option { let mut hashmap = map.lock().unwrap(); if hashmap.contains_key(&id) { hashmap.insert(id, message.0.contents); @@ -51,7 +51,7 @@ fn update(id: ID, message: Json, map: State) -> Option", format = "json")] -fn get(id: ID, map: State) -> Option> { +fn get(id: ID, map: State<'_, MessageMap>) -> Option> { let hashmap = map.lock().unwrap(); hashmap.get(&id).map(|contents| { Json(Message { diff --git a/examples/json/src/tests.rs b/examples/json/src/tests.rs index 8d22448bb6..8b6909373f 100644 --- a/examples/json/src/tests.rs +++ b/examples/json/src/tests.rs @@ -1,4 +1,4 @@ -use rocket; +use crate::rocket; use rocket::local::Client; use rocket::http::{Status, ContentType}; diff --git a/examples/managed_queue/Cargo.toml b/examples/managed_queue/Cargo.toml index c2041ac382..ba8330e9bf 100644 --- a/examples/managed_queue/Cargo.toml +++ b/examples/managed_queue/Cargo.toml @@ -2,6 +2,7 @@ name = "managed_queue" version = "0.0.0" workspace = "../.." +edition = "2018" publish = false [dependencies] diff --git a/examples/managed_queue/src/main.rs b/examples/managed_queue/src/main.rs index 809dd353da..22ed3db118 100644 --- a/examples/managed_queue/src/main.rs +++ b/examples/managed_queue/src/main.rs @@ -1,7 +1,6 @@ #![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; -extern crate crossbeam; #[cfg(test)] mod tests; @@ -11,12 +10,12 @@ use crossbeam::queue::SegQueue; struct LogChannel(SegQueue); #[put("/push?")] -fn push(event: String, queue: State) { +fn push(event: String, queue: State<'_, LogChannel>) { queue.0.push(event); } #[get("/pop")] -fn pop(queue: State) -> Option { +fn pop(queue: State<'_, LogChannel>) -> Option { queue.0.pop().ok() } diff --git a/examples/manual_routes/Cargo.toml b/examples/manual_routes/Cargo.toml index ba5399a8bf..8519ae945e 100644 --- a/examples/manual_routes/Cargo.toml +++ b/examples/manual_routes/Cargo.toml @@ -2,6 +2,7 @@ name = "manual_routes" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/msgpack/Cargo.toml b/examples/msgpack/Cargo.toml index fb5954f661..500b6a6ad2 100644 --- a/examples/msgpack/Cargo.toml +++ b/examples/msgpack/Cargo.toml @@ -2,6 +2,7 @@ name = "msgpack" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/msgpack/src/main.rs b/examples/msgpack/src/main.rs index 599f1d3868..2e5146295f 100644 --- a/examples/msgpack/src/main.rs +++ b/examples/msgpack/src/main.rs @@ -2,7 +2,6 @@ #[macro_use] extern crate rocket; #[macro_use] extern crate serde_derive; -extern crate rocket_contrib; #[cfg(test)] mod tests; @@ -20,7 +19,7 @@ fn get(id: usize) -> MsgPack> { } #[post("/", data = "", format = "msgpack")] -fn create(data: MsgPack) -> String { +fn create(data: MsgPack>) -> String { data.contents.to_string() } diff --git a/examples/msgpack/src/tests.rs b/examples/msgpack/src/tests.rs index 188e0a20e2..0c7e346113 100644 --- a/examples/msgpack/src/tests.rs +++ b/examples/msgpack/src/tests.rs @@ -1,4 +1,4 @@ -use rocket; +use crate::rocket; use rocket::local::Client; use rocket::http::{Status, ContentType}; diff --git a/examples/optional_redirect/Cargo.toml b/examples/optional_redirect/Cargo.toml index 501c2118db..f802bd7e30 100644 --- a/examples/optional_redirect/Cargo.toml +++ b/examples/optional_redirect/Cargo.toml @@ -2,6 +2,7 @@ name = "optional_redirect" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/optional_redirect/src/tests.rs b/examples/optional_redirect/src/tests.rs index 0ce66cbb0e..2e2875ee11 100644 --- a/examples/optional_redirect/src/tests.rs +++ b/examples/optional_redirect/src/tests.rs @@ -1,4 +1,3 @@ -use super::rocket; use rocket::local::Client; use rocket::http::Status; diff --git a/examples/pastebin/Cargo.toml b/examples/pastebin/Cargo.toml index 3809334b81..e508d89e87 100644 --- a/examples/pastebin/Cargo.toml +++ b/examples/pastebin/Cargo.toml @@ -2,6 +2,7 @@ name = "pastebin" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/pastebin/src/main.rs b/examples/pastebin/src/main.rs index 2aca1fb17e..1dddd41728 100644 --- a/examples/pastebin/src/main.rs +++ b/examples/pastebin/src/main.rs @@ -1,7 +1,6 @@ #![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; -extern crate rand; mod paste_id; #[cfg(test)] mod tests; @@ -13,7 +12,7 @@ use std::path::Path; use rocket::Data; use rocket::response::content; -use paste_id::PasteID; +use crate::paste_id::PasteID; const HOST: &str = "http://localhost:8000"; const ID_LENGTH: usize = 3; @@ -29,7 +28,7 @@ fn upload(paste: Data) -> io::Result { } #[get("/")] -fn retrieve(id: PasteID) -> Option> { +fn retrieve(id: PasteID<'_>) -> Option> { let filename = format!("upload/{id}", id = id); File::open(&filename).map(|f| content::Plain(f)).ok() } diff --git a/examples/pastebin/src/paste_id.rs b/examples/pastebin/src/paste_id.rs index 8fd18c9167..736155bd4c 100644 --- a/examples/pastebin/src/paste_id.rs +++ b/examples/pastebin/src/paste_id.rs @@ -28,7 +28,7 @@ impl<'a> PasteID<'a> { } impl<'a> fmt::Display for PasteID<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } diff --git a/examples/query_params/Cargo.toml b/examples/query_params/Cargo.toml index 71a6727337..66795f7907 100644 --- a/examples/query_params/Cargo.toml +++ b/examples/query_params/Cargo.toml @@ -2,6 +2,7 @@ name = "query_params" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/query_params/src/tests.rs b/examples/query_params/src/tests.rs index 4390bf72bc..137a497f29 100644 --- a/examples/query_params/src/tests.rs +++ b/examples/query_params/src/tests.rs @@ -11,12 +11,12 @@ macro_rules! run_test { #[test] fn age_and_name_params() { - run_test!("?age=10&name=john", |mut response: Response| { + run_test!("?age=10&name=john", |mut response: Response<'_>| { assert_eq!(response.body_string(), Some("Hello, 10 year old named john!".into())); }); - run_test!("?age=20&name=john", |mut response: Response| { + run_test!("?age=20&name=john", |mut response: Response<'_>| { assert_eq!(response.body_string(), Some("20 years old? Hi, john!".into())); }); @@ -24,12 +24,12 @@ fn age_and_name_params() { #[test] fn age_param_only() { - run_test!("?age=10", |mut response: Response| { + run_test!("?age=10", |mut response: Response<'_>| { assert_eq!(response.body_string(), Some("We're gonna need a name, and only a name.".into())); }); - run_test!("?age=20", |mut response: Response| { + run_test!("?age=20", |mut response: Response<'_>| { assert_eq!(response.body_string(), Some("We're gonna need a name, and only a name.".into())); }); @@ -37,19 +37,19 @@ fn age_param_only() { #[test] fn name_param_only() { - run_test!("?name=John", |mut response: Response| { + run_test!("?name=John", |mut response: Response<'_>| { assert_eq!(response.body_string(), Some("Hello John!".into())); }); } #[test] fn no_params() { - run_test!("", |mut response: Response| { + run_test!("", |mut response: Response<'_>| { assert_eq!(response.body_string(), Some("We're gonna need a name, and only a name.".into())); }); - run_test!("?", |mut response: Response| { + run_test!("?", |mut response: Response<'_>| { assert_eq!(response.body_string(), Some("We're gonna need a name, and only a name.".into())); }); @@ -57,12 +57,12 @@ fn no_params() { #[test] fn extra_params() { - run_test!("?age=20&name=Bob&extra", |mut response: Response| { + run_test!("?age=20&name=Bob&extra", |mut response: Response<'_>| { assert_eq!(response.body_string(), Some("20 years old? Hi, Bob!".into())); }); - run_test!("?age=30&name=Bob&extra", |mut response: Response| { + run_test!("?age=30&name=Bob&extra", |mut response: Response<'_>| { assert_eq!(response.body_string(), Some("We're gonna need a name, and only a name.".into())); }); @@ -70,7 +70,7 @@ fn extra_params() { #[test] fn wrong_path() { - run_test!("/other?age=20&name=Bob", |response: Response| { + run_test!("/other?age=20&name=Bob", |response: Response<'_>| { assert_eq!(response.status(), Status::NotFound); }); } diff --git a/examples/ranking/Cargo.toml b/examples/ranking/Cargo.toml index 554b6c2360..f033e5232f 100644 --- a/examples/ranking/Cargo.toml +++ b/examples/ranking/Cargo.toml @@ -2,6 +2,7 @@ name = "ranking" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/ranking/src/tests.rs b/examples/ranking/src/tests.rs index b4177cee2f..e638150a00 100644 --- a/examples/ranking/src/tests.rs +++ b/examples/ranking/src/tests.rs @@ -1,4 +1,3 @@ -use super::rocket; use rocket::local::Client; fn test(uri: &str, expected: String) { diff --git a/examples/raw_sqlite/Cargo.toml b/examples/raw_sqlite/Cargo.toml index cda1b782ce..1b09d9af6b 100644 --- a/examples/raw_sqlite/Cargo.toml +++ b/examples/raw_sqlite/Cargo.toml @@ -2,6 +2,7 @@ name = "raw_sqlite" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/raw_sqlite/src/main.rs b/examples/raw_sqlite/src/main.rs index cc0846523d..ac241ee804 100644 --- a/examples/raw_sqlite/src/main.rs +++ b/examples/raw_sqlite/src/main.rs @@ -1,7 +1,7 @@ #![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; -extern crate rusqlite; + use rusqlite::types::ToSql; #[cfg(test)] mod tests; @@ -25,7 +25,7 @@ fn init_database(conn: &Connection) { } #[get("/")] -fn hello(db_conn: State) -> Result { +fn hello(db_conn: State<'_, DbConn>) -> Result { db_conn.lock() .expect("db connection lock") .query_row("SELECT name FROM entries WHERE id = 0", diff --git a/examples/raw_upload/Cargo.toml b/examples/raw_upload/Cargo.toml index 2df5a281e6..3b3d04d23c 100644 --- a/examples/raw_upload/Cargo.toml +++ b/examples/raw_upload/Cargo.toml @@ -2,6 +2,7 @@ name = "raw_upload" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/redirect/Cargo.toml b/examples/redirect/Cargo.toml index 51896793d8..c7a756787f 100644 --- a/examples/redirect/Cargo.toml +++ b/examples/redirect/Cargo.toml @@ -2,6 +2,7 @@ name = "redirect" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/redirect/src/tests.rs b/examples/redirect/src/tests.rs index 7c32d785c4..51b6deb65e 100644 --- a/examples/redirect/src/tests.rs +++ b/examples/redirect/src/tests.rs @@ -1,4 +1,3 @@ -use super::rocket; use rocket::local::Client; use rocket::http::Status; diff --git a/examples/request_guard/Cargo.toml b/examples/request_guard/Cargo.toml index 9d563fd930..ebeeada732 100644 --- a/examples/request_guard/Cargo.toml +++ b/examples/request_guard/Cargo.toml @@ -2,6 +2,7 @@ name = "request_guard" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/request_local_state/Cargo.toml b/examples/request_local_state/Cargo.toml index 523a110355..8322df23c6 100644 --- a/examples/request_local_state/Cargo.toml +++ b/examples/request_local_state/Cargo.toml @@ -2,6 +2,7 @@ name = "request_local_state" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/request_local_state/src/main.rs b/examples/request_local_state/src/main.rs index 9aa2db1793..f406321132 100644 --- a/examples/request_local_state/src/main.rs +++ b/examples/request_local_state/src/main.rs @@ -22,7 +22,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for Guard1 { type Error = (); fn from_request(req: &'a Request<'r>) -> request::Outcome { - let atomics = req.guard::>()?; + let atomics = req.guard::>()?; atomics.uncached.fetch_add(1, Ordering::Relaxed); req.local_cache(|| atomics.cached.fetch_add(1, Ordering::Relaxed)); diff --git a/examples/session/Cargo.toml b/examples/session/Cargo.toml index 4a2de9af18..3a367bde01 100644 --- a/examples/session/Cargo.toml +++ b/examples/session/Cargo.toml @@ -2,6 +2,7 @@ name = "session" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/session/src/main.rs b/examples/session/src/main.rs index ff6881c0f5..c4197c6bcd 100644 --- a/examples/session/src/main.rs +++ b/examples/session/src/main.rs @@ -1,7 +1,6 @@ #![feature(proc_macro_hygiene, decl_macro, never_type)] #[macro_use] extern crate rocket; -extern crate rocket_contrib; #[cfg(test)] mod tests; @@ -35,7 +34,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for User { } #[post("/login", data = "")] -fn login(mut cookies: Cookies, login: Form) -> Result> { +fn login(mut cookies: Cookies<'_>, login: Form) -> Result> { if login.username == "Sergio" && login.password == "password" { cookies.add_private(Cookie::new("user_id", 1.to_string())); Ok(Redirect::to(uri!(index))) @@ -45,7 +44,7 @@ fn login(mut cookies: Cookies, login: Form) -> Result Flash { +fn logout(mut cookies: Cookies<'_>) -> Flash { cookies.remove_private(Cookie::named("user_id")); Flash::success(Redirect::to(uri!(login_page)), "Successfully logged out.") } @@ -56,7 +55,7 @@ fn login_user(_user: User) -> Redirect { } #[get("/login", rank = 2)] -fn login_page(flash: Option) -> Template { +fn login_page(flash: Option>) -> Template { let mut context = HashMap::new(); if let Some(ref msg) = flash { context.insert("flash", msg.msg()); diff --git a/examples/session/src/tests.rs b/examples/session/src/tests.rs index 7530f1a0ac..d6ab7771ad 100644 --- a/examples/session/src/tests.rs +++ b/examples/session/src/tests.rs @@ -3,7 +3,7 @@ use rocket::Response; use rocket::local::Client; use rocket::http::{Status, Cookie, ContentType}; -fn user_id_cookie(response: &Response) -> Option> { +fn user_id_cookie(response: &Response<'_>) -> Option> { let cookie = response.headers() .get("Set-Cookie") .filter(|v| v.starts_with("user_id")) diff --git a/examples/state/Cargo.toml b/examples/state/Cargo.toml index c6bd00c5fe..b102d637cb 100644 --- a/examples/state/Cargo.toml +++ b/examples/state/Cargo.toml @@ -2,6 +2,7 @@ name = "state" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/state/src/main.rs b/examples/state/src/main.rs index 08556a013d..7cc54e6d63 100644 --- a/examples/state/src/main.rs +++ b/examples/state/src/main.rs @@ -12,7 +12,7 @@ use rocket::response::content; struct HitCount(AtomicUsize); #[get("/")] -fn index(hit_count: State) -> content::Html { +fn index(hit_count: State<'_, HitCount>) -> content::Html { hit_count.0.fetch_add(1, Ordering::Relaxed); let msg = "Your visit has been recorded!"; let count = format!("Visits: {}", count(hit_count)); @@ -20,7 +20,7 @@ fn index(hit_count: State) -> content::Html { } #[get("/count")] -fn count(hit_count: State) -> String { +fn count(hit_count: State<'_, HitCount>) -> String { hit_count.0.load(Ordering::Relaxed).to_string() } diff --git a/examples/static_files/Cargo.toml b/examples/static_files/Cargo.toml index bb2fa2733f..a465246378 100644 --- a/examples/static_files/Cargo.toml +++ b/examples/static_files/Cargo.toml @@ -2,6 +2,7 @@ name = "static_files" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/stream/Cargo.toml b/examples/stream/Cargo.toml index 5f6f1b3030..96792d90d9 100644 --- a/examples/stream/Cargo.toml +++ b/examples/stream/Cargo.toml @@ -2,6 +2,7 @@ name = "stream" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/tera_templates/Cargo.toml b/examples/tera_templates/Cargo.toml index 49605b3d4d..4f656410ae 100644 --- a/examples/tera_templates/Cargo.toml +++ b/examples/tera_templates/Cargo.toml @@ -2,6 +2,7 @@ name = "tera_templates" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/tera_templates/src/main.rs b/examples/tera_templates/src/main.rs index 8cbbbcc69c..2b04cd7053 100644 --- a/examples/tera_templates/src/main.rs +++ b/examples/tera_templates/src/main.rs @@ -2,8 +2,6 @@ #[macro_use] extern crate rocket; #[macro_use] extern crate serde_derive; -extern crate serde_json; -extern crate rocket_contrib; #[cfg(test)] mod tests; @@ -31,7 +29,7 @@ fn get(name: String) -> Template { } #[catch(404)] -fn not_found(req: &Request) -> Template { +fn not_found(req: &Request<'_>) -> Template { let mut map = HashMap::new(); map.insert("path", req.uri().path()); Template::render("error/404", &map) diff --git a/examples/tera_templates/src/tests.rs b/examples/tera_templates/src/tests.rs index 425124d385..9fc00270a6 100644 --- a/examples/tera_templates/src/tests.rs +++ b/examples/tera_templates/src/tests.rs @@ -15,7 +15,7 @@ macro_rules! dispatch { fn test_root() { // Check that the redirect works. for method in &[Get, Head] { - dispatch!(*method, "/", |_: &Client, mut response: LocalResponse| { + dispatch!(*method, "/", |_: &Client, mut response: LocalResponse<'_>| { assert_eq!(response.status(), Status::SeeOther); assert!(response.body().is_none()); @@ -26,8 +26,8 @@ fn test_root() { // Check that other request methods are not accepted (and instead caught). for method in &[Post, Put, Delete, Options, Trace, Connect, Patch] { - dispatch!(*method, "/", |client: &Client, mut response: LocalResponse| { - let mut map = ::std::collections::HashMap::new(); + dispatch!(*method, "/", |client: &Client, mut response: LocalResponse<'_>| { + let mut map = std::collections::HashMap::new(); map.insert("path", "/"); let expected = Template::show(client.rocket(), "error/404", &map).unwrap(); @@ -40,7 +40,7 @@ fn test_root() { #[test] fn test_name() { // Check that the /hello/ route works. - dispatch!(Get, "/hello/Jack", |client: &Client, mut response: LocalResponse| { + dispatch!(Get, "/hello/Jack", |client: &Client, mut response: LocalResponse<'_>| { let context = super::TemplateContext { name: "Jack".into(), items: vec!["One", "Two", "Three"] @@ -55,8 +55,8 @@ fn test_name() { #[test] fn test_404() { // Check that the error catcher works. - dispatch!(Get, "/hello/", |client: &Client, mut response: LocalResponse| { - let mut map = ::std::collections::HashMap::new(); + dispatch!(Get, "/hello/", |client: &Client, mut response: LocalResponse<'_>| { + let mut map = std::collections::HashMap::new(); map.insert("path", "/hello/"); let expected = Template::show(client.rocket(), "error/404", &map).unwrap(); diff --git a/examples/testing/Cargo.toml b/examples/testing/Cargo.toml index 8bdcc82b3f..6ed69497e5 100644 --- a/examples/testing/Cargo.toml +++ b/examples/testing/Cargo.toml @@ -2,6 +2,7 @@ name = "testing" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/tls/Cargo.toml b/examples/tls/Cargo.toml index 0cc075edb7..7f9ff33784 100644 --- a/examples/tls/Cargo.toml +++ b/examples/tls/Cargo.toml @@ -2,6 +2,7 @@ name = "tls" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/tls/src/tests.rs b/examples/tls/src/tests.rs index da0b732b9f..80bf4aeb8d 100644 --- a/examples/tls/src/tests.rs +++ b/examples/tls/src/tests.rs @@ -1,4 +1,3 @@ -use super::rocket; use rocket::local::Client; #[test] diff --git a/examples/todo/Cargo.toml b/examples/todo/Cargo.toml index 797b431a28..21662e2584 100644 --- a/examples/todo/Cargo.toml +++ b/examples/todo/Cargo.toml @@ -2,6 +2,7 @@ name = "todo" version = "0.0.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/todo/src/main.rs b/examples/todo/src/main.rs index 8ce8c4aa62..d3ed0f1f7e 100644 --- a/examples/todo/src/main.rs +++ b/examples/todo/src/main.rs @@ -17,7 +17,7 @@ use rocket::response::{Flash, Redirect}; use rocket_contrib::{templates::Template, serve::StaticFiles}; use diesel::SqliteConnection; -use task::{Task, Todo}; +use crate::task::{Task, Todo}; // This macro from `diesel_migrations` defines an `embedded_migrations` module // containing a function named `run`. This allows the example to be run and @@ -71,7 +71,7 @@ fn delete(id: i32, conn: DbConn) -> Result, Template> { } #[get("/")] -fn index(msg: Option, conn: DbConn) -> Template { +fn index(msg: Option>, conn: DbConn) -> Template { Template::render("index", &match msg { Some(ref msg) => Context::raw(&conn, Some((msg.name(), msg.msg()))), None => Context::raw(&conn, None), diff --git a/examples/todo/src/tests.rs b/examples/todo/src/tests.rs index a9ca6bae42..1553e9ef13 100644 --- a/examples/todo/src/tests.rs +++ b/examples/todo/src/tests.rs @@ -1,9 +1,7 @@ -extern crate parking_lot; -extern crate rand; - use super::task::Task; -use self::parking_lot::Mutex; -use self::rand::{Rng, thread_rng, distributions::Alphanumeric}; + +use parking_lot::Mutex; +use rand::{Rng, thread_rng, distributions::Alphanumeric}; use rocket::local::Client; use rocket::http::{Status, ContentType}; diff --git a/examples/uuid/Cargo.toml b/examples/uuid/Cargo.toml index 24018823a1..476f90d043 100644 --- a/examples/uuid/Cargo.toml +++ b/examples/uuid/Cargo.toml @@ -2,6 +2,7 @@ name = "uuid" version = "0.1.0" workspace = "../../" +edition = "2018" publish = false [dependencies] diff --git a/examples/uuid/src/main.rs b/examples/uuid/src/main.rs index b5463ed598..df9fe13cda 100644 --- a/examples/uuid/src/main.rs +++ b/examples/uuid/src/main.rs @@ -2,8 +2,6 @@ #[macro_use] extern crate rocket; #[macro_use] extern crate lazy_static; -extern crate rocket_contrib; -extern crate uuid; use std::collections::HashMap; use rocket_contrib::uuid::Uuid;