Skip to content

Commit

Permalink
Simplify ErasedHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
willcrichton committed Aug 26, 2024
1 parent 6d21566 commit 1d89da8
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 9 deletions.
14 changes: 6 additions & 8 deletions crates/miniserve/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
#![warn(clippy::pedantic)]

use std::{collections::HashMap, future::Future, io, sync::Arc};
use std::{collections::HashMap, future::Future, io, pin::Pin, sync::Arc};
use tokio::net::{TcpListener, TcpStream};
use tokio_util::sync::ReusableBoxFuture;

/// Re-export for library clients.
pub use http;
Expand Down Expand Up @@ -40,9 +39,8 @@ where
type Future = F;
}

struct ErasedHandler(
Box<dyn Fn(Request) -> ReusableBoxFuture<'static, Response> + Send + Sync + 'static>,
);
type ErasedHandler =
Box<dyn Fn(Request) -> Pin<Box<dyn Future<Output = Response> + Send + Sync>> + Send + Sync>;

/// The main server data structure.
#[derive(Default)]
Expand All @@ -64,10 +62,10 @@ impl Server {
#[must_use]
pub fn route<H: Handler>(mut self, route: impl Into<String>, handler: H) -> Self {
let handler = Arc::new(handler);
let erased = ErasedHandler(Box::new(move |req| {
let erased = Box::new(move |req| {
let handler_ref = Arc::clone(&handler);
ReusableBoxFuture::new(async move { handler_ref(req).await })
}));
Box::pin(handler_ref(req)) as Pin<Box<dyn Future<Output = Response> + Send + Sync>>
});
self.routes.insert(route.into(), erased);
self
}
Expand Down
2 changes: 1 addition & 1 deletion crates/miniserve/src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ async fn generate_response<'a>(
return make_response(StatusCode::NOT_FOUND, "No valid route");
};

let response_res = handler.0(request).await;
let response_res = handler(request).await;

match response_res {
Ok(content) => {
Expand Down

0 comments on commit 1d89da8

Please sign in to comment.