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

Code before:
extern crate self as axum_extra;

pub mod body;
pub mod either;
pub mod extract;
pub mod handler;
pub mod middleware;
pub mod response;
pub mod routing;

#[cfg(feature = "json-lines")]
pub mod json_lines;

#[cfg(feature = "typed-header")]
pub mod typed_header;

#[cfg(feature = "typed-header")]
#[doc(no_inline)]
pub use headers;

#[cfg(feature = "typed-header")]
#[doc(inline)]
pub use typed_header::TypedHeader;

#[rustversion::since(1.80)]
#[cfg(feature = "typed-header")]
#[doc(inline)]
pub use self::routing::__private_validate_static_path;

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

/// _not_ public API
#[cfg(feature = "typed-routing")]
#[doc(hidden)]
pub mod __private {
    use percent_encoding::{AsciiSet, CONTROLS};

    pub use percent_encoding::utf8_percent_encode;

    // from https://github.com/servo/rust-url/blob/master/url/src/parser.rs
    const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
    const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
    pub const PATH_SEGMENT: &AsciiSet = &PATH.add(b'/').add(b'%');
}

#[cfg(test)]
use axum_macros::__private_axum_test as test;

#[cfg(test)]
pub(crate) use axum::test_helpers;

Review comment (bug):
The reason CI is failing is because this says `typed-header`, but that private symbol is actually defined behind the `typed-routing` feature gate. In any case, I don't think we should have this behind a feature flag. You can add rustversion as a non-optional dependency.

Code after:
extern crate self as axum_extra;

pub mod body;
pub mod either;
pub mod extract;
pub mod handler;
pub mod middleware;
pub mod response;
pub mod routing;

#[cfg(feature = "json-lines")]
pub mod json_lines;

#[cfg(feature = "typed-header")]
pub mod typed_header;

#[cfg(feature = "typed-header")]
#[doc(no_inline)]
pub use headers;

#[cfg(feature = "typed-header")]
#[doc(inline)]
pub use typed_header::TypedHeader;

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

/// _not_ public API
#[cfg(feature = "typed-routing")]
#[doc(hidden)]
pub mod __private {
    use percent_encoding::{AsciiSet, CONTROLS};

    pub use percent_encoding::utf8_percent_encode;

    // from https://github.com/servo/rust-url/blob/master/url/src/parser.rs
    const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
    const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
    pub const PATH_SEGMENT: &AsciiSet = &PATH.add(b'/').add(b'%');
}

#[cfg(test)]
use axum_macros::__private_axum_test as test;

#[cfg(test)]
pub(crate) use axum::test_helpers;
Repository: tokio-rs/axum
File: axum-extra/src/routing/mod.rs (Rust)

Code before:
use http::{uri::PathAndQuery, StatusCode, Uri};

#[cfg(feature = "typed-routing")]
use rustversion;

use std::{borrow::Cow, convert::Infallible};
use tower_service::Service;

mod resource;

#[cfg(feature = "typed-routing")]
mod typed;

pub use self::resource::Resource;

#[cfg(feature = "typed-routing")]
pub use self::typed::WithQueryParams;
#[cfg(feature = "typed-routing")]
pub use axum_macros::TypedPath;

#[cfg(feature = "typed-routing")]
pub use self::typed::{SecondElementIs, TypedPath};

#[rustversion::since(1.80)]
#[cfg(feature = "typed-routing")]
pub use self::typed::__private_validate_static_path;

/// Extension trait that adds additional methods to [`Router`].
pub trait RouterExt<S>: sealed::Sealed {
    /// Add a typed `GET` route to the router.
    ///
    /// The path will be inferred from the first argument to the handler function which must
    /// implement [`TypedPath`].
    ///
    /// See [`TypedPath`] for more details and examples.
    #[cfg(feature = "typed-routing")]
    fn typed_get<H, T, P>(self, handler: H) -> Self
    where
        H: axum::handler::Handler<T, S>,
        T: SecondElementIs<P> + 'static,
        P: TypedPath;

