ronantakizawa/codereview-bench huggingface dataset:
Repository: tokio-rs/axum
File: axum/src/handler/mod.rs (Rust)

Code before:
    pub enum IntoResponseHandler {}
}

impl<T, S> Handler<private::IntoResponseHandler, S> for T
where
    T: IntoResponse + Clone + Send + 'static,
{
    type Future = std::future::Ready<Response>;

    fn call(self, _req: Request, _state: S) -> Self::Future {
        std::future::ready(self.into_response())
    }
}

/// A [`Service`] created from a [`Handler`] by applying a Tower middleware.
///
/// Created with [`Handler::layer`]. See that method for more details.
pub struct Layered<L, H, T, S> {
    layer: L,
    handler: H,
    _marker: PhantomData<fn() -> (T, S)>,
}

impl<L, H, T, S> fmt::Debug for Layered<L, H, T, S>
where
    L: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Layered")
            .field("layer", &self.layer)
            .finish()
    }
}

impl<L, H, T, S> Clone for Layered<L, H, T, S>
where
    L: Clone,
    H: Clone,
{
    fn clone(&self) -> Self {
        Self {
            layer: self.layer.clone(),
            handler: self.handler.clone(),
            _marker: PhantomData,
        }
    }
}

impl<H, S, T, L> Handler<T, S> for Layered<L, H, T, S>
where
    L: Layer<HandlerService<H, T, S>> + Clone + Send + 'static,

Review comment (suggestion):
I don't think this needs to have `pub` visibility? At least on my v0.6.x based branch, things compiled with a private marker type.

Code after:
                            Err(rejection) => return rejection.into_response(),
                        };
                    )*

                    let req = Request::from_parts(parts, body);

                    let $last = match $last::from_request(req, state).await {
                        Ok(value) => value,
                        Err(rejection) => return rejection.into_response(),
                    };

                    let res = self($($ty,)* $last,).await;

                    res.into_response()
                })
            }
        }
    };
}

all_the_tuples!(impl_handler);

mod private {
    // Marker type for `impl<T: IntoResponse> Handler for T`
    #[allow(missing_debug_implementations)]
    pub enum IntoResponseHandler {}
}

impl<T, S> Handler<private::IntoResponseHandler, S> for T
where
    T: IntoResponse + Clone + Send + 'static,
{
    type Future = std::future::Ready<Response>;

    fn call(self, _req: Request, _state: S) -> Self::Future {
        std::future::ready(self.into_response())
    }
}

/// A [`Service`] created from a [`Handler`] by applying a Tower middleware.
///
/// Created with [`Handler::layer`]. See that method for more details.
pub struct Layered<L, H, T, S> {
    layer: L,
    handler: H,
    _marker: PhantomData<fn() -> (T, S)>,
}

impl<L, H, T, S> fmt::Debug for Layered<L, H, T, S>
where
    L: fmt::Debug,
Repository: tokio-rs/axum
File: axum-macros/src/debug_handler.rs (Rust)

Code before:
                        },
                        None => check_into_response_parts(ty, parts_amount)
                    }
                }
            }
            _ => quote! {},
        })
        .collect::<TokenStream>();
    Some(token_stream)
}

fn _check_into_response_not_parts(ty: &Type) -> Option<&'static str> {
    let name = extract_clean_typename(ty);
    match name {
        Some(name) => {
            let s = match &*name {
                "Json" => "Json<_>",
                "String" => "String",
                //todo add more types that implement IntoResponse but not IntoResponseParts
                _ => return None,
            };
            Some(s)
        }
        None => None,
    }
}

