Remove Option wrapper around middleware

This commit is contained in:
Martin Algesten
2021-12-20 20:49:19 +01:00
parent 09ecb6ffd6
commit a2d62368f3
2 changed files with 7 additions and 10 deletions

View File

@@ -43,7 +43,7 @@ pub struct AgentBuilder {
#[cfg(feature = "cookies")] #[cfg(feature = "cookies")]
cookie_store: Option<CookieStore>, cookie_store: Option<CookieStore>,
resolver: ArcResolver, resolver: ArcResolver,
middleware: Option<Vec<Arc<dyn Middleware + Send + Sync>>>, middleware: Vec<Arc<dyn Middleware + Send + Sync>>,
} }
/// Config as built by AgentBuilder and then static for the lifetime of the Agent. /// Config as built by AgentBuilder and then static for the lifetime of the Agent.
@@ -111,7 +111,7 @@ pub(crate) struct AgentState {
#[cfg(feature = "cookies")] #[cfg(feature = "cookies")]
pub(crate) cookie_tin: CookieTin, pub(crate) cookie_tin: CookieTin,
pub(crate) resolver: ArcResolver, pub(crate) resolver: ArcResolver,
pub(crate) middleware: Option<Vec<Arc<dyn Middleware + Send + Sync>>>, pub(crate) middleware: Vec<Arc<dyn Middleware + Send + Sync>>,
} }
impl Agent { impl Agent {
@@ -248,7 +248,7 @@ impl AgentBuilder {
resolver: StdResolver.into(), resolver: StdResolver.into(),
#[cfg(feature = "cookies")] #[cfg(feature = "cookies")]
cookie_store: None, cookie_store: None,
middleware: None, middleware: vec![],
} }
} }
@@ -602,10 +602,7 @@ impl AgentBuilder {
/// All requests made by the agent will use this middleware. Middleware is invoked /// All requests made by the agent will use this middleware. Middleware is invoked
/// in the order they are added to the builder. /// in the order they are added to the builder.
pub fn middleware(mut self, m: impl Middleware + Send + Sync + 'static) -> Self { pub fn middleware(mut self, m: impl Middleware + Send + Sync + 'static) -> Self {
if self.middleware.is_none() { self.middleware.push(Arc::new(m));
self.middleware = Some(vec![]);
}
self.middleware.as_mut().unwrap().push(Arc::new(m));
self self
} }
} }

View File

@@ -142,10 +142,10 @@ impl Request {
unit::connect(unit, true, reader).map_err(|e| e.url(url.clone())) unit::connect(unit, true, reader).map_err(|e| e.url(url.clone()))
}; };
// This clone is quite cheap since either we are cloning the Optional::None or a Vec<Arc<dyn Middleware>>. let response = if !agent.state.middleware.is_empty() {
let maybe_middleware = agent.state.middleware.clone(); // This clone is quite cheap since either we are cloning a Vec<Arc<dyn Middleware>>.
let middleware = agent.state.middleware.clone();
let response = if let Some(middleware) = maybe_middleware {
// The request_fn is the final target in the middleware chain doing the actual invocation. // The request_fn is the final target in the middleware chain doing the actual invocation.
let mut chain = MiddlewareNext::new(Next::End(Box::new(request_fn))); let mut chain = MiddlewareNext::new(Next::End(Box::new(request_fn)));