    /// Add a typed `DELETE` route to the router.
    ///
    /// The path will be inferred from the first argument to the handler function which must
    /// implement [`TypedPath`].
    ///
    /// See [`TypedPath`] for more details and examples.
    #[cfg(feature = "typed-routing")]
    fn typed_delete<H, T, P>(self, handler: H) -> Self
    where

Review comment (refactor):
I'd prefer if the macro and the helper were declared in this module, not in `routing::typed`.

Code after:
use http::{uri::PathAndQuery, StatusCode, Uri};
use std::{borrow::Cow, convert::Infallible};
use tower_service::Service;

mod resource;

#[cfg(feature = "typed-routing")]
mod typed;

pub use self::resource::Resource;

#[cfg(feature = "typed-routing")]
pub use self::typed::WithQueryParams;
#[cfg(feature = "typed-routing")]
pub use axum_macros::TypedPath;

#[cfg(feature = "typed-routing")]
pub use self::typed::{SecondElementIs, TypedPath};

// Validates a path at compile time, used with the vpath macro.
#[rustversion::since(1.80)]
#[doc(hidden)]
pub const fn __private_validate_static_path(path: &'static str) -> &'static str {
    if path.is_empty() {
        panic!("Paths must start with a `/`. Use \"/\" for root routes")
    }
    if path.as_bytes()[0] != b'/' {
        panic!("Paths must start with /");
    }
    path
}

/// This macro aborts compilation if the path is invalid.
///
/// This example will fail to compile:
///
/// ```compile_fail
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("invalid_path"), get(root))
///     .to_owned();
///
/// async fn root() {}
/// ```
///
/// This one will compile without problems:
///
/// ```no_run
/// use axum::routing::{Router, get};
Repository: tokio-rs/axum
File: axum-extra/src/routing/mod.rs (Rust)

Code before:
    extract::{OriginalUri, Request},
    response::{IntoResponse, Redirect, Response},
    routing::{any, MethodRouter},
    Router,
};
use http::{uri::PathAndQuery, StatusCode, Uri};
use rustversion;
use std::{borrow::Cow, convert::Infallible};
use tower_service::Service;

mod resource;

#[cfg(feature = "typed-routing")]
mod typed;

pub use self::resource::Resource;

#[cfg(feature = "typed-routing")]
pub use self::typed::WithQueryParams;
#[cfg(feature = "typed-routing")]
pub use axum_macros::TypedPath;

#[cfg(feature = "typed-routing")]
pub use self::typed::{SecondElementIs, TypedPath};

// Validates a path in compile time, used with the vpath macro.
// Allow dead code needed because this is only used within the vpath macro
// and if there's no call to it, then, there's no users of it.
#[rustversion::since(1.80)]
#[doc(hidden)]
pub const fn __private_validate_static_path(path: &'static str) -> &'static str {
    if path.is_empty() {
        panic!("Paths must start with a `/`. Use \"/\" for root routes")
    }
    if path.as_bytes()[0] != b'/' {
        panic!("Paths must start with /");
    }
    path
}

/// This macro abort compilation if the path is invalid.
///
/// This example will stop the compilation:
///
/// ```compile_fail
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("invalid_path"), get(root))
///     .to_owned();

Review comment (suggestion):
```suggestion
// Validates a path at compile time, used with the vpath macro.
```

Code after:
    extract::{OriginalUri, Request},
    response::{IntoResponse, Redirect, Response},
    routing::{any, MethodRouter},
    Router,
};
use http::{uri::PathAndQuery, StatusCode, Uri};
use std::{borrow::Cow, convert::Infallible};
use tower_service::Service;

mod resource;

#[cfg(feature = "typed-routing")]
mod typed;

pub use self::resource::Resource;

#[cfg(feature = "typed-routing")]
pub use self::typed::WithQueryParams;
#[cfg(feature = "typed-routing")]
pub use axum_macros::TypedPath;

#[cfg(feature = "typed-routing")]
pub use self::typed::{SecondElementIs, TypedPath};

// Validates a path at compile time, used with the vpath macro.
#[rustversion::since(1.80)]
#[doc(hidden)]
pub const fn __private_validate_static_path(path: &'static str) -> &'static str {
    if path.is_empty() {
        panic!("Paths must start with a `/`. Use \"/\" for root routes")
    }
    if path.as_bytes()[0] != b'/' {
        panic!("Paths must start with /");
    }
    path
}

/// This macro aborts compilation if the path is invalid.
///
/// This example will fail to compile:
///
/// ```compile_fail
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("invalid_path"), get(root))
///     .to_owned();
///
/// async fn root() {}
/// ```
Repository: tokio-rs/axum
File: axum-extra/src/routing/mod.rs (Rust)

Code before:
    routing::{any, MethodRouter},
    Router,
};
use http::{uri::PathAndQuery, StatusCode, Uri};
use rustversion;
use std::{borrow::Cow, convert::Infallible};
use tower_service::Service;

mod resource;

#[cfg(feature = "typed-routing")]
mod typed;