fn check_into_response(ty: &Type) -> TokenStream {
    let (span, ty) = (ty.span(), ty.clone());

    let check_fn = format_ident!("__axum_macros_check_into_response_check", span = span,);

    let call_check_fn = format_ident!("__axum_macros_check_into_response_call_check", span = span,);

    let call_check_fn_body = quote_spanned! {span=>
        #check_fn();
    };

    let from_request_bound = quote_spanned! {span=>
        #ty: ::axum::response::IntoResponse
    };
    quote::quote_spanned! {span=>
        #[allow(warnings)]
        #[allow(unreachable_code)]
        #[doc(hidden)]
        fn #check_fn()
        where
            #from_request_bound,
        {}

        // we have to call the function to actually trigger a compile error

Review comment (bug):
We already have the function https://github.com/tokio-rs/axum/blob/4cd8498aeb723ba7eda85a4eaf7680173c085b6f/axum-macros/src/debug_handler.rs#L531 which does something similar. Could we use that instead?

Code after:

    let check_fn = format_ident!(
        "__axum_macros_check_{handler}_into_response_check",
        span = span,
    );

    let call_check_fn = format_ident!(
        "__axum_macros_check_{handler}_into_response_call_check",
        span = span,
    );

    let call_check_fn_body = quote_spanned! {span=>
        #check_fn();
    };

    let from_request_bound = quote_spanned! {span=>
        #ty: ::axum::response::IntoResponse
    };
    quote_spanned! {span=>
        #[allow(warnings)]
        #[allow(unreachable_code)]
        #[doc(hidden)]
        fn #check_fn()
        where
            #from_request_bound,
        {}

        // we have to call the function to actually trigger a compile error
        // since the function is generic, just defining it is not enough
        #[allow(warnings)]
        #[allow(unreachable_code)]
        #[doc(hidden)]
        fn #call_check_fn() {
            #call_check_fn_body
        }
    }
}

