Migrate contrib to Rust 2018.

This commit is contained in:
Jeb Rosen 2019-06-12 19:17:59 -07:00 committed by Sergio Benitez
parent be784a7845
commit 2315171971
29 changed files with 123 additions and 154 deletions

View File

@ -10,6 +10,7 @@ readme = "../../README.md"
keywords = ["rocket", "contrib", "code", "generation", "proc-macro"] keywords = ["rocket", "contrib", "code", "generation", "proc-macro"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
build = "build.rs" build = "build.rs"
edition = "2018"
[features] [features]
database_attribute = [] database_attribute = []

View File

@ -1,6 +1,6 @@
use proc_macro::TokenStream; use proc_macro::TokenStream;
use devise::{Spanned, Result}; 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)] #[derive(Debug)]
struct DatabaseInvocation { struct DatabaseInvocation {
@ -24,12 +24,12 @@ const NO_GENERIC_STRUCTS: &str = "`database` attribute cannot be applied to stru
with generics"; with generics";
fn parse_invocation(attr: TokenStream, input: TokenStream) -> Result<DatabaseInvocation> { fn parse_invocation(attr: TokenStream, input: TokenStream) -> Result<DatabaseInvocation> {
let attr_stream2 = ::proc_macro2::TokenStream::from(attr); let attr_stream2 = crate::proc_macro2::TokenStream::from(attr);
let attr_span = attr_stream2.span(); let attr_span = attr_stream2.span();
let string_lit = ::syn::parse2::<LitStr>(attr_stream2) let string_lit = crate::syn::parse2::<LitStr>(attr_stream2)
.map_err(|_| attr_span.error("expected string literal"))?; .map_err(|_| attr_span.error("expected string literal"))?;
let input = ::syn::parse::<DeriveInput>(input).unwrap(); let input = crate::syn::parse::<DeriveInput>(input).unwrap();
if !input.generics.params.is_empty() { if !input.generics.params.is_empty() {
return Err(input.generics.span().error(NO_GENERIC_STRUCTS)); return Err(input.generics.span().error(NO_GENERIC_STRUCTS));
} }

View File

@ -2,6 +2,8 @@
#![feature(crate_visibility_modifier)] #![feature(crate_visibility_modifier)]
#![recursion_limit="256"] #![recursion_limit="256"]
#![warn(rust_2018_idioms)]
//! # Rocket Contrib - Code Generation //! # Rocket Contrib - Code Generation
//! This crate implements the code generation portion of the Rocket Contrib //! This crate implements the code generation portion of the Rocket Contrib
//! crate. This is for officially sanctioned contributor libraries that require //! crate. This is for officially sanctioned contributor libraries that require
@ -24,7 +26,6 @@
//! DATABASE_NAME := (string literal) //! DATABASE_NAME := (string literal)
//! </pre> //! </pre>
extern crate devise;
extern crate proc_macro; extern crate proc_macro;
#[allow(unused_imports)] #[allow(unused_imports)]
@ -43,7 +44,7 @@ use proc_macro::TokenStream;
#[cfg(feature = "database_attribute")] #[cfg(feature = "database_attribute")]
#[proc_macro_attribute] #[proc_macro_attribute]
pub fn database(attr: TokenStream, input: TokenStream) -> TokenStream { 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(); diag.emit();
TokenStream::new() TokenStream::new()
}) })

View File

@ -9,6 +9,7 @@ repository = "https://github.com/SergioBenitez/Rocket"
readme = "../../README.md" readme = "../../README.md"
keywords = ["rocket", "web", "framework", "contrib", "contributed"] keywords = ["rocket", "web", "framework", "contrib", "contributed"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
edition = "2018"
[features] [features]
# Internal use only. # Internal use only.

View File

@ -144,9 +144,9 @@ impl Fairing for Compression {
Ok(rocket.manage(ctxt)) 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 let context = request
.guard::<::rocket::State<Context>>() .guard::<rocket::State<'_, Context>>()
.expect("Compression Context registered in on_attach"); .expect("Compression Context registered in on_attach");
super::CompressionUtils::compress_response(request, response, &context.exclusions); super::CompressionUtils::compress_response(request, response, &context.exclusions);

View File

@ -22,8 +22,6 @@
//! application vulnerable to attacks including BREACH. These risks should be //! application vulnerable to attacks including BREACH. These risks should be
//! evaluated in the context of your application before enabling compression. //! 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 fairing;
mod responder; mod responder;
@ -38,15 +36,15 @@ use rocket::http::hyper::header::{ContentEncoding, Encoding};
use rocket::{Request, Response}; use rocket::{Request, Response};
#[cfg(feature = "brotli_compression")] #[cfg(feature = "brotli_compression")]
use self::brotli::enc::backward_references::BrotliEncoderMode; use brotli::enc::backward_references::BrotliEncoderMode;
#[cfg(feature = "gzip_compression")] #[cfg(feature = "gzip_compression")]
use self::flate2::read::GzEncoder; use flate2::read::GzEncoder;
struct CompressionUtils; struct CompressionUtils;
impl CompressionUtils { impl CompressionUtils {
fn accepts_encoding(request: &Request, encoding: &str) -> bool { fn accepts_encoding(request: &Request<'_>, encoding: &str) -> bool {
request request
.headers() .headers()
.get("Accept-Encoding") .get("Accept-Encoding")
@ -55,7 +53,7 @@ impl CompressionUtils {
.any(|accept| accept == encoding) .any(|accept| accept == encoding)
} }
fn already_encoded(response: &Response) -> bool { fn already_encoded(response: &Response<'_>) -> bool {
response.headers().get("Content-Encoding").next().is_some() 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) { if CompressionUtils::already_encoded(response) {
return; return;
} }

View File

@ -36,7 +36,7 @@ pub struct Compress<R>(pub R);
impl<'r, R: Responder<'r>> Responder<'r> for Compress<R> { impl<'r, R: Responder<'r>> Responder<'r> for Compress<R> {
#[inline(always)] #[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() let mut response = Response::build()
.merge(self.0.respond_to(request)?) .merge(self.0.respond_to(request)?)
.finalize(); .finalize();

View File

@ -86,7 +86,7 @@
//! # struct LogsDbConn(diesel::SqliteConnection); //! # struct LogsDbConn(diesel::SqliteConnection);
//! # //! #
//! # type Logs = (); //! # type Logs = ();
//! # type Result<T> = ::std::result::Result<T, ()>; //! # type Result<T> = std::result::Result<T, ()>;
//! # //! #
//! #[get("/logs/<id>")] //! #[get("/logs/<id>")]
//! fn get_logs(conn: LogsDbConn, id: usize) -> Result<Logs> { //! fn get_logs(conn: LogsDbConn, id: usize) -> Result<Logs> {
@ -229,7 +229,7 @@
//! allowing the type to be used as a request guard. This implementation //! allowing the type to be used as a request guard. This implementation
//! retrieves a connection from the database pool or fails with a //! retrieves a connection from the database pool or fails with a
//! `Status::ServiceUnavailable` if no connections are available. The macro also //! `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 internal `Poolable` type as the target.
//! //!
//! The macro will also generate two inherent methods on the decorated type: //! The macro will also generate two inherent methods on the decorated type:
@ -491,7 +491,7 @@ pub enum ConfigError {
/// configuration. /// configuration.
MissingKey, MissingKey,
/// The configuration associated with the key isn't a /// The configuration associated with the key isn't a
/// [`Table`](::rocket::config::Table). /// [`Table`](rocket::config::Table).
MalformedConfiguration, MalformedConfiguration,
/// The required `url` key is missing. /// The required `url` key is missing.
MissingUrl, MissingUrl,
@ -594,7 +594,7 @@ pub fn database_config<'a>(
} }
impl<'a> Display for ConfigError { impl<'a> Display for ConfigError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self { match self {
ConfigError::MissingTable => { ConfigError::MissingTable => {
write!(f, "A table named `databases` was not found for this configuration") write!(f, "A table named `databases` was not found for this configuration")
@ -659,7 +659,7 @@ impl<'a> Display for ConfigError {
/// # use std::fmt; /// # use std::fmt;
/// # use rocket_contrib::databases::r2d2; /// # use rocket_contrib::databases::r2d2;
/// # #[derive(Debug)] pub struct Error; /// # #[derive(Debug)] pub struct Error;
/// # impl ::std::error::Error for Error { } /// # impl std::error::Error for Error { }
/// # impl fmt::Display for Error { /// # impl fmt::Display for Error {
/// # fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Ok(()) } /// # fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Ok(()) }
/// # } /// # }
@ -667,7 +667,7 @@ impl<'a> Display for ConfigError {
/// # pub struct Connection; /// # pub struct Connection;
/// # pub struct ConnectionManager; /// # pub struct ConnectionManager;
/// # /// #
/// # type Result<T> = ::std::result::Result<T, Error>; /// # type Result<T> = std::result::Result<T, Error>;
/// # /// #
/// # impl ConnectionManager { /// # impl ConnectionManager {
/// # pub fn new(url: &str) -> Result<Self> { Err(Error) } /// # pub fn new(url: &str) -> Result<Self> { Err(Error) }
@ -717,7 +717,7 @@ pub trait Poolable: Send + Sized + 'static {
/// Creates an `r2d2` connection pool for `Manager::Connection`, returning /// Creates an `r2d2` connection pool for `Manager::Connection`, returning
/// the pool on success. /// the pool on success.
fn pool(config: DatabaseConfig) -> Result<r2d2::Pool<Self::Manager>, Self::Error>; fn pool(config: DatabaseConfig<'_>) -> Result<r2d2::Pool<Self::Manager>, Self::Error>;
} }
#[cfg(feature = "diesel_sqlite_pool")] #[cfg(feature = "diesel_sqlite_pool")]
@ -725,7 +725,7 @@ impl Poolable for diesel::SqliteConnection {
type Manager = diesel::r2d2::ConnectionManager<diesel::SqliteConnection>; type Manager = diesel::r2d2::ConnectionManager<diesel::SqliteConnection>;
type Error = r2d2::Error; type Error = r2d2::Error;
fn pool(config: DatabaseConfig) -> Result<r2d2::Pool<Self::Manager>, Self::Error> { fn pool(config: DatabaseConfig<'_>) -> Result<r2d2::Pool<Self::Manager>, Self::Error> {
let manager = diesel::r2d2::ConnectionManager::new(config.url); let manager = diesel::r2d2::ConnectionManager::new(config.url);
r2d2::Pool::builder().max_size(config.pool_size).build(manager) r2d2::Pool::builder().max_size(config.pool_size).build(manager)
} }
@ -736,7 +736,7 @@ impl Poolable for diesel::PgConnection {
type Manager = diesel::r2d2::ConnectionManager<diesel::PgConnection>; type Manager = diesel::r2d2::ConnectionManager<diesel::PgConnection>;
type Error = r2d2::Error; type Error = r2d2::Error;
fn pool(config: DatabaseConfig) -> Result<r2d2::Pool<Self::Manager>, Self::Error> { fn pool(config: DatabaseConfig<'_>) -> Result<r2d2::Pool<Self::Manager>, Self::Error> {
let manager = diesel::r2d2::ConnectionManager::new(config.url); let manager = diesel::r2d2::ConnectionManager::new(config.url);
r2d2::Pool::builder().max_size(config.pool_size).build(manager) r2d2::Pool::builder().max_size(config.pool_size).build(manager)
} }
@ -747,7 +747,7 @@ impl Poolable for diesel::MysqlConnection {
type Manager = diesel::r2d2::ConnectionManager<diesel::MysqlConnection>; type Manager = diesel::r2d2::ConnectionManager<diesel::MysqlConnection>;
type Error = r2d2::Error; type Error = r2d2::Error;
fn pool(config: DatabaseConfig) -> Result<r2d2::Pool<Self::Manager>, Self::Error> { fn pool(config: DatabaseConfig<'_>) -> Result<r2d2::Pool<Self::Manager>, Self::Error> {
let manager = diesel::r2d2::ConnectionManager::new(config.url); let manager = diesel::r2d2::ConnectionManager::new(config.url);
r2d2::Pool::builder().max_size(config.pool_size).build(manager) r2d2::Pool::builder().max_size(config.pool_size).build(manager)
} }
@ -759,7 +759,7 @@ impl Poolable for postgres::Connection {
type Manager = r2d2_postgres::PostgresConnectionManager; type Manager = r2d2_postgres::PostgresConnectionManager;
type Error = DbError<postgres::Error>; type Error = DbError<postgres::Error>;
fn pool(config: DatabaseConfig) -> Result<r2d2::Pool<Self::Manager>, Self::Error> { fn pool(config: DatabaseConfig<'_>) -> Result<r2d2::Pool<Self::Manager>, Self::Error> {
let manager = r2d2_postgres::PostgresConnectionManager::new(config.url, r2d2_postgres::TlsMode::None) let manager = r2d2_postgres::PostgresConnectionManager::new(config.url, r2d2_postgres::TlsMode::None)
.map_err(DbError::Custom)?; .map_err(DbError::Custom)?;
@ -773,7 +773,7 @@ impl Poolable for mysql::Conn {
type Manager = r2d2_mysql::MysqlConnectionManager; type Manager = r2d2_mysql::MysqlConnectionManager;
type Error = r2d2::Error; type Error = r2d2::Error;
fn pool(config: DatabaseConfig) -> Result<r2d2::Pool<Self::Manager>, Self::Error> { fn pool(config: DatabaseConfig<'_>) -> Result<r2d2::Pool<Self::Manager>, Self::Error> {
let opts = mysql::OptsBuilder::from_opts(config.url); let opts = mysql::OptsBuilder::from_opts(config.url);
let manager = r2d2_mysql::MysqlConnectionManager::new(opts); let manager = r2d2_mysql::MysqlConnectionManager::new(opts);
r2d2::Pool::builder().max_size(config.pool_size).build(manager) r2d2::Pool::builder().max_size(config.pool_size).build(manager)
@ -785,7 +785,7 @@ impl Poolable for rusqlite::Connection {
type Manager = r2d2_sqlite::SqliteConnectionManager; type Manager = r2d2_sqlite::SqliteConnectionManager;
type Error = r2d2::Error; type Error = r2d2::Error;
fn pool(config: DatabaseConfig) -> Result<r2d2::Pool<Self::Manager>, Self::Error> { fn pool(config: DatabaseConfig<'_>) -> Result<r2d2::Pool<Self::Manager>, Self::Error> {
let manager = r2d2_sqlite::SqliteConnectionManager::file(config.url); let manager = r2d2_sqlite::SqliteConnectionManager::file(config.url);
r2d2::Pool::builder().max_size(config.pool_size).build(manager) r2d2::Pool::builder().max_size(config.pool_size).build(manager)
@ -797,7 +797,7 @@ impl Poolable for rusted_cypher::GraphClient {
type Manager = r2d2_cypher::CypherConnectionManager; type Manager = r2d2_cypher::CypherConnectionManager;
type Error = r2d2::Error; type Error = r2d2::Error;
fn pool(config: DatabaseConfig) -> Result<r2d2::Pool<Self::Manager>, Self::Error> { fn pool(config: DatabaseConfig<'_>) -> Result<r2d2::Pool<Self::Manager>, Self::Error> {
let manager = r2d2_cypher::CypherConnectionManager { url: config.url.to_string() }; let manager = r2d2_cypher::CypherConnectionManager { url: config.url.to_string() };
r2d2::Pool::builder().max_size(config.pool_size).build(manager) r2d2::Pool::builder().max_size(config.pool_size).build(manager)
} }
@ -808,7 +808,7 @@ impl Poolable for redis::Connection {
type Manager = r2d2_redis::RedisConnectionManager; type Manager = r2d2_redis::RedisConnectionManager;
type Error = DbError<redis::RedisError>; type Error = DbError<redis::RedisError>;
fn pool(config: DatabaseConfig) -> Result<r2d2::Pool<Self::Manager>, Self::Error> { fn pool(config: DatabaseConfig<'_>) -> Result<r2d2::Pool<Self::Manager>, Self::Error> {
let manager = r2d2_redis::RedisConnectionManager::new(config.url).map_err(DbError::Custom)?; let manager = r2d2_redis::RedisConnectionManager::new(config.url).map_err(DbError::Custom)?;
r2d2::Pool::builder().max_size(config.pool_size).build(manager) r2d2::Pool::builder().max_size(config.pool_size).build(manager)
.map_err(DbError::PoolError) .map_err(DbError::PoolError)
@ -820,7 +820,7 @@ impl Poolable for mongodb::db::Database {
type Manager = r2d2_mongodb::MongodbConnectionManager; type Manager = r2d2_mongodb::MongodbConnectionManager;
type Error = DbError<mongodb::Error>; type Error = DbError<mongodb::Error>;
fn pool(config: DatabaseConfig) -> Result<r2d2::Pool<Self::Manager>, Self::Error> { fn pool(config: DatabaseConfig<'_>) -> Result<r2d2::Pool<Self::Manager>, Self::Error> {
let manager = r2d2_mongodb::MongodbConnectionManager::new_with_uri(config.url).map_err(DbError::Custom)?; 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) r2d2::Pool::builder().max_size(config.pool_size).build(manager).map_err(DbError::PoolError)
} }
@ -831,7 +831,7 @@ impl Poolable for memcache::Client {
type Manager = r2d2_memcache::MemcacheConnectionManager; type Manager = r2d2_memcache::MemcacheConnectionManager;
type Error = DbError<memcache::MemcacheError>; type Error = DbError<memcache::MemcacheError>;
fn pool(config: DatabaseConfig) -> Result<r2d2::Pool<Self::Manager>, Self::Error> { fn pool(config: DatabaseConfig<'_>) -> Result<r2d2::Pool<Self::Manager>, Self::Error> {
let manager = r2d2_memcache::MemcacheConnectionManager::new(config.url); let manager = r2d2_memcache::MemcacheConnectionManager::new(config.url);
r2d2::Pool::builder().max_size(config.pool_size).build(manager).map_err(DbError::PoolError) r2d2::Pool::builder().max_size(config.pool_size).build(manager).map_err(DbError::PoolError)
} }

View File

@ -5,7 +5,7 @@ use rocket::http::uncased::UncasedStr;
use rocket::fairing::{Fairing, Info, Kind}; use rocket::fairing::{Fairing, Info, Kind};
use rocket::{Request, Response, Rocket}; use rocket::{Request, Response, Rocket};
use helmet::*; use crate::helmet::*;
/// A [`Fairing`](../../rocket/fairing/trait.Fairing.html) that adds HTTP /// A [`Fairing`](../../rocket/fairing/trait.Fairing.html) that adds HTTP
/// headers to outgoing responses that control security features on the browser. /// 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 /// Sets all of the headers in `self.policies` in `response` as long as the
/// header is not already in the response. /// 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() { for policy in self.policies.values() {
let name = policy.name(); let name = policy.name();
if response.headers().contains(name.as_str()) { 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); self.apply(response);
} }

View File

@ -103,8 +103,6 @@
//! //!
//! [OWASP]: https://www.owasp.org/index.php/OWASP_Secure_Headers_Project#tab=Headers //! [OWASP]: https://www.owasp.org/index.php/OWASP_Secure_Headers_Project#tab=Headers
extern crate time;
mod helmet; mod helmet;
mod policy; mod policy;

View File

@ -4,16 +4,16 @@ use std::borrow::Cow;
use rocket::http::{Header, uri::Uri, uncased::UncasedStr}; use rocket::http::{Header, uri::Uri, uncased::UncasedStr};
use helmet::time::Duration; use time::Duration;
/// Trait implemented by security and privacy policy headers. /// Trait implemented by security and privacy policy headers.
/// ///
/// Types that implement this trait can be [`enable()`]d and [`disable()`]d on /// Types that implement this trait can be [`enable()`]d and [`disable()`]d on
/// instances of [`SpaceHelmet`]. /// instances of [`SpaceHelmet`].
/// ///
/// [`SpaceHelmet`]: ::helmet::SpaceHelmet /// [`SpaceHelmet`]: crate::helmet::SpaceHelmet
/// [`enable()`]: ::helmet::SpaceHelmet::enable() /// [`enable()`]: crate::helmet::SpaceHelmet::enable()
/// [`disable()`]: ::helmet::SpaceHelmet::disable() /// [`disable()`]: crate::helmet::SpaceHelmet::disable()
pub trait Policy: Default + Send + Sync + 'static { pub trait Policy: Default + Send + Sync + 'static {
/// The actual name of the HTTP header. /// The actual name of the HTTP header.
/// ///
@ -151,8 +151,8 @@ impl Default for Referrer {
} }
} }
impl<'h, 'a> Into<Header<'h>> for &'a Referrer { impl Into<Header<'static>> for &Referrer {
fn into(self) -> Header<'h> { fn into(self) -> Header<'static> {
let policy_string = match self { let policy_string = match self {
Referrer::NoReferrer => "no-referrer", Referrer::NoReferrer => "no-referrer",
Referrer::NoReferrerWhenDowngrade => "no-referrer-when-downgrade", Referrer::NoReferrerWhenDowngrade => "no-referrer-when-downgrade",
@ -209,7 +209,7 @@ impl Default for ExpectCt {
} }
} }
impl<'a> Into<Header<'static>> for &'a ExpectCt { impl Into<Header<'static>> for &ExpectCt {
fn into(self) -> Header<'static> { fn into(self) -> Header<'static> {
let policy_string = match self { let policy_string = match self {
ExpectCt::Enforce(age) => format!("max-age={}, enforce", age.num_seconds()), ExpectCt::Enforce(age) => format!("max-age={}, enforce", age.num_seconds()),
@ -243,8 +243,8 @@ impl Default for NoSniff {
} }
} }
impl<'h, 'a> Into<Header<'h>> for &'a NoSniff { impl Into<Header<'static>> for &NoSniff {
fn into(self) -> Header<'h> { fn into(self) -> Header<'static> {
Header::new(NoSniff::NAME, "nosniff") Header::new(NoSniff::NAME, "nosniff")
} }
} }
@ -295,7 +295,7 @@ impl Default for Hsts {
} }
} }
impl<'a> Into<Header<'static>> for &'a Hsts { impl Into<Header<'static>> for &Hsts {
fn into(self) -> Header<'static> { fn into(self) -> Header<'static> {
let policy_string = match self { let policy_string = match self {
Hsts::Enable(age) => format!("max-age={}", age.num_seconds()), Hsts::Enable(age) => format!("max-age={}", age.num_seconds()),
@ -345,7 +345,7 @@ impl Default for Frame {
} }
} }
impl<'a> Into<Header<'static>> for &'a Frame { impl Into<Header<'static>> for &Frame {
fn into(self) -> Header<'static> { fn into(self) -> Header<'static> {
let policy_string: Cow<'static, str> = match self { let policy_string: Cow<'static, str> = match self {
Frame::Deny => "DENY".into(), Frame::Deny => "DENY".into(),
@ -387,7 +387,7 @@ impl Default for XssFilter {
} }
} }
impl<'a> Into<Header<'static>> for &'a XssFilter { impl Into<Header<'static>> for &XssFilter {
fn into(self) -> Header<'static> { fn into(self) -> Header<'static> {
let policy_string: Cow<'static, str> = match self { let policy_string: Cow<'static, str> = match self {
XssFilter::Disable => "0".into(), XssFilter::Disable => "0".into(),

View File

@ -14,9 +14,6 @@
//! features = ["json"] //! features = ["json"]
//! ``` //! ```
extern crate serde;
extern crate serde_json;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::io::{self, Read}; use std::io::{self, Read};
use std::iter::FromIterator; 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::response::{self, Responder, content};
use rocket::http::Status; use rocket::http::Status;
use self::serde::{Serialize, Serializer}; use serde::{Serialize, Serializer};
use self::serde::de::{Deserialize, Deserializer}; use serde::de::{Deserialize, Deserializer};
#[doc(hidden)] #[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 /// The JSON type: implements [`FromData`] and [`Responder`], allowing you to
/// easily consume and respond with JSON. /// easily consume and respond with JSON.
@ -136,7 +133,7 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for Json<T> {
type Owned = String; type Owned = String;
type Borrowed = str; type Borrowed = str;
fn transform(r: &Request, d: Data) -> Transform<Outcome<Self::Owned, Self::Error>> { fn transform(r: &Request<'_>, d: Data) -> Transform<Outcome<Self::Owned, Self::Error>> {
let size_limit = r.limits().get("json").unwrap_or(LIMIT); let size_limit = r.limits().get("json").unwrap_or(LIMIT);
let mut s = String::with_capacity(512); let mut s = String::with_capacity(512);
match d.open().take(size_limit).read_to_string(&mut s) { match d.open().take(size_limit).read_to_string(&mut s) {
@ -145,7 +142,7 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for Json<T> {
} }
} }
fn from_data(_: &Request, o: Transformed<'a, Self>) -> Outcome<Self, Self::Error> { fn from_data(_: &Request<'_>, o: Transformed<'a, Self>) -> Outcome<Self, Self::Error> {
let string = o.borrowed()?; let string = o.borrowed()?;
match serde_json::from_str(&string) { match serde_json::from_str(&string) {
Ok(v) => Success(Json(v)), Ok(v) => Success(Json(v)),
@ -165,7 +162,7 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for Json<T> {
/// JSON and a fixed-size body with the serialized value. If serialization /// JSON and a fixed-size body with the serialized value. If serialization
/// fails, an `Err` of `Status::InternalServerError` is returned. /// fails, an `Err` of `Status::InternalServerError` is returned.
impl<'a, T: Serialize> Responder<'a> for Json<T> { impl<'a, T: Serialize> Responder<'a> for Json<T> {
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| { serde_json::to_string(&self.0).map(|string| {
content::Json(string).respond_to(req).unwrap() content::Json(string).respond_to(req).unwrap()
}).map_err(|e| { }).map_err(|e| {
@ -288,7 +285,7 @@ impl<T> FromIterator<T> for JsonValue where serde_json::Value: FromIterator<T> {
/// and a fixed-size body with the serialized value. /// and a fixed-size body with the serialized value.
impl<'a> Responder<'a> for JsonValue { impl<'a> Responder<'a> for JsonValue {
#[inline] #[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) content::Json(self.0.to_string()).respond_to(req)
} }
} }

View File

@ -6,6 +6,9 @@
#![doc(html_favicon_url = "https://rocket.rs/v0.5/images/favicon.ico")] #![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")] #![doc(html_logo_url = "https://rocket.rs/v0.5/images/logo-boxed.png")]
#![warn(rust_2018_idioms)]
#![allow(unused_extern_crates)]
//! This crate contains officially sanctioned contributor libraries that provide //! This crate contains officially sanctioned contributor libraries that provide
//! functionality commonly used by Rocket applications. //! functionality commonly used by Rocket applications.
//! //!
@ -54,5 +57,4 @@
#[cfg(feature = "helmet")] pub mod helmet; #[cfg(feature = "helmet")] pub mod helmet;
#[cfg(any(feature="brotli_compression", feature="gzip_compression"))] pub mod compression; #[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::*; #[cfg(feature="databases")] #[doc(hidden)] pub use rocket_contrib_codegen::*;

View File

@ -1,6 +1,6 @@
//! Automatic MessagePack (de)serialization support. //! 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 //! # Enabling
//! //!
@ -13,8 +13,6 @@
//! default-features = false //! default-features = false
//! features = ["msgpack"] //! features = ["msgpack"]
//! ``` //! ```
extern crate serde;
extern crate rmp_serde;
use std::io::Read; use std::io::Read;
use std::ops::{Deref, DerefMut}; 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::response::{self, Responder, content};
use rocket::http::Status; use rocket::http::Status;
use self::serde::Serialize; use serde::Serialize;
use self::serde::de::Deserialize; 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 /// The `MsgPack` type: implements [`FromData`] and [`Responder`], allowing you
/// to easily consume and respond with MessagePack data. /// to easily consume and respond with MessagePack data.
@ -121,7 +119,7 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for MsgPack<T> {
type Owned = Vec<u8>; type Owned = Vec<u8>;
type Borrowed = [u8]; type Borrowed = [u8];
fn transform(r: &Request, d: Data) -> Transform<Outcome<Self::Owned, Self::Error>> { fn transform(r: &Request<'_>, d: Data) -> Transform<Outcome<Self::Owned, Self::Error>> {
let mut buf = Vec::new(); let mut buf = Vec::new();
let size_limit = r.limits().get("msgpack").unwrap_or(LIMIT); let size_limit = r.limits().get("msgpack").unwrap_or(LIMIT);
match d.open().take(size_limit).read_to_end(&mut buf) { match d.open().take(size_limit).read_to_end(&mut buf) {
@ -130,7 +128,7 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for MsgPack<T> {
} }
} }
fn from_data(_: &Request, o: Transformed<'a, Self>) -> Outcome<Self, Self::Error> { fn from_data(_: &Request<'_>, o: Transformed<'a, Self>) -> Outcome<Self, Self::Error> {
use self::Error::*; use self::Error::*;
let buf = o.borrowed()?; let buf = o.borrowed()?;
@ -153,7 +151,7 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for MsgPack<T> {
/// Content-Type `MsgPack` and a fixed-size body with the serialization. If /// Content-Type `MsgPack` and a fixed-size body with the serialization. If
/// serialization fails, an `Err` of `Status::InternalServerError` is returned. /// serialization fails, an `Err` of `Status::InternalServerError` is returned.
impl<T: Serialize> Responder<'static> for MsgPack<T> { impl<T: Serialize> Responder<'static> for MsgPack<T> {
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| { rmp_serde::to_vec(&self.0).map_err(|e| {
error_!("MsgPack failed to serialize: {:?}", e); error_!("MsgPack failed to serialize: {:?}", e);
Status::InternalServerError Status::InternalServerError

View File

@ -86,7 +86,7 @@ impl Default for Options {
} }
} }
impl ::std::ops::BitOr for Options { impl std::ops::BitOr for Options {
type Output = Self; type Output = Self;
#[inline(always)] #[inline(always)]
@ -272,8 +272,8 @@ impl Into<Vec<Route>> for StaticFiles {
} }
impl Handler for StaticFiles { impl Handler for StaticFiles {
fn handle<'r>(&self, req: &'r Request, _: Data) -> 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> { fn handle_index<'r>(opt: Options, r: &'r Request<'_>, path: &Path) -> Outcome<'r> {
if !opt.contains(Options::Index) { if !opt.contains(Options::Index) {
return Outcome::failure(Status::NotFound); return Outcome::failure(Status::NotFound);
} }
@ -292,7 +292,7 @@ impl Handler for StaticFiles {
// Otherwise, we're handling segments. Get the segments as a `PathBuf`, // Otherwise, we're handling segments. Get the segments as a `PathBuf`,
// only allowing dotfiles if the user allowed it. // only allowing dotfiles if the user allowed it.
let allow_dotfiles = self.options.contains(Options::DotFiles); let allow_dotfiles = self.options.contains(Options::DotFiles);
let path = req.get_segments::<Segments>(0) let path = req.get_segments::<Segments<'_>>(0)
.and_then(|res| res.ok()) .and_then(|res| res.ok())
.and_then(|segments| segments.into_path_buf(allow_dotfiles).ok()) .and_then(|segments| segments.into_path_buf(allow_dotfiles).ok())
.map(|path| self.root.join(path)) .map(|path| self.root.join(path))

View File

@ -1,7 +1,7 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::collections::HashMap; use std::collections::HashMap;
use templates::{glob, Engines, TemplateInfo}; use crate::templates::{Engines, TemplateInfo};
use rocket::http::ContentType; use rocket::http::ContentType;
@ -25,7 +25,7 @@ impl Context {
glob_path.set_extension(ext); glob_path.set_extension(ext);
let glob_path = glob_path.to_str().expect("valid glob path string"); 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); let (name, data_type_str) = split_path(&root, &path);
if let Some(info) = templates.get(&*name) { if let Some(info) = templates.get(&*name) {
warn_!("Template name '{}' does not have a unique path.", name); warn_!("Template name '{}' does not have a unique path.", name);

View File

@ -1,9 +1,11 @@
use std::collections::HashMap; use std::collections::HashMap;
use templates::{TemplateInfo, serde::Serialize}; use serde::Serialize;
#[cfg(feature = "tera_templates")] use templates::tera::Tera; use crate::templates::TemplateInfo;
#[cfg(feature = "handlebars_templates")] use templates::handlebars::Handlebars;
#[cfg(feature = "tera_templates")] use crate::templates::tera::Tera;
#[cfg(feature = "handlebars_templates")] use crate::templates::handlebars::Handlebars;
crate trait Engine: Send + Sync + 'static { crate trait Engine: Send + Sync + 'static {
const EXT: &'static str; const EXT: &'static str;
@ -40,8 +42,8 @@ crate trait Engine: Send + Sync + 'static {
/// # } /// # }
/// ``` /// ```
/// ///
/// [`tera::Value`]: ::templates::tera::Value /// [`tera::Value`]: crate::templates::tera::Value
/// [`tera::Result`]: ::templates::tera::Result /// [`tera::Result`]: crate::templates::tera::Result
pub struct Engines { pub struct Engines {
/// A `Tera` templating engine. This field is only available when the /// A `Tera` templating engine. This field is only available when the
/// `tera_templates` feature is enabled. When calling methods on the `Tera` /// `tera_templates` feature is enabled. When calling methods on the `Tera`

View File

@ -1,4 +1,4 @@
use templates::{DEFAULT_TEMPLATE_DIR, Context, Engines}; use crate::templates::{DEFAULT_TEMPLATE_DIR, Context, Engines};
use rocket::Rocket; use rocket::Rocket;
use rocket::config::ConfigError; use rocket::config::ConfigError;
@ -9,7 +9,7 @@ crate use self::context::ContextManager;
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
mod context { mod context {
use std::ops::Deref; use std::ops::Deref;
use templates::Context; use crate::templates::Context;
/// Wraps a Context. With `cfg(debug_assertions)` active, this structure /// Wraps a Context. With `cfg(debug_assertions)` active, this structure
/// additionally provides a method to reload the context at runtime. /// additionally provides a method to reload the context at runtime.
@ -32,15 +32,13 @@ mod context {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
mod context { mod context {
extern crate notify;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::sync::{RwLock, Mutex}; use std::sync::{RwLock, Mutex};
use std::sync::mpsc::{channel, Receiver}; 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 /// Wraps a Context. With `cfg(debug_assertions)` active, this structure
/// additionally provides a method to reload the context at runtime. /// additionally provides a method to reload the context at runtime.
@ -75,7 +73,7 @@ mod context {
} }
} }
crate fn context<'a>(&'a self) -> impl Deref<Target=Context> + 'a { crate fn context(&self) -> impl Deref<Target=Context> + '_ {
self.context.read().unwrap() self.context.read().unwrap()
} }
@ -83,7 +81,7 @@ mod context {
self.watcher.is_some() self.watcher.is_some()
} }
fn context_mut<'a>(&'a self) -> impl DerefMut<Target=Context> + 'a { fn context_mut(&self) -> impl DerefMut<Target=Context> + '_ {
self.context.write().unwrap() self.context.write().unwrap()
} }
@ -123,7 +121,7 @@ pub struct TemplateFairing {
/// The user-provided customization callback, allowing the use of /// The user-provided customization callback, allowing the use of
/// functionality specific to individual template engines. In debug mode, /// functionality specific to individual template engines. In debug mode,
/// this callback might be run multiple times as templates are reloaded. /// this callback might be run multiple times as templates are reloaded.
crate custom_callback: Box<Fn(&mut Engines) + Send + Sync + 'static>, crate custom_callback: Box<dyn Fn(&mut Engines) + Send + Sync + 'static>,
} }
impl Fairing for TemplateFairing { impl Fairing for TemplateFairing {
@ -165,8 +163,8 @@ impl Fairing for TemplateFairing {
} }
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
fn on_request(&self, req: &mut ::rocket::Request, _data: &::rocket::Data) { fn on_request(&self, req: &mut rocket::Request<'_>, _data: &rocket::Data) {
let cm = req.guard::<::rocket::State<ContextManager>>() let cm = req.guard::<rocket::State<'_, ContextManager>>()
.expect("Template ContextManager registered in on_attach"); .expect("Template ContextManager registered in on_attach");
cm.reload_if_needed(&*self.custom_callback); cm.reload_if_needed(&*self.custom_callback);

View File

@ -1,7 +1,8 @@
use templates::serde::Serialize; use serde::Serialize;
use templates::{Engine, TemplateInfo};
pub use templates::handlebars::Handlebars; use crate::templates::{Engine, TemplateInfo};
pub use crate::templates::handlebars::Handlebars;
impl Engine for Handlebars { impl Engine for Handlebars {
const EXT: &'static str = "hbs"; const EXT: &'static str = "hbs";

View File

@ -2,7 +2,7 @@ use rocket::{Request, State, Outcome};
use rocket::http::Status; use rocket::http::Status;
use rocket::request::{self, FromRequest}; use rocket::request::{self, FromRequest};
use templates::ContextManager; use crate::templates::ContextManager;
/// Request guard for dynamiclly querying template metadata. /// Request guard for dynamiclly querying template metadata.
/// ///
@ -39,7 +39,7 @@ use templates::ContextManager;
/// ``` /// ```
pub struct Metadata<'a>(&'a ContextManager); pub struct Metadata<'a>(&'a ContextManager);
impl<'a> Metadata<'a> { impl Metadata<'_> {
/// Returns `true` if the template with the given `name` is currently /// Returns `true` if the template with the given `name` is currently
/// loaded. Otherwise, returns `false`. /// loaded. Otherwise, returns `false`.
/// ///
@ -87,11 +87,11 @@ impl<'a> Metadata<'a> {
/// Retrieves the template metadata. If a template fairing hasn't been attached, /// Retrieves the template metadata. If a template fairing hasn't been attached,
/// an error is printed and an empty `Err` with status `InternalServerError` /// an error is printed and an empty `Err` with status `InternalServerError`
/// (`500`) is returned. /// (`500`) is returned.
impl<'a, 'r> FromRequest<'a, 'r> for Metadata<'a> { impl<'a> FromRequest<'a, '_> for Metadata<'a> {
type Error = (); type Error = ();
fn from_request(request: &'a Request) -> request::Outcome<Self, ()> { fn from_request(request: &'a Request<'_>) -> request::Outcome<Self, ()> {
request.guard::<State<ContextManager>>() request.guard::<State<'_, ContextManager>>()
.succeeded() .succeeded()
.and_then(|cm| Some(Outcome::Success(Metadata(cm.inner())))) .and_then(|cm| Some(Outcome::Success(Metadata(cm.inner()))))
.unwrap_or_else(|| { .unwrap_or_else(|| {

View File

@ -111,10 +111,6 @@
//! [`Template::custom()`]: templates::Template::custom() //! [`Template::custom()`]: templates::Template::custom()
//! [`Template::render()`]: templates::Template::render() //! [`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")] pub extern crate tera;
#[cfg(feature = "tera_templates")] mod tera_templates; #[cfg(feature = "tera_templates")] mod tera_templates;
@ -133,9 +129,9 @@ crate use self::fairing::ContextManager;
use self::engine::Engine; use self::engine::Engine;
use self::fairing::TemplateFairing; use self::fairing::TemplateFairing;
use self::serde::Serialize;
use self::serde_json::{Value, to_value}; use serde::Serialize;
use self::glob::glob; use serde_json::{Value, to_value};
use std::borrow::Cow; use std::borrow::Cow;
use std::path::PathBuf; use std::path::PathBuf;
@ -387,8 +383,8 @@ impl Template {
/// extension and a fixed-size body containing the rendered template. If /// extension and a fixed-size body containing the rendered template. If
/// rendering fails, an `Err` of `Status::InternalServerError` is returned. /// rendering fails, an `Err` of `Status::InternalServerError` is returned.
impl Responder<'static> for Template { impl Responder<'static> for Template {
fn respond_to(self, req: &Request) -> response::Result<'static> { fn respond_to(self, req: &Request<'_>) -> response::Result<'static> {
let ctxt = req.guard::<State<ContextManager>>().succeeded().ok_or_else(|| { let ctxt = req.guard::<State<'_, ContextManager>>().succeeded().ok_or_else(|| {
error_!("Uninitialized template context: missing fairing."); error_!("Uninitialized template context: missing fairing.");
info_!("To use templates, you must attach `Template::fairing()`."); info_!("To use templates, you must attach `Template::fairing()`.");
info_!("See the `Template` documentation for more information."); info_!("See the `Template` documentation for more information.");

View File

@ -1,7 +1,8 @@
use templates::serde::Serialize; use serde::Serialize;
use templates::{Engine, TemplateInfo};
pub use templates::tera::Tera; use crate::templates::{Engine, TemplateInfo};
pub use crate::templates::tera::Tera;
impl Engine for Tera { impl Engine for Tera {
const EXT: &'static str = "tera"; const EXT: &'static str = "tera";

View File

@ -95,7 +95,7 @@ impl Uuid {
impl fmt::Display for Uuid { impl fmt::Display for Uuid {
#[inline(always)] #[inline(always)]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f) self.0.fmt(f)
} }
} }
@ -127,7 +127,7 @@ impl FromStr for Uuid {
#[inline] #[inline]
fn from_str(s: &str) -> Result<Uuid, Self::Err> { fn from_str(s: &str) -> Result<Uuid, Self::Err> {
Ok(Uuid(try!(s.parse()))) s.parse().map(Uuid)
} }
} }

View File

@ -4,14 +4,8 @@
#[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))] #[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))]
extern crate rocket; extern crate rocket;
#[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))]
extern crate rocket_contrib;
#[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))] #[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))]
mod compress_responder_tests { mod compress_responder_tests {
extern crate brotli;
extern crate flate2;
use rocket::http::hyper::header::{ContentEncoding, Encoding}; use rocket::http::hyper::header::{ContentEncoding, Encoding};
use rocket::http::Status; use rocket::http::Status;
use rocket::http::{ContentType, Header}; use rocket::http::{ContentType, Header};
@ -22,7 +16,7 @@ mod compress_responder_tests {
use std::io::Cursor; use std::io::Cursor;
use std::io::Read; 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 \ 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. !"; in order to have to read more than one buffer when gzipping. !";

View File

@ -4,14 +4,8 @@
#[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))] #[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))]
extern crate rocket; extern crate rocket;
#[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))]
extern crate rocket_contrib;
#[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))] #[cfg(all(feature = "brotli_compression", feature = "gzip_compression"))]
mod compression_fairing_tests { mod compression_fairing_tests {
extern crate brotli;
extern crate flate2;
use rocket::config::{Config, Environment}; use rocket::config::{Config, Environment};
use rocket::http::hyper::header::{ContentEncoding, Encoding}; use rocket::http::hyper::header::{ContentEncoding, Encoding};
use rocket::http::Status; use rocket::http::Status;
@ -23,7 +17,7 @@ mod compression_fairing_tests {
use std::io::Cursor; use std::io::Cursor;
use std::io::Read; 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 \ 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. !"; in order to have to read more than one buffer when gzipping. !";

View File

@ -1,6 +1,3 @@
extern crate rocket;
extern crate rocket_contrib;
#[cfg(all(feature = "diesel_sqlite_pool", feature = "diesel_postgres_pool"))] #[cfg(all(feature = "diesel_sqlite_pool", feature = "diesel_postgres_pool"))]
mod databases_tests { mod databases_tests {
use rocket_contrib::databases::{database, diesel}; use rocket_contrib::databases::{database, diesel};
@ -20,7 +17,7 @@ mod rusqlite_integration_test {
use rocket_contrib::databases::rusqlite; use rocket_contrib::databases::rusqlite;
use rocket_contrib::database; use rocket_contrib::database;
use self::rusqlite::types::ToSql; use rusqlite::types::ToSql;
#[database("test_db")] #[database("test_db")]
struct SqliteDb(pub rusqlite::Connection); struct SqliteDb(pub rusqlite::Connection);

View File

@ -6,15 +6,11 @@ extern crate rocket;
#[cfg(feature = "helmet")] #[cfg(feature = "helmet")]
mod helmet_tests { mod helmet_tests {
extern crate time;
extern crate rocket_contrib;
use rocket;
use rocket::http::{Status, uri::Uri}; use rocket::http::{Status, uri::Uri};
use rocket::local::{Client, LocalResponse}; use rocket::local::{Client, LocalResponse};
use self::rocket_contrib::helmet::*; use rocket_contrib::helmet::*;
use self::time::Duration; use time::Duration;
#[get("/")] fn hello() { } #[get("/")] fn hello() { }
@ -47,7 +43,7 @@ mod helmet_tests {
#[test] #[test]
fn default_headers_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-XSS-Protection", "1");
assert_header!(response, "X-Frame-Options", "SAMEORIGIN"); assert_header!(response, "X-Frame-Options", "SAMEORIGIN");
assert_header!(response, "X-Content-Type-Options", "nosniff"); assert_header!(response, "X-Content-Type-Options", "nosniff");
@ -57,14 +53,14 @@ mod helmet_tests {
#[test] #[test]
fn disable_headers_test() { fn disable_headers_test() {
let helmet = SpaceHelmet::default().disable::<XssFilter>(); let helmet = SpaceHelmet::default().disable::<XssFilter>();
dispatch!(helmet, |response: LocalResponse| { dispatch!(helmet, |response: LocalResponse<'_>| {
assert_header!(response, "X-Frame-Options", "SAMEORIGIN"); assert_header!(response, "X-Frame-Options", "SAMEORIGIN");
assert_header!(response, "X-Content-Type-Options", "nosniff"); assert_header!(response, "X-Content-Type-Options", "nosniff");
assert_no_header!(response, "X-XSS-Protection"); assert_no_header!(response, "X-XSS-Protection");
}); });
let helmet = SpaceHelmet::default().disable::<Frame>(); let helmet = SpaceHelmet::default().disable::<Frame>();
dispatch!(helmet, |response: LocalResponse| { dispatch!(helmet, |response: LocalResponse<'_>| {
assert_header!(response, "X-XSS-Protection", "1"); assert_header!(response, "X-XSS-Protection", "1");
assert_header!(response, "X-Content-Type-Options", "nosniff"); assert_header!(response, "X-Content-Type-Options", "nosniff");
assert_no_header!(response, "X-Frame-Options"); assert_no_header!(response, "X-Frame-Options");
@ -75,13 +71,13 @@ mod helmet_tests {
.disable::<XssFilter>() .disable::<XssFilter>()
.disable::<NoSniff>(); .disable::<NoSniff>();
dispatch!(helmet, |response: LocalResponse| { dispatch!(helmet, |response: LocalResponse<'_>| {
assert_no_header!(response, "X-Frame-Options"); assert_no_header!(response, "X-Frame-Options");
assert_no_header!(response, "X-XSS-Protection"); assert_no_header!(response, "X-XSS-Protection");
assert_no_header!(response, "X-Content-Type-Options"); 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-Frame-Options");
assert_no_header!(response, "X-XSS-Protection"); assert_no_header!(response, "X-XSS-Protection");
assert_no_header!(response, "X-Content-Type-Options"); assert_no_header!(response, "X-Content-Type-Options");
@ -95,7 +91,7 @@ mod helmet_tests {
.enable(ExpectCt::default()) .enable(ExpectCt::default())
.enable(Referrer::default()); .enable(Referrer::default());
dispatch!(helmet, |response: LocalResponse| { dispatch!(helmet, |response: LocalResponse<'_>| {
assert_header!( assert_header!(
response, response,
"Strict-Transport-Security", "Strict-Transport-Security",
@ -123,7 +119,7 @@ mod helmet_tests {
.enable(XssFilter::EnableReport(report_uri)) .enable(XssFilter::EnableReport(report_uri))
.enable(ExpectCt::ReportAndEnforce(Duration::seconds(30), enforce_uri)); .enable(ExpectCt::ReportAndEnforce(Duration::seconds(30), enforce_uri));
dispatch!(helmet, |response: LocalResponse| { dispatch!(helmet, |response: LocalResponse<'_>| {
assert_header!(response, "X-Frame-Options", assert_header!(response, "X-Frame-Options",
"ALLOW-FROM https://www.google.com"); "ALLOW-FROM https://www.google.com");

View File

@ -1,8 +1,5 @@
#![feature(proc_macro_hygiene, decl_macro)] #![feature(proc_macro_hygiene, decl_macro)]
extern crate rocket;
extern crate rocket_contrib;
#[cfg(feature = "serve")] #[cfg(feature = "serve")]
mod static_tests { mod static_tests {
use std::{io::Read, fs::File}; use std::{io::Read, fs::File};

View File

@ -3,9 +3,6 @@
#[cfg(feature = "templates")] #[cfg(feature = "templates")]
#[macro_use] extern crate rocket; #[macro_use] extern crate rocket;
#[cfg(feature = "templates")]
extern crate rocket_contrib;
#[cfg(feature = "templates")] #[cfg(feature = "templates")]
mod templates_tests { mod templates_tests {
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -15,7 +12,7 @@ mod templates_tests {
use rocket_contrib::templates::{Template, Metadata}; use rocket_contrib::templates::{Template, Metadata};
#[get("/<engine>/<name>")] #[get("/<engine>/<name>")]
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)) { match md.contains_template(&format!("{}/{}", engine, name)) {
true => Some(()), true => Some(()),
false => None false => None
@ -23,7 +20,7 @@ mod templates_tests {
} }
#[get("/is_reloading")] #[get("/is_reloading")]
fn is_reloading(md: Metadata) -> Option<()> { fn is_reloading(md: Metadata<'_>) -> Option<()> {
if md.reloading() { Some(()) } else { None } if md.reloading() { Some(()) } else { None }
} }
@ -36,7 +33,7 @@ mod templates_tests {
.extra("template_dir", template_root().to_str().expect("template directory")) .extra("template_dir", template_root().to_str().expect("template directory"))
.expect("valid configuration"); .expect("valid configuration");
::rocket::custom(config).attach(Template::fairing()) rocket::custom(config).attach(Template::fairing())
.mount("/", routes![template_check, is_reloading]) .mount("/", routes![template_check, is_reloading])
} }