pub use self::resource::Resource;

#[cfg(feature = "typed-routing")]
pub use self::typed::WithQueryParams;
#[cfg(feature = "typed-routing")]
pub use axum_macros::TypedPath;

#[cfg(feature = "typed-routing")]
pub use self::typed::{SecondElementIs, TypedPath};

// Validates a path in compile time, used with the vpath macro.
// Allow dead code needed because this is only used within the vpath macro
// and if there's no call to it, then, there's no users of it.
#[rustversion::since(1.80)]
#[doc(hidden)]
pub const fn __private_validate_static_path(path: &'static str) -> &'static str {
    if path.is_empty() {
        panic!("Paths must start with a `/`. Use \"/\" for root routes")
    }
    if path.as_bytes()[0] != b'/' {
        panic!("Paths must start with /");
    }
    path
}

/// This macro abort compilation if the path is invalid.
///
/// This example will stop the compilation:
///
/// ```compile_fail
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("invalid_path"), get(root))
///     .to_owned();
///
/// async fn root() {}

Review comment (suggestion):
"Allow dead code"? I don't see `#[allow(dead_code)]` here, and I'm sure it's not necessary for public symbols anyways.

Code after:
    routing::{any, MethodRouter},
    Router,
};
use http::{uri::PathAndQuery, StatusCode, Uri};
use std::{borrow::Cow, convert::Infallible};
use tower_service::Service;

mod resource;

#[cfg(feature = "typed-routing")]
mod typed;

pub use self::resource::Resource;

#[cfg(feature = "typed-routing")]
pub use self::typed::WithQueryParams;
#[cfg(feature = "typed-routing")]
pub use axum_macros::TypedPath;

#[cfg(feature = "typed-routing")]
pub use self::typed::{SecondElementIs, TypedPath};

// Validates a path at compile time, used with the vpath macro.
#[rustversion::since(1.80)]
#[doc(hidden)]
pub const fn __private_validate_static_path(path: &'static str) -> &'static str {
    if path.is_empty() {
        panic!("Paths must start with a `/`. Use \"/\" for root routes")
    }
    if path.as_bytes()[0] != b'/' {
        panic!("Paths must start with /");
    }
    path
}

/// This macro aborts compilation if the path is invalid.
///
/// This example will fail to compile:
///
/// ```compile_fail
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("invalid_path"), get(root))
///     .to_owned();
///
/// async fn root() {}
/// ```
///
/// This one will compile without problems:
Repository: tokio-rs/axum
File: axum-extra/src/routing/mod.rs (Rust)

Code before:
#[cfg(feature = "typed-routing")]
pub use self::typed::WithQueryParams;
#[cfg(feature = "typed-routing")]
pub use axum_macros::TypedPath;

#[cfg(feature = "typed-routing")]
pub use self::typed::{SecondElementIs, TypedPath};

// Validates a path in compile time, used with the vpath macro.
// Allow dead code needed because this is only used within the vpath macro
// and if there's no call to it, then, there's no users of it.
#[rustversion::since(1.80)]
#[doc(hidden)]
pub const fn __private_validate_static_path(path: &'static str) -> &'static str {
    if path.is_empty() {
        panic!("Paths must start with a `/`. Use \"/\" for root routes")
    }
    if path.as_bytes()[0] != b'/' {
        panic!("Paths must start with /");
    }
    path
}

/// This macro abort compilation if the path is invalid.
///
/// This example will stop the compilation:
///
/// ```compile_fail
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("invalid_path"), get(root))
///     .to_owned();
///
/// async fn root() {}
/// ```
///
/// This one will compile without problems:
///
/// ```no_run
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("/valid_path"), get(root))
///     .to_owned();
///
/// async fn root() {}
/// ```
///

Review comment (bug):
```suggestion
/// This example will fail to compile:
```

Code after:
pub use self::typed::WithQueryParams;
#[cfg(feature = "typed-routing")]
pub use axum_macros::TypedPath;

#[cfg(feature = "typed-routing")]
pub use self::typed::{SecondElementIs, TypedPath};

