diff --git a/examples/handlers/async_handlers/src/main.rs b/examples/handlers/async_handlers/src/main.rs index a65fab64c..912868849 100644 --- a/examples/handlers/async_handlers/src/main.rs +++ b/examples/handlers/async_handlers/src/main.rs @@ -21,7 +21,7 @@ use gotham::state::{FromState, State}; type ResponseContentFuture = Pin, gotham::hyper::Error>> + Send>>; -#[derive(Deserialize, StateData, StaticResponseExtender)] +#[derive(Deserialize, StaticResponseExtender)] struct QueryStringExtractor { length: i8, } diff --git a/examples/handlers/multipart/src/main.rs b/examples/handlers/multipart/src/main.rs index 148cd1557..023529817 100644 --- a/examples/handlers/multipart/src/main.rs +++ b/examples/handlers/multipart/src/main.rs @@ -2,8 +2,8 @@ use futures::prelude::*; use gotham::handler::HandlerFuture; use gotham::helpers::http::response::create_response; -use gotham::hyper::header::CONTENT_TYPE; -use gotham::hyper::{body, Body, HeaderMap, StatusCode}; +use gotham::hyper::header::{HeaderMap, CONTENT_TYPE}; +use gotham::hyper::{body, Body, StatusCode}; use gotham::router::builder::{build_simple_router, DefineSingleRoute, DrawRoutes}; use gotham::router::Router; use gotham::state::{FromState, State}; @@ -15,7 +15,7 @@ use std::pin::Pin; /// Extracts the elements of the POST request and responds with the form keys and values fn form_handler(mut state: State) -> Pin> { const BOUNDARY: &str = "boundary="; - let header_map = HeaderMap::take_from(&mut state); + let header_map: HeaderMap = state.take(); let boundary = header_map .get(CONTENT_TYPE) .and_then(|ct| { diff --git a/examples/handlers/request_data/src/main.rs b/examples/handlers/request_data/src/main.rs index bfe5bc5da..4f85526bf 100644 --- a/examples/handlers/request_data/src/main.rs +++ b/examples/handlers/request_data/src/main.rs @@ -1,6 +1,7 @@ //! A basic example showing the request components use futures::prelude::*; -use gotham::hyper::{body, Body, HeaderMap, Method, Response, StatusCode, Uri, Version}; +use gotham::hyper::header::HeaderMap; +use gotham::hyper::{body, Body, Method, Response, StatusCode, Uri, Version}; use std::pin::Pin; use gotham::handler::HandlerFuture; @@ -14,7 +15,7 @@ fn print_request_elements(state: &State) { let method = Method::borrow_from(state); let uri = Uri::borrow_from(state); let http_version = Version::borrow_from(state); - let headers = HeaderMap::borrow_from(state); + let headers: &HeaderMap = state.borrow(); println!("Method: {:?}", method); println!("URI: {:?}", uri); println!("HTTP Version: {:?}", http_version); diff --git a/examples/handlers/simple_async_handlers/src/main.rs b/examples/handlers/simple_async_handlers/src/main.rs index 96e551184..69e91738b 100644 --- a/examples/handlers/simple_async_handlers/src/main.rs +++ b/examples/handlers/simple_async_handlers/src/main.rs @@ -21,7 +21,7 @@ use tokio::time::delay_until; type SleepFuture = Pin> + Send>>; -#[derive(Deserialize, StateData, StaticResponseExtender)] +#[derive(Deserialize, StaticResponseExtender)] struct QueryStringExtractor { seconds: u64, } diff --git a/examples/handlers/simple_async_handlers_await/src/main.rs b/examples/handlers/simple_async_handlers_await/src/main.rs index 567b48e09..343b6a7d1 100644 --- a/examples/handlers/simple_async_handlers_await/src/main.rs +++ b/examples/handlers/simple_async_handlers_await/src/main.rs @@ -12,14 +12,14 @@ use gotham::router::builder::DefineSingleRoute; use gotham::router::builder::{build_simple_router, DrawRoutes}; use gotham::router::Router; use gotham::state::{FromState, State}; -use gotham_derive::{StateData, StaticResponseExtender}; +use gotham_derive::StaticResponseExtender; use serde_derive::Deserialize; use tokio::time::delay_until; type SleepFuture = Pin> + Send>>; -#[derive(Deserialize, StateData, StaticResponseExtender)] +#[derive(Deserialize, StaticResponseExtender)] struct QueryStringExtractor { seconds: u64, } diff --git a/examples/middleware/introduction/src/main.rs b/examples/middleware/introduction/src/main.rs index 6b5f24440..ffb18cd74 100644 --- a/examples/middleware/introduction/src/main.rs +++ b/examples/middleware/introduction/src/main.rs @@ -19,7 +19,6 @@ use gotham::state::{FromState, State}; /// A simple struct which holds an identifier for the user agent which made the request. /// /// It is created by our Middleware and then accessed via `state` by both our Middleware and Handler. -#[derive(StateData)] pub struct ExampleMiddlewareData { pub user_agent: String, pub supported: bool, @@ -50,7 +49,8 @@ impl Middleware for ExampleMiddleware { where Chain: FnOnce(State) -> Pin>, { - let user_agent = match HeaderMap::borrow_from(&state).get(USER_AGENT) { + let header_map: HeaderMap = state.take(); + let user_agent = match header_map.get(USER_AGENT) { Some(ua) => ua.to_str().unwrap().to_string(), None => "None".to_string(), }; diff --git a/examples/middleware/multiple_pipelines/src/main.rs b/examples/middleware/multiple_pipelines/src/main.rs index f1669bdb7..643d48a1a 100644 --- a/examples/middleware/multiple_pipelines/src/main.rs +++ b/examples/middleware/multiple_pipelines/src/main.rs @@ -29,7 +29,7 @@ use gotham::pipeline::set::{finalize_pipeline_set, new_pipeline_set}; use gotham::pipeline::single::single_pipeline; use gotham::router::builder::*; use gotham::router::Router; -use gotham::state::{FromState, State}; +use gotham::state::State; /// A simple struct to represent our default session data. #[derive(Default, Serialize, Deserialize)] @@ -50,11 +50,12 @@ pub struct ApiMiddleware; /// Our example API middleware will reject any requests that /// don't accept JSON as the response content type. impl Middleware for ApiMiddleware { - fn call(self, state: State, chain: Chain) -> Pin> + fn call(self, mut state: State, chain: Chain) -> Pin> where Chain: FnOnce(State) -> Pin> + 'static, { - let accepts = HeaderMap::borrow_from(&state) + let header_map: HeaderMap = state.take(); + let accepts = header_map .get(ACCEPT) .map(|ct| ct.to_str().unwrap().to_string()); diff --git a/examples/path/globs/src/main.rs b/examples/path/globs/src/main.rs index 5c347044a..062aa59a6 100644 --- a/examples/path/globs/src/main.rs +++ b/examples/path/globs/src/main.rs @@ -8,19 +8,19 @@ use gotham::router::builder::*; use gotham::router::Router; use gotham::state::{FromState, State}; -#[derive(Deserialize, StateData, StaticResponseExtender)] +#[derive(Deserialize, StaticResponseExtender)] struct PathExtractor { // This will be a Vec containing each path segment as a separate String, with no '/'s. #[serde(rename = "*")] parts: Vec, } -#[derive(Deserialize, StateData, StaticResponseExtender)] +#[derive(Deserialize, StaticResponseExtender)] struct NamedPathExtractor { parts: Vec, } -#[derive(Deserialize, StateData, StaticResponseExtender)] +#[derive(Deserialize, StaticResponseExtender)] struct MultiGlobExtractor { top: Vec, bottom: Vec, diff --git a/examples/path/introduction/src/main.rs b/examples/path/introduction/src/main.rs index a28304519..e09cc6dcd 100644 --- a/examples/path/introduction/src/main.rs +++ b/examples/path/introduction/src/main.rs @@ -22,10 +22,7 @@ use gotham::state::{FromState, State}; /// deriving it. The Gotham router uses this property during Request path evaluation to /// create and instance of your struct, populate it and store it into state ready for /// access by application code. -/// 2. That the struct implements `gotham::state::data::StateData` so that it can be stored, -/// retrieved and removed from state. You generally get this for free by deriving -/// `StateData` as shown here. -/// 3. That the struct implements the +/// 2. That the struct implements the /// `gotham::router::response::extender::StaticResponseExtender` trait so that bad request /// path data can be appropriately refused by the Router. You generally get this for free by /// deriving `StaticResponseExtender` as shown here which results in bad requests being @@ -33,7 +30,7 @@ use gotham::state::{FromState, State}; /// /// Naming of fields in extraction structs is important, the same names must appear in the path, /// proceeded by a colon to indicate a variable, when defining routes. -#[derive(Deserialize, StateData, StaticResponseExtender)] +#[derive(Deserialize, StaticResponseExtender)] struct PathExtractor { name: String, } diff --git a/examples/path/regex/src/main.rs b/examples/path/regex/src/main.rs index 11a5c0816..1b26cad0e 100644 --- a/examples/path/regex/src/main.rs +++ b/examples/path/regex/src/main.rs @@ -8,7 +8,7 @@ use gotham::router::builder::*; use gotham::router::Router; use gotham::state::{FromState, State}; -#[derive(Deserialize, StateData, StaticResponseExtender)] +#[derive(Deserialize, StaticResponseExtender)] struct PathExtractor { id: usize, } diff --git a/examples/query_string/introduction/src/main.rs b/examples/query_string/introduction/src/main.rs index d03bfcb42..f9800dde1 100644 --- a/examples/query_string/introduction/src/main.rs +++ b/examples/query_string/introduction/src/main.rs @@ -22,10 +22,7 @@ use gotham::state::{FromState, State}; /// simply deriving it. The Gotham router uses this property during Request query string /// evaluation to create and instance of your struct, populate it and store it into state /// ready for access by application code. -/// 2. That the struct implements `gotham::state::data::StateData` trait so that it can be -/// stored, retrieved and removed from state. You generally get this for free by deriving -/// `StateData` as shown here. -/// 3. That the struct implements the +/// 2. That the struct implements the /// `gotham::router::response::extender::StaticResponseExtender` trait so that bad request /// query string data can be appropriately refused by the Router. You generally get this /// for free by deriving `StaticResponseExtender` as shown here which results in bad @@ -33,7 +30,7 @@ use gotham::state::{FromState, State}; /// /// Naming of fields in extraction structs is important, the same names must appear in the /// query string. -#[derive(Deserialize, StateData, StaticResponseExtender)] +#[derive(Deserialize, StaticResponseExtender)] struct QueryStringExtractor { name: String, } diff --git a/examples/sessions/custom_data_type/src/main.rs b/examples/sessions/custom_data_type/src/main.rs index 5bfa83d19..40d04305c 100644 --- a/examples/sessions/custom_data_type/src/main.rs +++ b/examples/sessions/custom_data_type/src/main.rs @@ -1,8 +1,6 @@ //! Storing and retrieving session data with a custom data type, in a type safe //! way, with the Gotham web framework. #[macro_use] -extern crate gotham_derive; -#[macro_use] extern crate serde_derive; use gotham::middleware::session::{NewSessionMiddleware, SessionData}; @@ -13,7 +11,7 @@ use gotham::router::Router; use gotham::state::{FromState, State}; // A custom type for storing data associated with the user's session. -#[derive(Clone, Deserialize, Serialize, StateData)] +#[derive(Clone, Deserialize, Serialize)] struct VisitData { count: usize, last_visit: String, diff --git a/examples/shared_state/src/main.rs b/examples/shared_state/src/main.rs index e1d37ec82..72be65fd7 100644 --- a/examples/shared_state/src/main.rs +++ b/examples/shared_state/src/main.rs @@ -6,9 +6,6 @@ #![cfg_attr(feature = "cargo-clippy", allow(clippy::mutex_atomic))] -#[macro_use] -extern crate gotham_derive; - use gotham::middleware::state::StateMiddleware; use gotham::pipeline::single::single_pipeline; use gotham::pipeline::single_middleware; @@ -26,7 +23,7 @@ use std::sync::{Arc, Mutex}; /// /// This struct must implement `Clone` and `StateData` to be applicable /// for use with the `StateMiddleware`, and be shared via `Middleware`. -#[derive(Clone, StateData)] +#[derive(Clone)] struct RequestCounter { inner: Arc>, } diff --git a/gotham/src/extractor/path.rs b/gotham/src/extractor/path.rs index dd9b77cde..91a043396 100644 --- a/gotham/src/extractor/path.rs +++ b/gotham/src/extractor/path.rs @@ -1,8 +1,9 @@ use hyper::{body::HttpBody, Body, Response}; use serde::{Deserialize, Deserializer}; +use std::any::Any; use crate::router::response::extender::StaticResponseExtender; -use crate::state::{State, StateData}; +use crate::state::State; /// Defines a binding for storing the dynamic segments of the `Request` path in `State`. On failure /// the `StaticResponseExtender` implementation extends the `Response` to indicate why the @@ -35,7 +36,7 @@ use crate::state::{State, StateData}; /// # use gotham::router::builder::*; /// # use gotham::test::TestServer; /// # -/// #[derive(Deserialize, StateData, StaticResponseExtender)] +/// #[derive(Deserialize, StaticResponseExtender)] /// struct MyPathParams { /// id: i32, /// slug: String, @@ -76,7 +77,7 @@ use crate::state::{State, StateData}; /// # assert_eq!(body, "id = 1551, slug = ten-reasons-serde-is-amazing"); /// # } pub trait PathExtractor: - for<'de> Deserialize<'de> + StaticResponseExtender + StateData + for<'de> Deserialize<'de> + StaticResponseExtender + Any + Send where B: HttpBody, { @@ -85,7 +86,7 @@ where impl PathExtractor for T where B: HttpBody, - for<'de> T: Deserialize<'de> + StaticResponseExtender + StateData, + for<'de> T: Deserialize<'de> + StaticResponseExtender + Any + Send, { } @@ -107,8 +108,6 @@ impl<'de> Deserialize<'de> for NoopPathExtractor { } } -impl StateData for NoopPathExtractor {} - impl StaticResponseExtender for NoopPathExtractor { type ResBody = Body; fn extend(_state: &mut State, _res: &mut Response) {} diff --git a/gotham/src/extractor/query_string.rs b/gotham/src/extractor/query_string.rs index f9341ad03..cce50b773 100644 --- a/gotham/src/extractor/query_string.rs +++ b/gotham/src/extractor/query_string.rs @@ -1,8 +1,9 @@ use hyper::{body::HttpBody, Body, Response}; use serde::{Deserialize, Deserializer}; +use std::any::Any; use crate::router::response::extender::StaticResponseExtender; -use crate::state::{State, StateData}; +use crate::state::State; /// Defines a binding for storing the query parameters from the `Request` URI in `State`. On /// failure the `StaticResponseExtender` implementation extends the `Response` to indicate why the @@ -35,7 +36,7 @@ use crate::state::{State, StateData}; /// # use gotham::router::builder::*; /// # use gotham::test::TestServer; /// # -/// #[derive(Deserialize, StateData, StaticResponseExtender)] +/// #[derive(Deserialize, StaticResponseExtender)] /// struct MyQueryParams { /// x: i32, /// y: MyEnum, @@ -84,7 +85,7 @@ use crate::state::{State, StateData}; /// # assert_eq!(body, "x = 15, y = B"); /// # } pub trait QueryStringExtractor: - for<'de> Deserialize<'de> + StaticResponseExtender + StateData + for<'de> Deserialize<'de> + StaticResponseExtender + Any + Send where B: HttpBody, { @@ -93,7 +94,7 @@ where impl QueryStringExtractor for T where B: HttpBody, - for<'de> T: Deserialize<'de> + StaticResponseExtender + StateData, + for<'de> T: Deserialize<'de> + StaticResponseExtender + Any + Send, { } @@ -117,8 +118,6 @@ impl<'de> Deserialize<'de> for NoopQueryStringExtractor { } } -impl StateData for NoopQueryStringExtractor {} - impl StaticResponseExtender for NoopQueryStringExtractor { type ResBody = Body; fn extend(_state: &mut State, _res: &mut Response) {} diff --git a/gotham/src/handler/assets/mod.rs b/gotham/src/handler/assets/mod.rs index 2eed61bc2..bbe116d8a 100644 --- a/gotham/src/handler/assets/mod.rs +++ b/gotham/src/handler/assets/mod.rs @@ -24,7 +24,7 @@ use tokio::io::AsyncRead; use self::accepted_encoding::accepted_encodings; use crate::handler::{Handler, HandlerError, HandlerFuture, NewHandler}; use crate::router::response::extender::StaticResponseExtender; -use crate::state::{FromState, State, StateData}; +use crate::state::{FromState, State}; use std::cmp; use std::convert::From; @@ -358,8 +358,6 @@ pub struct FilePathExtractor { parts: Vec, } -impl StateData for FilePathExtractor {} - impl StaticResponseExtender for FilePathExtractor { type ResBody = Body; fn extend(_state: &mut State, _res: &mut Response) {} diff --git a/gotham/src/middleware/mod.rs b/gotham/src/middleware/mod.rs index 17a54ad83..4947f23b5 100644 --- a/gotham/src/middleware/mod.rs +++ b/gotham/src/middleware/mod.rs @@ -99,7 +99,6 @@ pub mod timer; /// #[derive(NewMiddleware, Copy, Clone)] /// struct MiddlewareWithStateData; /// -/// #[derive(StateData)] /// struct MiddlewareStateData { /// i: i32, /// } diff --git a/gotham/src/middleware/session/mod.rs b/gotham/src/middleware/session/mod.rs index 55580cfe7..99ba7747c 100644 --- a/gotham/src/middleware/session/mod.rs +++ b/gotham/src/middleware/session/mod.rs @@ -21,7 +21,7 @@ use super::cookie::CookieParser; use super::{Middleware, NewMiddleware}; use crate::handler::{HandlerError, HandlerFuture}; use crate::helpers::http::response::create_empty_response; -use crate::state::{self, FromState, State, StateData}; +use crate::state::{self, FromState, State}; mod backend; mod rng; @@ -372,11 +372,6 @@ where } } -impl StateData for SessionData where - T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static -{ -} - impl Deref for SessionData where T: Default + Serialize + for<'de> Deserialize<'de> + Send + 'static, @@ -398,8 +393,6 @@ where } } -impl StateData for SessionDropData {} - trait SessionTypePhantom: Send + Sync + RefUnwindSafe where T: Send, diff --git a/gotham/src/middleware/state/mod.rs b/gotham/src/middleware/state/mod.rs index 95ae1f78c..a10d17050 100644 --- a/gotham/src/middleware/state/mod.rs +++ b/gotham/src/middleware/state/mod.rs @@ -6,7 +6,8 @@ //! value to attach to the request state. use crate::handler::HandlerFuture; use crate::middleware::{Middleware, NewMiddleware}; -use crate::state::{State, StateData}; +use crate::state::State; +use std::any::Any; use std::panic::RefUnwindSafe; use std::pin::Pin; @@ -21,7 +22,7 @@ use std::pin::Pin; #[derive(Clone)] pub struct StateMiddleware where - T: Clone + RefUnwindSafe + StateData + Sync, + T: Clone + RefUnwindSafe + Any + Send + Sync, { t: T, } @@ -29,7 +30,7 @@ where /// Main implementation. impl StateMiddleware where - T: Clone + RefUnwindSafe + StateData + Sync, + T: Clone + RefUnwindSafe + Any + Send + Sync, { /// Creates a new middleware binding, taking ownership of the state data. pub fn new(t: T) -> Self { @@ -40,7 +41,7 @@ where /// `Middleware` trait implementation. impl Middleware for StateMiddleware where - T: Clone + RefUnwindSafe + StateData + Sync, + T: Clone + RefUnwindSafe + Any + Send + Sync, { /// Attaches the inner generic value to the request state. /// @@ -57,7 +58,7 @@ where /// `NewMiddleware` trait implementation. impl NewMiddleware for StateMiddleware where - T: Clone + RefUnwindSafe + StateData + Sync, + T: Clone + RefUnwindSafe + Any + Send + Sync, { type Instance = Self; diff --git a/gotham/src/pipeline/mod.rs b/gotham/src/pipeline/mod.rs index 71d883d1c..65160f01a 100644 --- a/gotham/src/pipeline/mod.rs +++ b/gotham/src/pipeline/mod.rs @@ -40,7 +40,6 @@ use crate::state::{request_id, State}; /// # use gotham::test::TestServer; /// # use hyper::{Body, Response, StatusCode}; /// # -/// #[derive(StateData)] /// struct MiddlewareData { /// vec: Vec /// } @@ -296,7 +295,6 @@ mod tests { use crate::handler::Handler; use crate::middleware::Middleware; - use crate::state::StateData; use crate::test::TestServer; fn handler(state: State) -> (State, Response) { @@ -334,8 +332,6 @@ mod tests { } } - impl StateData for Number {} - struct Addition { value: i32, } diff --git a/gotham/src/router/builder/associated.rs b/gotham/src/router/builder/associated.rs index d370d7bfc..13ea14c9d 100644 --- a/gotham/src/router/builder/associated.rs +++ b/gotham/src/router/builder/associated.rs @@ -156,7 +156,7 @@ where /// # (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap()) /// } /// - /// #[derive(Deserialize, StateData, StaticResponseExtender)] + /// #[derive(Deserialize, StaticResponseExtender)] /// struct MyPathExtractor { /// # #[allow(dead_code)] /// id: u32, @@ -221,7 +221,7 @@ where /// # (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap()) /// } /// - /// #[derive(StateData, Deserialize, StaticResponseExtender)] + /// #[derive(Deserialize, StaticResponseExtender)] /// struct MyQueryStringExtractor { /// # #[allow(dead_code)] /// val: String, diff --git a/gotham/src/router/builder/mod.rs b/gotham/src/router/builder/mod.rs index a31d84fe1..da75a6365 100644 --- a/gotham/src/router/builder/mod.rs +++ b/gotham/src/router/builder/mod.rs @@ -341,15 +341,13 @@ mod tests { use crate::pipeline::new_pipeline; use crate::router::response::extender::StaticResponseExtender; use crate::service::GothamService; - use crate::state::{State, StateData}; + use crate::state::State; #[derive(Deserialize)] struct SalutationParams { name: String, } - impl StateData for SalutationParams {} - impl StaticResponseExtender for SalutationParams { type ResBody = Body; fn extend(_: &mut State, _: &mut Response) {} @@ -361,8 +359,6 @@ mod tests { y: u64, } - impl StateData for AddParams {} - impl StaticResponseExtender for AddParams { type ResBody = Body; fn extend(_: &mut State, _: &mut Response) {} diff --git a/gotham/src/router/builder/single.rs b/gotham/src/router/builder/single.rs index 55e241a99..9ef81a5d1 100644 --- a/gotham/src/router/builder/single.rs +++ b/gotham/src/router/builder/single.rs @@ -440,7 +440,7 @@ pub trait DefineSingleRoute { /// # use gotham::middleware::session::NewSessionMiddleware; /// # use gotham::test::TestServer; /// # - /// #[derive(Deserialize, StateData, StaticResponseExtender)] + /// #[derive(Deserialize, StaticResponseExtender)] /// struct MyPathParams { /// # #[allow(dead_code)] /// name: String, @@ -510,7 +510,7 @@ pub trait DefineSingleRoute { /// # use gotham::middleware::session::NewSessionMiddleware; /// # use gotham::test::TestServer; /// # - /// #[derive(StateData, Deserialize, StaticResponseExtender)] + /// #[derive(Deserialize, StaticResponseExtender)] /// struct MyQueryParams { /// # #[allow(dead_code)] /// id: u64, diff --git a/gotham/src/router/route/dispatch.rs b/gotham/src/router/route/dispatch.rs index de4e647f7..34a6bfba9 100644 --- a/gotham/src/router/route/dispatch.rs +++ b/gotham/src/router/route/dispatch.rs @@ -83,7 +83,6 @@ mod tests { use crate::middleware::{Middleware, NewMiddleware}; use crate::pipeline::new_pipeline; use crate::pipeline::set::*; - use crate::state::StateData; use crate::test::TestServer; fn handler(state: State) -> (State, Response) { @@ -121,8 +120,6 @@ mod tests { } } - impl StateData for Number {} - struct Addition { value: i32, } diff --git a/gotham/src/router/route/matcher/accept.rs b/gotham/src/router/route/matcher/accept.rs index be05bfd9c..83ded4a8d 100644 --- a/gotham/src/router/route/matcher/accept.rs +++ b/gotham/src/router/route/matcher/accept.rs @@ -9,7 +9,7 @@ use mime::Mime; use super::{LookupTable, LookupTableFromTypes}; use crate::router::route::RouteMatcher; use crate::router::RouteNonMatch; -use crate::state::{request_id, FromState, State}; +use crate::state::{request_id, State}; /// A mime type that is optionally weighted with a quality. struct QMime { @@ -135,7 +135,8 @@ impl RouteMatcher for AcceptHeaderRouteMatcher { /// Quality values within `Accept` header values are not considered by the matcher, as the /// matcher is only able to indicate whether a successful match has been found. fn is_match(&self, state: &State) -> Result<(), RouteNonMatch> { - HeaderMap::borrow_from(state) + let header_map: &HeaderMap = state.borrow(); + header_map .get(ACCEPT) .map(|header| { // parse mime types from the accept header diff --git a/gotham/src/router/route/matcher/access_control_request_method.rs b/gotham/src/router/route/matcher/access_control_request_method.rs index 5bc87120f..c813e51a7 100644 --- a/gotham/src/router/route/matcher/access_control_request_method.rs +++ b/gotham/src/router/route/matcher/access_control_request_method.rs @@ -2,7 +2,7 @@ use crate::{ router::{non_match::RouteNonMatch, route::matcher::RouteMatcher}, - state::{FromState, State}, + state::State, }; use hyper::{ header::{HeaderMap, ACCESS_CONTROL_REQUEST_METHOD}, @@ -51,7 +51,8 @@ impl RouteMatcher for AccessControlRequestMethodMatcher { fn is_match(&self, state: &State) -> Result<(), RouteNonMatch> { // according to the fetch specification, methods should be normalized by byte-uppercase // https://fetch.spec.whatwg.org/#concept-method - match HeaderMap::borrow_from(state) + let header_map: &HeaderMap = state.borrow(); + match header_map .get(ACCESS_CONTROL_REQUEST_METHOD) .and_then(|value| value.to_str().ok()) .and_then(|str| str.to_ascii_uppercase().parse::().ok()) diff --git a/gotham/src/router/route/matcher/content_type.rs b/gotham/src/router/route/matcher/content_type.rs index 4fd3e6098..2c2201464 100644 --- a/gotham/src/router/route/matcher/content_type.rs +++ b/gotham/src/router/route/matcher/content_type.rs @@ -9,7 +9,7 @@ use mime::Mime; use super::{LookupTable, LookupTableFromTypes}; use crate::router::route::RouteMatcher; use crate::router::RouteNonMatch; -use crate::state::{request_id, FromState, State}; +use crate::state::{request_id, State}; /// A `RouteMatcher` that succeeds when the `Request` has been made with a `Content-Type` header /// that includes a supported media type. The matcher will fail if the Content-Type @@ -98,7 +98,8 @@ impl RouteMatcher for ContentTypeHeaderRouteMatcher { /// Determines if the `Request` was made using a `Content-Type` header that includes a /// supported media type. fn is_match(&self, state: &State) -> Result<(), RouteNonMatch> { - HeaderMap::borrow_from(state) + let header_map: &HeaderMap = state.borrow(); + header_map .get(CONTENT_TYPE) .map(|ty| { // parse mime type from the content type header diff --git a/gotham/src/state/client_addr.rs b/gotham/src/state/client_addr.rs index 4f706fff2..5037030fe 100644 --- a/gotham/src/state/client_addr.rs +++ b/gotham/src/state/client_addr.rs @@ -1,14 +1,12 @@ //! Defines storage for the remote address of the client -use crate::state::{FromState, State, StateData}; +use crate::state::{FromState, State}; use std::net::SocketAddr; struct ClientAddr { addr: SocketAddr, } -impl StateData for ClientAddr {} - pub(crate) fn put_client_addr(state: &mut State, addr: SocketAddr) { state.put(ClientAddr { addr }) } diff --git a/gotham/src/state/data.rs b/gotham/src/state/data.rs deleted file mode 100644 index 603460e50..000000000 --- a/gotham/src/state/data.rs +++ /dev/null @@ -1,42 +0,0 @@ -use std::any::Any; - -use cookie::CookieJar; -use hyper::{Body, HeaderMap, Method, Uri, Version}; - -use crate::helpers::http::request::path::RequestPathSegments; -use crate::state::request_id::RequestId; - -/// A marker trait for types that can be stored in `State`. -/// -/// This is typically implemented using `#[derive(StateData)]`, which is provided by the -/// `gotham_derive` crate. -/// -/// ```rust -/// # extern crate gotham; -/// # #[macro_use] -/// # extern crate gotham_derive; -/// # -/// # use gotham::state::{FromState, State}; -/// # -/// #[derive(StateData)] -/// struct MyStateData { -/// x: u32, -/// } -/// # fn main() { -/// # State::with_new(|state| { -/// # state.put(MyStateData { x: 1 }); -/// # assert_eq!(MyStateData::borrow_from(state).x, 1); -/// # }); -/// # } -/// ``` -pub trait StateData: Any + Send {} - -impl StateData for Body {} -impl StateData for Method {} -impl StateData for Uri {} -impl StateData for Version {} -impl StateData for HeaderMap {} -impl StateData for CookieJar {} - -impl StateData for RequestPathSegments {} -impl StateData for RequestId {} diff --git a/gotham/src/state/from_state.rs b/gotham/src/state/from_state.rs index 98584932b..1f2d7537e 100644 --- a/gotham/src/state/from_state.rs +++ b/gotham/src/state/from_state.rs @@ -1,23 +1,22 @@ -use crate::state::{State, StateData}; +use crate::state::State; +use std::any::Any; /// A trait for accessing data that is stored in `State`. /// /// This provides the easier `T::try_borrow_from(&state)` API (for example), as an alternative to /// `state.try_borrow::()`. -pub trait FromState: StateData + Sized { +pub trait FromState: Any + Send + Sized { /// Tries to borrow a value from the `State` storage. /// /// # Examples /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::{FromState, State}; /// # /// # fn main() { - /// #[derive(StateData, Eq, PartialEq, Debug)] + /// #[derive(Eq, PartialEq, Debug)] /// struct MyStruct { /// val: &'static str, /// } @@ -44,13 +43,11 @@ pub trait FromState: StateData + Sized { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::{FromState, State}; /// # /// # fn main() { - /// #[derive(StateData, Eq, PartialEq, Debug)] + /// #[derive(Eq, PartialEq, Debug)] /// struct MyStruct { /// val: &'static str, /// } @@ -71,13 +68,11 @@ pub trait FromState: StateData + Sized { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::{FromState, State}; /// # /// # fn main() { - /// #[derive(StateData, Eq, PartialEq, Debug)] + /// #[derive(Eq, PartialEq, Debug)] /// struct MyStruct { /// val: &'static str, /// } @@ -106,13 +101,11 @@ pub trait FromState: StateData + Sized { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::{FromState, State}; /// # /// # fn main() { - /// #[derive(StateData, Eq, PartialEq, Debug)] + /// #[derive(Eq, PartialEq, Debug)] /// struct MyStruct { /// val: &'static str, /// } @@ -136,13 +129,11 @@ pub trait FromState: StateData + Sized { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::{FromState, State}; /// # /// # fn main() { - /// #[derive(StateData, Eq, PartialEq, Debug)] + /// #[derive(Eq, PartialEq, Debug)] /// struct MyStruct { /// val: &'static str, /// } @@ -169,13 +160,11 @@ pub trait FromState: StateData + Sized { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::{FromState, State}; /// # /// # fn main() { - /// #[derive(StateData, Eq, PartialEq, Debug)] + /// #[derive(Eq, PartialEq, Debug)] /// struct MyStruct { /// val: &'static str, /// } @@ -193,7 +182,7 @@ pub trait FromState: StateData + Sized { impl FromState for T where - T: StateData, + T: Any + Send, { fn try_borrow_from(state: &State) -> Option<&Self> { state.try_borrow() diff --git a/gotham/src/state/mod.rs b/gotham/src/state/mod.rs index 425d5fb93..9f3691da9 100644 --- a/gotham/src/state/mod.rs +++ b/gotham/src/state/mod.rs @@ -1,7 +1,6 @@ //! Defines types for passing request state through `Middleware` and `Handler` implementations pub(crate) mod client_addr; -mod data; mod from_state; pub mod request_id; @@ -11,7 +10,6 @@ use std::any::{Any, TypeId}; use std::collections::HashMap; pub use crate::state::client_addr::client_addr; -pub use crate::state::data::StateData; pub use crate::state::from_state::FromState; pub use crate::state::request_id::request_id; @@ -25,12 +23,9 @@ pub(crate) use crate::state::request_id::set_request_id; /// /// ```rust /// extern crate gotham; -/// #[macro_use] -/// extern crate gotham_derive; /// /// use gotham::state::State; /// -/// #[derive(StateData)] /// struct MyStruct { /// value: i32 /// } @@ -76,17 +71,13 @@ impl State { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::State; /// # - /// # #[derive(StateData)] /// # struct MyStruct { /// # value: i32 /// # } /// # - /// # #[derive(StateData)] /// # struct AnotherStruct { /// # value: &'static str /// # } @@ -108,7 +99,7 @@ impl State { /// ``` pub fn put(&mut self, t: T) where - T: StateData, + T: Any + Send, { let type_id = TypeId::of::(); trace!(" inserting record to state for type_id `{:?}`", type_id); @@ -121,17 +112,13 @@ impl State { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::State; /// # - /// # #[derive(StateData)] /// # struct MyStruct { /// # value: i32 /// # } /// # - /// # #[derive(StateData)] /// # struct AnotherStruct { /// # } /// # @@ -149,7 +136,7 @@ impl State { /// ``` pub fn has(&self) -> bool where - T: StateData, + T: Any + Send, { let type_id = TypeId::of::(); self.data.get(&type_id).is_some() @@ -161,17 +148,13 @@ impl State { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::State; /// # - /// # #[derive(StateData)] /// # struct MyStruct { /// # value: i32 /// # } /// # - /// # #[derive(StateData)] /// # struct AnotherStruct { /// # } /// # @@ -189,7 +172,7 @@ impl State { /// ``` pub fn try_borrow(&self) -> Option<&T> where - T: StateData, + T: Any + Send, { let type_id = TypeId::of::(); trace!(" borrowing state data for type_id `{:?}`", type_id); @@ -206,12 +189,9 @@ impl State { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::State; /// # - /// # #[derive(StateData)] /// # struct MyStruct { /// # value: i32 /// # } @@ -227,7 +207,7 @@ impl State { /// ``` pub fn borrow(&self) -> &T where - T: StateData, + T: Any + Send, { self.try_borrow() .expect("required type is not present in State container") @@ -239,17 +219,13 @@ impl State { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::State; /// # - /// # #[derive(StateData)] /// # struct MyStruct { /// # value: i32 /// # } /// # - /// # #[derive(StateData)] /// # struct AnotherStruct { /// # } /// # @@ -269,7 +245,7 @@ impl State { /// # } pub fn try_borrow_mut(&mut self) -> Option<&mut T> where - T: StateData, + T: Any + Send, { let type_id = TypeId::of::(); trace!(" mutably borrowing state data for type_id `{:?}`", type_id); @@ -288,17 +264,13 @@ impl State { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::State; /// # - /// # #[derive(StateData)] /// # struct MyStruct { /// # value: i32 /// # } /// # - /// # #[derive(StateData)] /// # struct AnotherStruct { /// # } /// # @@ -320,7 +292,7 @@ impl State { /// # } pub fn borrow_mut(&mut self) -> &mut T where - T: StateData, + T: Any + Send, { self.try_borrow_mut() .expect("required type is not present in State container") @@ -332,17 +304,13 @@ impl State { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::State; /// # - /// # #[derive(StateData)] /// # struct MyStruct { /// # value: i32 /// # } /// # - /// # #[derive(StateData)] /// # struct AnotherStruct { /// # } /// # @@ -363,7 +331,7 @@ impl State { /// # } pub fn try_take(&mut self) -> Option where - T: StateData, + T: Any + Send, { let type_id = TypeId::of::(); trace!( @@ -386,12 +354,9 @@ impl State { /// /// ```rust /// # extern crate gotham; - /// # #[macro_use] - /// # extern crate gotham_derive; /// # /// # use gotham::state::State; /// # - /// # #[derive(StateData)] /// # struct MyStruct { /// # value: i32 /// # } @@ -411,7 +376,7 @@ impl State { /// # } pub fn take(&mut self) -> T where - T: StateData, + T: Any + Send, { self.try_take() .expect("required type is not present in State container") diff --git a/gotham/src/state/request_id.rs b/gotham/src/state/request_id.rs index 05a2059b5..93ebdb375 100644 --- a/gotham/src/state/request_id.rs +++ b/gotham/src/state/request_id.rs @@ -22,7 +22,8 @@ pub(super) struct RequestId { /// that a value for `RequestId` is always available. pub(crate) fn set_request_id<'a>(state: &'a mut State) -> &'a str { if !state.has::() { - let request_id = match HeaderMap::borrow_from(state).get("X-Request-ID") { + let header_map: &HeaderMap = state.borrow(); + let request_id = match header_map.get("X-Request-ID") { Some(ex_req_id) => { let id = String::from_utf8(ex_req_id.as_bytes().into()).unwrap(); trace!( diff --git a/gotham_derive/src/lib.rs b/gotham_derive/src/lib.rs index a652c2001..1f193344e 100644 --- a/gotham_derive/src/lib.rs +++ b/gotham_derive/src/lib.rs @@ -3,7 +3,6 @@ extern crate proc_macro; mod extenders; mod new_middleware; -mod state; #[proc_macro_derive(StaticResponseExtender)] pub fn static_response_extender(input: proc_macro::TokenStream) -> proc_macro::TokenStream { @@ -11,12 +10,6 @@ pub fn static_response_extender(input: proc_macro::TokenStream) -> proc_macro::T extenders::bad_request_static_response_extender(&ast) } -#[proc_macro_derive(StateData)] -pub fn state_data(input: proc_macro::TokenStream) -> proc_macro::TokenStream { - let ast = syn::parse(input).unwrap(); - state::state_data(&ast) -} - #[proc_macro_derive(NewMiddleware)] pub fn new_middleware(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let ast = syn::parse(input).unwrap(); diff --git a/gotham_derive/src/state.rs b/gotham_derive/src/state.rs deleted file mode 100644 index 1607adf78..000000000 --- a/gotham_derive/src/state.rs +++ /dev/null @@ -1,14 +0,0 @@ -use proc_macro; -use quote::quote; -use syn; - -pub(crate) fn state_data(ast: &syn::DeriveInput) -> proc_macro::TokenStream { - let name = &ast.ident; - let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); - - let expanded = quote! { - impl #impl_generics ::gotham::state::StateData for #name #ty_generics #where_clause {} - }; - - expanded.into() -} diff --git a/middleware/diesel/src/repo.rs b/middleware/diesel/src/repo.rs index 11819cdae..82064d49d 100644 --- a/middleware/diesel/src/repo.rs +++ b/middleware/diesel/src/repo.rs @@ -1,6 +1,5 @@ use diesel::r2d2::ConnectionManager; use diesel::Connection; -use gotham_derive::StateData; use log::error; use r2d2::{CustomizeConnection, Pool, PooledConnection}; use tokio::task; @@ -49,7 +48,6 @@ use tokio::task; /// })).unwrap(); /// /// ``` -#[derive(StateData)] pub struct Repo where T: Connection + 'static, diff --git a/middleware/jwt/src/lib.rs b/middleware/jwt/src/lib.rs index 537decb95..99871b508 100644 --- a/middleware/jwt/src/lib.rs +++ b/middleware/jwt/src/lib.rs @@ -8,8 +8,6 @@ //! `401: Unauthorized`. #![warn(missing_docs, deprecated)] #[macro_use] -extern crate gotham_derive; -#[macro_use] extern crate log; #[cfg(test)] #[macro_use] diff --git a/middleware/jwt/src/middleware.rs b/middleware/jwt/src/middleware.rs index d231c2800..dd3ab4709 100644 --- a/middleware/jwt/src/middleware.rs +++ b/middleware/jwt/src/middleware.rs @@ -133,7 +133,8 @@ where { trace!("[{}] pre-chain jwt middleware", request_id(&state)); - let token = match HeaderMap::borrow_from(&state).get(AUTHORIZATION) { + let header_map: &HeaderMap = state.borrow(); + let token = match header_map.get(AUTHORIZATION) { Some(h) => match h.to_str() { Ok(hx) => hx.get((self.scheme.len() + 1)..), _ => None, diff --git a/middleware/jwt/src/state_data.rs b/middleware/jwt/src/state_data.rs index 7c1f6f12e..af7a6b579 100644 --- a/middleware/jwt/src/state_data.rs +++ b/middleware/jwt/src/state_data.rs @@ -1,5 +1,5 @@ pub use jsonwebtoken::TokenData; /// Struct to contain the JSON Web Token on a per-request basis. -#[derive(StateData, Debug)] +#[derive(Debug)] pub struct AuthorizationToken(pub TokenData); diff --git a/middleware/template/src/lib.rs b/middleware/template/src/lib.rs index d863c9d51..a956c2417 100644 --- a/middleware/template/src/lib.rs +++ b/middleware/template/src/lib.rs @@ -9,10 +9,6 @@ #[macro_use] extern crate log; -// Enable to use #[derive(StateData)] below -//#[macro_use] -//extern crate gotham_derive; - use std::pin::Pin; use futures::prelude::*; @@ -27,7 +23,6 @@ use gotham::state::{request_id, State}; // n.b. There is no requirement to have a StateData struct associated with your Middleware // instance but it is a common need hence we've shown one here to assist newcomers. // -//#[derive(StateData)] //pub struct MyData { // pub my_value: String, //}