fn check_is_response_parts(ty: &Type, ident: &Ident, index: usize) -> TokenStream {
    let (span, ty) = (ty.span(), ty.clone());

    let check_fn = format_ident!(
        "__axum_macros_check_{}_is_response_parts_{index}_check",
        ident,
        span = span,
    );

    quote_spanned! {span=>
        #[allow(warnings)]
        #[allow(unreachable_code)]
        #[doc(hidden)]
Repository: tokio-rs/axum
File: axum-macros/tests/debug_handler/fail/wrong_return_tuple.rs (Rust)

Code before:

#[axum::debug_handler]
async fn handler() -> (
    axum::http::StatusCode,
    axum::Json<&'static str>,
    axum::response::AppendHeaders<[( axum::http::HeaderName,&'static str); 1]>,
) {
    panic!()
}

fn main(){}

Review comment (suggestion):
I think it would be nice to have a third test like this but with a type that isn't special cased. So a type made by the user that implements `IntoResponse` and isn't the last item. To see that the error is also good there.

Code after:
#![allow(unused_parens)]

#[axum::debug_handler]
async fn named_type() -> (
    axum::http::StatusCode,
    axum::Json<&'static str>,
    axum::response::AppendHeaders<[( axum::http::HeaderName,&'static str); 1]>,
) {
    panic!()
}


struct CustomIntoResponse{

}
impl axum::response::IntoResponse for CustomIntoResponse{
    fn into_response(self) -> axum::response::Response {
        todo!()
    }
}
#[axum::debug_handler]
async fn custom_type() -> (
    axum::http::StatusCode,
    CustomIntoResponse,
    axum::response::AppendHeaders<[( axum::http::HeaderName,&'static str); 1]>,
) {
    panic!()
}

fn main() {}
Repository: tokio-rs/axum
File: axum-macros/src/debug_handler.rs (Rust)

Code before:
        _ => return None,
    };
    path.segments.last().map(|p| p.ident.to_string())
}

fn request_consuming_type_name(ty: &Type) -> Option<&'static str> {
    let typename = match extract_clean_typename(ty) {
        Some(tn) => tn,
        None => return None,
    };

    let type_name = match &*typename {
        "Json" => "Json<_>",
        "RawBody" => "RawBody<_>",
        "RawForm" => "RawForm",
        "Multipart" => "Multipart",
        "Protobuf" => "Protobuf",
        "JsonLines" => "JsonLines<_>",
        "Form" => "Form<_>",
        "Request" => "Request<_>",
        "Bytes" => "Bytes",
        "String" => "String",
        "Parts" => "Parts",
        _ => return None,
    };

    Some(type_name)
}

fn well_known_last_response_type(ty: &Type) -> Option<&'static str> {
    let typename = match extract_clean_typename(ty) {
        Some(tn) => tn,
        None => return None,
    };

    let type_name = match &*typename {
        "Json" => "Json<_>",
        "Protobuf" => "Protobuf",
        "JsonLines" => "JsonLines<_>",
        "Form" => "Form<_>",
        "Bytes" => "Bytes",
        "String" => "String",
        _ => return None,
    };

    Some(type_name)
}

fn check_output_impls_into_response(item_fn: &ItemFn) -> TokenStream {
    let ty = match &item_fn.sig.output {
        syn::ReturnType::Default => return quote! {},

Review comment (refactor):
```suggestion
    let typename = extract_clean_typename(ty)?;
```

Code after:
fn request_consuming_type_name(ty: &Type) -> Option<&'static str> {
    let typename = extract_clean_typename(ty)?;

    let type_name = match &*typename {
        "Json" => "Json<_>",
        "RawBody" => "RawBody<_>",
        "RawForm" => "RawForm",
        "Multipart" => "Multipart",
        "Protobuf" => "Protobuf",
        "JsonLines" => "JsonLines<_>",
        "Form" => "Form<_>",
        "Request" => "Request<_>",
        "Bytes" => "Bytes",
        "String" => "String",
        "Parts" => "Parts",
        _ => return None,
    };

    Some(type_name)
}

fn well_known_last_response_type(ty: &Type) -> Option<&'static str> {
    let typename = match extract_clean_typename(ty) {
        Some(tn) => tn,
        None => return None,
    };

    let type_name = match &*typename {
        "Json" => "Json<_>",
        "Protobuf" => "Protobuf",
        "JsonLines" => "JsonLines<_>",
        "Form" => "Form<_>",
        "Bytes" => "Bytes",
        "String" => "String",
        _ => return None,
    };

    Some(type_name)
}

fn check_output_impls_into_response(item_fn: &ItemFn) -> TokenStream {
    let ty = match &item_fn.sig.output {
        syn::ReturnType::Default => return quote! {},
        syn::ReturnType::Type(_, ty) => ty,
    };
    let span = ty.span();

    let declare_inputs = item_fn
        .sig
        .inputs
        .iter()
Repository: tokio-rs/axum
File: axum-extra/src/extract/with_rejection.rs (Rust)

Code before:
impl<E, R> Debug for WithRejection<E, R>
where
    E: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("WithRejection")
            .field(&self.0)
            .field(&self.1)
            .finish()
    }
}

impl<E, R> Clone for WithRejection<E, R>
where
    E: Clone,
{
    fn clone(&self) -> Self {
        Self(self.0.clone(), self.1)
    }
}

impl<E, R> Copy for WithRejection<E, R> where E: Copy {}

impl<E: Default, R> Default for WithRejection<E, R> {
    fn default() -> Self {
        Self(E::default(), PhantomData)
    }
}

impl<E, R> Deref for WithRejection<E, R> {
    type Target = E;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<E, R> DerefMut for WithRejection<E, R> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[async_trait]
impl<E, R, S> FromRequest<S> for WithRejection<E, R>
where
    S: Send + Sync,
    E: FromRequest<S>,
    R: From<E::Rejection> + IntoResponse,
{
    type Rejection = R;

Review comment (suggestion):
I'd rather just keep `Default::default()` here and for the rest of these changes. I don't think it impacts maintainability much.

Code after:
impl<E, R> Debug for WithRejection<E, R>
where
    E: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("WithRejection")
            .field(&self.0)
            .field(&self.1)
            .finish()
    }
}

impl<E, R> Clone for WithRejection<E, R>
where
    E: Clone,
{
    fn clone(&self) -> Self {
        Self(self.0.clone(), self.1)
    }
}

impl<E, R> Copy for WithRejection<E, R> where E: Copy {}

impl<E: Default, R> Default for WithRejection<E, R> {
    fn default() -> Self {
        Self(Default::default(), Default::default())
    }
}

impl<E, R> Deref for WithRejection<E, R> {
    type Target = E;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<E, R> DerefMut for WithRejection<E, R> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[async_trait]
impl<E, R, S> FromRequest<S> for WithRejection<E, R>
where
    S: Send + Sync,
    E: FromRequest<S>,
    R: From<E::Rejection> + IntoResponse,
{
    type Rejection = R;
Repository: tokio-rs/axum
File: axum-extra/src/middleware.rs (Rust)

Code before:
/// use tower_http::timeout::TimeoutLayer;
///
/// # let option_timeout = Some(Duration::new(10, 0));
/// let timeout_layer = option_timeout.map(TimeoutLayer::new);
///
/// let app = Router::new()
///     .route("/", get(|| async {}))
///     .layer(option_layer(timeout_layer));
/// # let _: Router = app;
/// ```
///
/// # Difference between this and [`tower::util::option_layer`]
///
/// [`tower::util::option_layer`] always changes the error type to [`BoxError`] which requires
/// using [`HandleErrorLayer`] when used with axum, even if the layer you're applying uses
/// [`Infallible`].
///
/// `axum_extra::middleware::option_layer` on the other hand doesn't change the error type so can
/// be applied directly.
///
/// [`Layer`]: tower_layer::Layer
/// [`BoxError`]: tower::BoxError
/// [`HandleErrorLayer`]: axum::error_handling::HandleErrorLayer
/// [`Infallible`]: std::convert::Infallible
pub fn option_layer<L>(layer: Option<L>) -> Either<L, Identity> {
    layer.map_or_else(|| Either::E2(Identity::new()), Either::E1)
}


Review comment (suggestion):
I actually think `map().unwrap_or_else()` is easier to parse. Closures as the first argument is generally uncommon in Rust. So I'd rather keep this as is. Same goes for the other similar changes in this PR.

Code after:
/// use tower_http::timeout::TimeoutLayer;
///
/// # let option_timeout = Some(Duration::new(10, 0));
/// let timeout_layer = option_timeout.map(TimeoutLayer::new);
///
/// let app = Router::new()
///     .route("/", get(|| async {}))
///     .layer(option_layer(timeout_layer));
/// # let _: Router = app;
/// ```
///
/// # Difference between this and [`tower::util::option_layer`]
///
/// [`tower::util::option_layer`] always changes the error type to [`BoxError`] which requires
/// using [`HandleErrorLayer`] when used with axum, even if the layer you're applying uses
/// [`Infallible`].
///
/// `axum_extra::middleware::option_layer` on the other hand doesn't change the error type so can
/// be applied directly.
///
/// [`Layer`]: tower_layer::Layer
/// [`BoxError`]: tower::BoxError
/// [`HandleErrorLayer`]: axum::error_handling::HandleErrorLayer
/// [`Infallible`]: std::convert::Infallible
pub fn option_layer<L>(layer: Option<L>) -> Either<L, Identity> {
    layer
        .map(Either::E1)
        .unwrap_or_else(|| Either::E2(Identity::new()))
}
Repository: tokio-rs/axum
File: axum-extra/src/extract/mod.rs (Rust)

Code before:
//! Additional extractors.

mod cached;
mod optional_path;
mod with_rejection;

#[cfg(feature = "form")]
mod form;

#[cfg(feature = "cookie")]
pub mod cookie;

#[cfg(feature = "query")]
mod optional_query;

#[cfg(feature = "query")]
mod query;

#[cfg(feature = "multipart")]
pub mod multipart;

pub use self::{cached::Cached, optional_path::OptionalPath, with_rejection::WithRejection};

#[cfg(feature = "cookie")]
pub use self::cookie::CookieJar;

#[cfg(feature = "cookie-private")]
pub use self::cookie::PrivateCookieJar;

#[cfg(feature = "cookie-signed")]
pub use self::cookie::SignedCookieJar;

#[cfg(feature = "form")]
pub use self::form::{Form, FormRejection};

#[cfg(feature = "query")]
pub use self::optional_query::{OptionalQuery, OptionalQueryRejection};

#[cfg(feature = "query")]

Review comment (suggestion):
I think this should live in the `query` module, since we already have that.

Code after:
//! Additional extractors.

mod cached;
mod optional_path;
mod with_rejection;

#[cfg(feature = "form")]
mod form;

#[cfg(feature = "cookie")]
pub mod cookie;

#[cfg(feature = "query")]
mod query;

#[cfg(feature = "multipart")]
pub mod multipart;

pub use self::{cached::Cached, optional_path::OptionalPath, with_rejection::WithRejection};

#[cfg(feature = "cookie")]
pub use self::cookie::CookieJar;

#[cfg(feature = "cookie-private")]
pub use self::cookie::PrivateCookieJar;

#[cfg(feature = "cookie-signed")]
pub use self::cookie::SignedCookieJar;

#[cfg(feature = "form")]
pub use self::form::{Form, FormRejection};

#[cfg(feature = "query")]
pub use self::query::{OptionalQuery, OptionalQueryRejection, Query, QueryRejection};

#[cfg(feature = "multipart")]
pub use self::multipart::Multipart;

#[cfg(feature = "json-lines")]
Repository: tokio-rs/axum
File: axum/src/body/mod.rs (Rust)

Code before:
//! HTTP body utilities.

#[doc(no_inline)]
pub use http_body::Body as HttpBody;

#[doc(no_inline)]
pub use bytes::Bytes;

#[doc(inline)]
pub use axum_core::body::Body;

use http_body_util::BodyExt;

/// Converts [`Body`] into [`Bytes`].
/// ```rust
/// # use axum::body::{to_bytes, Body};
/// async fn foo() {
///     let body = Body::from(vec![1, 2, 3]);
///     assert_eq!(&to_bytes(body).await.unwrap()[..], &[1, 2, 3]);
/// }
/// ```
pub async fn to_bytes(body: Body) -> Result<Bytes, axum_core::Error> {
    body.collect().await.map(|col| col.to_bytes())
}


Review comment (suggestion):
```suggestion
/// Converts [`Body`] into [`Bytes`].
///
/// # Example
///
/// ```rust
/// use axum::body::{to_bytes, Body};
///
/// # async fn foo() -> Result<(), axum::Error> {
/// let body = Body::from(vec![1, 2, 3]);
/// let bytes = to_bytes(body).await?
/// assert_eq!(&bytes[..], &[1, 2, 3]);
/// # Ok(())
/// # }
/// ```
```

Code after:
//! HTTP body utilities.

#[doc(no_inline)]
pub use http_body::Body as HttpBody;

#[doc(no_inline)]
pub use bytes::Bytes;

#[doc(inline)]
pub use axum_core::body::Body;

use http_body_util::{BodyExt, Limited};

/// Converts [`Body`] into [`Bytes`] and limits the maximum size of the body.
///
/// # Example
///
/// ```rust
/// use axum::body::{to_bytes, Body};
///
/// # async fn foo() -> Result<(), axum_core::Error> {
/// let body = Body::from(vec![1, 2, 3]);
/// // Use `usize::MAX` if you don't care about the maximum size.
/// let bytes = to_bytes(body, usize::MAX).await?;
/// assert_eq!(&bytes[..], &[1, 2, 3]);
/// # Ok(())
/// # }
/// ```
///
/// You can detect if the limit was hit by checking the source of the error:
///
/// ```rust
/// use axum::body::{to_bytes, Body};
/// use http_body_util::LengthLimitError;
///
/// # #[tokio::main]
/// # async fn main() {
/// let body = Body::from(vec![1, 2, 3]);
/// match to_bytes(body, 1).await {
///     Ok(_bytes) => panic!("should have hit the limit"),
///     Err(err) => {
///         let source = std::error::Error::source(&err).unwrap();
///         assert!(source.is::<LengthLimitError>());
///     }
/// }
/// # }
Repository: tokio-rs/axum
File: axum/src/body/mod.rs (Rust)

Code before:
#[doc(no_inline)]
pub use http_body::Body as HttpBody;

#[doc(no_inline)]
pub use bytes::Bytes;

#[doc(inline)]
pub use axum_core::body::Body;

use http_body_util::{BodyExt, Limited};

/// Converts [`Body`] into [`Bytes`] and limits the maximum size of the body.
///
/// # Example
///
/// ```rust
/// use axum::body::{to_bytes, Body};
///
/// # async fn foo() -> Result<(), axum_core::Error> {
/// let body = Body::from(vec![1, 2, 3]);
/// // Use `usize::MAX` if you don't care about the maximum size.
/// let bytes = to_bytes(body, usize::MAX).await?;
/// assert_eq!(&bytes[..], &[1, 2, 3]);
/// # Ok(())
/// # }
/// ```
pub async fn to_bytes(body: Body, limit: usize) -> Result<Bytes, axum_core::Error> {
    Limited::new(body, limit)
        .collect()
        .await
        .map(|col| col.to_bytes())
        .map_err(axum_core::Error::new)
}


Review comment (suggestion):
Probably also good to show how to detect if the limit was hit

```suggestion
/// ```
///
/// You can detect if the limit was hit by checking the source of the error:
///
/// ```rust
/// use axum::body::{to_bytes, Body};
/// use http_body_util::LengthLimitError;
///
/// # #[tokio::main]
/// # async fn main() {
/// let body = Body::from(vec![1, 2, 3]);
/// match to_bytes(body, 1).await {
///     Ok(_bytes) => panic!("should have hit the limit"),
///     Err(err) => {
///         let source = std::error::Error::source(&err).unwrap();
///         assert!(source.is::<LengthLimitError>());
///     }
/// }
/// # }
/// ```
```

Code after:
#[doc(no_inline)]
pub use http_body::Body as HttpBody;

#[doc(no_inline)]
pub use bytes::Bytes;

#[doc(inline)]
pub use axum_core::body::Body;

use http_body_util::{BodyExt, Limited};

/// Converts [`Body`] into [`Bytes`] and limits the maximum size of the body.
///
/// # Example
///
/// ```rust
/// use axum::body::{to_bytes, Body};
///
/// # async fn foo() -> Result<(), axum_core::Error> {
/// let body = Body::from(vec![1, 2, 3]);
/// // Use `usize::MAX` if you don't care about the maximum size.
/// let bytes = to_bytes(body, usize::MAX).await?;
/// assert_eq!(&bytes[..], &[1, 2, 3]);
/// # Ok(())
/// # }
/// ```
///
/// You can detect if the limit was hit by checking the source of the error:
///
/// ```rust
/// use axum::body::{to_bytes, Body};
/// use http_body_util::LengthLimitError;
///
/// # #[tokio::main]
/// # async fn main() {
/// let body = Body::from(vec![1, 2, 3]);
/// match to_bytes(body, 1).await {
///     Ok(_bytes) => panic!("should have hit the limit"),
///     Err(err) => {
///         let source = std::error::Error::source(&err).unwrap();
///         assert!(source.is::<LengthLimitError>());
///     }
/// }
/// # }
/// ```
pub async fn to_bytes(body: Body, limit: usize) -> Result<Bytes, axum_core::Error> {
    Limited::new(body, limit)
        .collect()
        .await
        .map(|col| col.to_bytes())
        .map_err(axum_core::Error::new)
Repository: tokio-rs/axum
File: axum/src/serve.rs (Rust)

Code before:
//! Serve services.

use std::{
    convert::Infallible,
    fmt::Debug,
    future::{Future, IntoFuture},
    io,
    marker::PhantomData,
    net::SocketAddr,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};

use axum_core::{body::Body, extract::Request, response::Response};
use futures_util::{future::poll_fn, pin_mut, FutureExt};
use hyper::body::Incoming;
use hyper_util::{
    rt::{TokioExecutor, TokioIo},
    server::conn::auto::Builder,
};
use pin_project_lite::pin_project;
use tokio::{
    net::{TcpListener, TcpStream},
    sync::watch,
};
use tower::util::{Oneshot, ServiceExt};
use tower_service::Service;

/// Serve the service with the supplied listener.
///
/// This method of running a service is intentionally simple and doesn't support any configuration.
/// Use hyper or hyper-util if you need configuration.
///
/// It supports both HTTP/1 as well as HTTP/2.
///
/// # Examples
///
/// Serving a [`Router`]:
///
/// ```

Review comment (suggestion):
While `std::pin::pin` is unfortunately not available with our MSRV, `std::future::poll_fn` is. Might make sense to use it so it becomes more apparent where we *actually* depend on the util crate.

Code after:
//! Serve services.

use std::{
    convert::Infallible,
    fmt::Debug,
    future::{poll_fn, Future, IntoFuture},
    io,
    marker::PhantomData,
    net::SocketAddr,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};

use axum_core::{body::Body, extract::Request, response::Response};
use futures_util::{pin_mut, FutureExt};
use hyper::body::Incoming;
use hyper_util::{
    rt::{TokioExecutor, TokioIo},
    server::conn::auto::Builder,
};
use pin_project_lite::pin_project;
use tokio::{
    net::{TcpListener, TcpStream},
    sync::watch,
};
use tower::util::{Oneshot, ServiceExt};
use tower_service::Service;

/// Serve the service with the supplied listener.
///
/// This method of running a service is intentionally simple and doesn't support any configuration.
/// Use hyper or hyper-util if you need configuration.
///
/// It supports both HTTP/1 as well as HTTP/2.
///
/// # Examples
///
/// Serving a [`Router`]:
///
/// ```