// Validates a path at compile time, used with the vpath macro.
#[rustversion::since(1.80)]
#[doc(hidden)]
pub const fn __private_validate_static_path(path: &'static str) -> &'static str {
    if path.is_empty() {
        panic!("Paths must start with a `/`. Use \"/\" for root routes")
    }
    if path.as_bytes()[0] != b'/' {
        panic!("Paths must start with /");
    }
    path
}

/// This macro aborts compilation if the path is invalid.
///
/// This example will fail to compile:
///
/// ```compile_fail
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("invalid_path"), get(root))
///     .to_owned();
///
/// async fn root() {}
/// ```
///
/// This one will compile without problems:
///
/// ```no_run
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("/valid_path"), get(root))
///     .to_owned();
///
/// async fn root() {}
/// ```
///
/// This macro is available only on rust versions 1.80 and above.
#[rustversion::since(1.80)]
#[macro_export]
Repository: tokio-rs/axum
File: axum-extra/src/routing/mod.rs (Rust)

Code before:
mod typed;

pub use self::resource::Resource;

#[cfg(feature = "typed-routing")]
pub use self::typed::WithQueryParams;
#[cfg(feature = "typed-routing")]
pub use axum_macros::TypedPath;

#[cfg(feature = "typed-routing")]
pub use self::typed::{SecondElementIs, TypedPath};

// Validates a path at compile time, used with the vpath macro.
#[rustversion::since(1.80)]
#[doc(hidden)]
pub const fn __private_validate_static_path(path: &'static str) -> &'static str {
    if path.is_empty() {
        panic!("Paths must start with a `/`. Use \"/\" for root routes")
    }
    if path.as_bytes()[0] != b'/' {
        panic!("Paths must start with /");
    }
    path
}

/// This macro abort compilation if the path is invalid.
///
/// This example will fail to compile:
///
/// ```compile_fail
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("invalid_path"), get(root))
///     .to_owned();
///
/// async fn root() {}
/// ```
///
/// This one will compile without problems:
///
/// ```no_run
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("/valid_path"), get(root))
///     .to_owned();
///
/// async fn root() {}

Review comment (suggestion):
```suggestion
/// This macro aborts compilation if the path is invalid.
```

Code after:
mod typed;

pub use self::resource::Resource;

#[cfg(feature = "typed-routing")]
pub use self::typed::WithQueryParams;
#[cfg(feature = "typed-routing")]
pub use axum_macros::TypedPath;

#[cfg(feature = "typed-routing")]
pub use self::typed::{SecondElementIs, TypedPath};

// Validates a path at compile time, used with the vpath macro.
#[rustversion::since(1.80)]
#[doc(hidden)]
pub const fn __private_validate_static_path(path: &'static str) -> &'static str {
    if path.is_empty() {
        panic!("Paths must start with a `/`. Use \"/\" for root routes")
    }
    if path.as_bytes()[0] != b'/' {
        panic!("Paths must start with /");
    }
    path
}

/// This macro aborts compilation if the path is invalid.
///
/// This example will fail to compile:
///
/// ```compile_fail
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("invalid_path"), get(root))
///     .to_owned();
///
/// async fn root() {}
/// ```
///
/// This one will compile without problems:
///
/// ```no_run
/// use axum::routing::{Router, get};
/// use axum_extra::vpath;
///
/// let router = axum::Router::<()>::new()
///     .route(vpath!("/valid_path"), get(root))
///     .to_owned();
///
/// async fn root() {}
Repository: tokio-rs/axum
File: axum/src/extract/connect_info.rs (Rust)

Code before:
    fn connect_info(stream: T) -> Self;
}

#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
const _: () = {
    use crate::serve;

    impl<L> Connected<serve::IncomingStream<'_, L>> for SocketAddr
    where
        L: serve::Listener<Addr = SocketAddr>,
    {
        fn connect_info(stream: serve::IncomingStream<'_, L>) -> Self {
            *stream.remote_addr()
        }
    }
};

impl Connected<SocketAddr> for SocketAddr {
    fn connect_info(remote_addr: SocketAddr) -> Self {
        remote_addr
    }
}

#[allow(dead_code)]
#[test]
fn connected_traits() {
    // Test that the `Connected` trait can be used with custom address and listener types.

    use tokio::net::{TcpListener, TcpStream};

    use crate::extract::connect_info::Connected;
    use crate::serve::{IncomingStream, Listener};
    use crate::Router;

    fn create_router() -> Router {
        todo!()
    }

    fn tcp_listener() -> TcpListener {
        todo!()
    }

    #[derive(Clone)]
    #[allow(dead_code)]
    struct CustomAddr(SocketAddr);

    impl Connected<IncomingStream<'_, TcpListener>> for CustomAddr {
        fn connect_info(_stream: IncomingStream<'_, TcpListener>) -> Self {
            todo!()
        }
    }

Review comment (refactor):
There is already a `mod tests` at the end of the file, would you move this there please?

Code after:

    impl<L> Connected<serve::IncomingStream<'_, L>> for SocketAddr
    where
        L: serve::Listener<Addr = Self>,
    {
        fn connect_info(stream: serve::IncomingStream<'_, L>) -> Self {
            *stream.remote_addr()
        }
    }
};

impl Connected<Self> for SocketAddr {
    fn connect_info(remote_addr: Self) -> Self {
        remote_addr
    }
}

impl<S, C, T> Service<T> for IntoMakeServiceWithConnectInfo<S, C>
where
    S: Clone,
    C: Connected<T>,
{
    type Response = AddExtension<S, ConnectInfo<C>>;
    type Error = Infallible;
    type Future = ResponseFuture<S, C>;

    #[inline]
    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, target: T) -> Self::Future {
        let connect_info = ConnectInfo(C::connect_info(target));
        let svc = Extension(connect_info).layer(self.svc.clone());
        ResponseFuture::new(ready(Ok(svc)))
    }
}

opaque_future! {
    /// Response future for [`IntoMakeServiceWithConnectInfo`].
    pub type ResponseFuture<S, C> =
        std::future::Ready<Result<AddExtension<S, ConnectInfo<C>>, Infallible>>;
}

/// Extractor for getting connection information produced by a [`Connected`].
///
/// Note this extractor requires you to use
/// [`Router::into_make_service_with_connect_info`] to run your app
/// otherwise it will fail at runtime.
///
/// See [`Router::into_make_service_with_connect_info`] for more details.
Repository: tokio-rs/axum
File: axum/src/extract/connect_info.rs (Rust)

Code before:
    T: Clone + Send + Sync + 'static,
{
    type Service = <Extension<Self> as Layer<S>>::Service;

    fn layer(&self, inner: S) -> Self::Service {
        Extension(self.clone()).layer(inner)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        extract::connect_info::Connected, routing::get, serve::IncomingStream, serve::Listener,
        test_helpers::TestClient, Router,
    };
    use tokio::net::{TcpListener, TcpStream};

    #[test]
    fn into_make_service_traits() {
        use crate::test_helpers::*;
        assert_send::<IntoMakeServiceWithConnectInfo<(), NotSendSync>>();
    }

    #[allow(dead_code)]
    #[test]
    fn connected_traits() {
        // Test that the `Connected` trait can be used with custom address and listener types.

        fn create_router() -> Router {
            todo!()
        }

        fn tcp_listener() -> TcpListener {
            todo!()
        }

        #[derive(Clone)]
        #[allow(dead_code)]
        struct CustomAddr(SocketAddr);

        impl Connected<IncomingStream<'_, TcpListener>> for CustomAddr {
            fn connect_info(_stream: IncomingStream<'_, TcpListener>) -> Self {
                todo!()
            }
        }

        impl Connected<IncomingStream<'_, CustomListener>> for CustomAddr {
            fn connect_info(_stream: IncomingStream<'_, CustomListener>) -> Self {
                todo!()
            }

Review comment (suggestion):
```suggestion
    #[allow(clippy::todo)]
```

This doesn't need to be ran as a `#[test]`, we just want the compiler to compile it.

Code after:
    T: Clone + Send + Sync + 'static,
{
    type Service = <Extension<Self> as Layer<S>>::Service;

    fn layer(&self, inner: S) -> Self::Service {
        Extension(self.clone()).layer(inner)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        extract::connect_info::Connected, routing::get, serve::IncomingStream, serve::Listener,
        test_helpers::TestClient, Router,
    };
    use tokio::net::{TcpListener, TcpStream};

    #[test]
    fn into_make_service_traits() {
        use crate::test_helpers::*;
        assert_send::<IntoMakeServiceWithConnectInfo<(), NotSendSync>>();
    }

    #[allow(dead_code)]
    #[allow(clippy::todo)]
    fn connected_traits() {
        // Test that the `Connected` trait can be used with custom address and listener types.

        fn create_router() -> Router {
            todo!()
        }

        fn tcp_listener() -> TcpListener {
            todo!()
        }

        #[derive(Clone)]
        struct CustomAddr(SocketAddr);

        impl Connected<IncomingStream<'_, TcpListener>> for CustomAddr {
            fn connect_info(_stream: IncomingStream<'_, TcpListener>) -> Self {
                todo!()
            }
        }

        impl Connected<IncomingStream<'_, CustomListener>> for CustomAddr {
            fn connect_info(_stream: IncomingStream<'_, CustomListener>) -> Self {
                todo!()
            }
        }