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

Code before:
/// struct InnerState {}
///
/// impl FromRef<AppState> for InnerState {
///     fn from_ref(app_state: &AppState) -> InnerState {
///         app_state.inner.clone()
///     }
/// }
///
/// async fn api_users(State(inner): State<InnerState>) {
///     // ...
/// }
/// ```
///
/// In general however we recommend you implement `Clone` for all your state types to avoid
/// potential type errors.
///
/// # Shared mutable state
///
/// [As state is global within a `Router`][global] you can't directly get a mutable reference to
/// the state.
///
/// The most basic solution is to use an `Arc<Mutex<_>>`. Which kind of mutex you need depends on
/// your use case. See [the tokio docs] for more details.
///
/// Note that holding a locked `std::sync::Mutex` across `.await` points will result in `!Send`
/// futures which are incompatible with axum. If you need to hold a mutex across `.await` points
/// consider using a `tokio::sync::Mutex` instead.
///
/// ## Example
///
/// ```
/// use axum::{Router, routing::get, extract::State};
/// use std::sync::{Arc, Mutex};
///
/// #[derive(Clone)]
/// struct AppState {
///     data: Arc<Mutex<String>>,
/// }
///
/// async fn handler(State(state): State<AppState>) {
///     let mut data = state.data.lock().expect("mutex was poisoned");
///     *data = "updated foo".to_owned();
///
///     // ...
/// }
///
/// let state = AppState {
///     data: Arc::new(Mutex::new("foo".to_owned())),
/// };
///
/// let app = Router::new()

Review comment (suggestion):
```suggestion
/// futures which are incompatible with axum. If you need to hold a mutex across `.await` points,
```

Code after:
/// struct InnerState {}
///
/// impl FromRef<AppState> for InnerState {
///     fn from_ref(app_state: &AppState) -> InnerState {
///         app_state.inner.clone()
///     }
/// }
///
/// async fn api_users(State(inner): State<InnerState>) {
///     // ...
/// }
/// ```
///
/// In general however we recommend you implement `Clone` for all your state types to avoid
/// potential type errors.
///
/// # Shared mutable state
///
/// [As state is global within a `Router`][global] you can't directly get a mutable reference to
/// the state.
///
/// The most basic solution is to use an `Arc<Mutex<_>>`. Which kind of mutex you need depends on
/// your use case. See [the tokio docs] for more details.
///
/// Note that holding a locked `std::sync::Mutex` across `.await` points will result in `!Send`
/// futures which are incompatible with axum. If you need to hold a mutex across `.await` points,
/// consider using a `tokio::sync::Mutex` instead.
///
/// ## Example
///
/// ```
/// use axum::{Router, routing::get, extract::State};
/// use std::sync::{Arc, Mutex};
///
/// #[derive(Clone)]
/// struct AppState {
///     data: Arc<Mutex<String>>,
/// }
///
/// async fn handler(State(state): State<AppState>) {
///     let mut data = state.data.lock().expect("mutex was poisoned");
///     *data = "updated foo".to_owned();
///
///     // ...
/// }
///
/// let state = AppState {
///     data: Arc::new(Mutex::new("foo".to_owned())),
/// };
///
/// let app = Router::new()
Repository: tokio-rs/axum
File: axum-extra/src/extract/cookie/mod.rs (Rust)

Code before:
            state.custom_key.clone()
        }
    }

    #[derive(Clone)]
    struct CustomKey(Key);

    impl From<CustomKey> for Key {
        fn from(custom: CustomKey) -> Self {
            custom.0
        }
    }

    #[cfg(feature = "cookie-signed")]
    #[tokio::test]
    async fn signed_cannot_access_invalid_cookies() {
        async fn get_cookie(jar: SignedCookieJar) -> impl IntoResponse {
            format!("{:?}", jar.get("key"))
        }

        let state = AppState {
            key: Key::generate(),
            custom_key: CustomKey(Key::generate()),
        };

        let app = Router::<_>::new()
            .route("/get", get(get_cookie))
            .with_state(state);

        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/get")
                    .header("cookie", "key=value")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let body = body_text(res).await;
        assert_eq!(body, "None");
    }

    async fn body_text<B>(body: B) -> String
    where
        B: axum::body::HttpBody,
        B::Error: std::fmt::Debug,
    {
        let bytes = hyper::body::to_bytes(body).await.unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()

Review comment (suggestion):
```suggestion
        let app = Router::new()
```

Code after:
            state.custom_key.clone()
        }
    }

    #[derive(Clone)]
    struct CustomKey(Key);

    impl From<CustomKey> for Key {
        fn from(custom: CustomKey) -> Self {
            custom.0
        }
    }

    #[cfg(feature = "cookie-signed")]
    #[tokio::test]
    async fn signed_cannot_access_invalid_cookies() {
        async fn get_cookie(jar: SignedCookieJar) -> impl IntoResponse {
            format!("{:?}", jar.get("key"))
        }

        let state = AppState {
            key: Key::generate(),
            custom_key: CustomKey(Key::generate()),
        };

        let app = Router::new()
            .route("/get", get(get_cookie))
            .with_state(state);

        let res = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/get")
                    .header("cookie", "key=value")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let body = body_text(res).await;
        assert_eq!(body, "None");
    }

    async fn body_text<B>(body: B) -> String
    where
        B: axum::body::HttpBody,
        B::Error: std::fmt::Debug,
    {
        let bytes = hyper::body::to_bytes(body).await.unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()
Repository: tokio-rs/axum
File: examples/hyper-1-0/src/main.rs (Rust)

Code before:
        .with(tracing_subscriber::fmt::layer())
        .init();

    // you have to use `HttpBody1ToHttpBody04<Incoming>` as the second type parameter to `Router`
    let app: Router<_, HttpBody1ToHttpBody04<Incoming>> = Router::new()
        .route("/", get(|| async { "Hello, World!" }))
        // we can still add regular tower middleware
        .layer(TraceLayer::new_for_http());

    // `Router` implements tower-service 0.3's `Service` trait. Convert that to something
    // that implements hyper 1.0's `Service` trait.
    let service = TowerService03HttpServiceAsHyper1HttpService::new(app);

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    let tcp_listener = TcpListener::bind(addr).await.unwrap();
    tracing::debug!("listening on {}", addr);
    loop {
        let (tcp_stream, _) = tcp_listener.accept().await.unwrap();
        let service = service.clone();
        tokio::task::spawn(async move {
            if let Err(http_err) = http1::Builder::new()
                .keep_alive(true)
                .serve_connection(tcp_stream, service)
                .await
            {
                eprintln!("Error while serving HTTP connection: {}", http_err);
            }
        });
    }
}


Review comment (suggestion):
```suggestion
                eprintln!("Error while serving HTTP connection: {http_err}");
```


Code after:
        .with(tracing_subscriber::fmt::layer())
        .init();

    // you have to use `HttpBody1ToHttpBody04<Incoming>` as the second type parameter to `Router`
    let app: Router<_, HttpBody1ToHttpBody04<Incoming>> = Router::new()
        .route("/", get(|| async { "Hello, World!" }))
        // we can still add regular tower middleware
        .layer(TraceLayer::new_for_http());

    // `Router` implements tower-service 0.3's `Service` trait. Convert that to something
    // that implements hyper 1.0's `Service` trait.
    let service = TowerService03HttpServiceAsHyper1HttpService::new(app);

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    let tcp_listener = TcpListener::bind(addr).await.unwrap();
    tracing::debug!("listening on {addr}");
    loop {
        let (tcp_stream, _) = tcp_listener.accept().await.unwrap();
        let service = service.clone();
        tokio::task::spawn(async move {
            if let Err(http_err) = http1::Builder::new()
                .keep_alive(true)
                .serve_connection(tcp_stream, service)
                .await
            {
                eprintln!("Error while serving HTTP connection: {http_err}");
            }
        });
    }
}
Repository: tokio-rs/axum
File: axum-macros/src/lib.rs (Rust)

Code before:
///
/// #[debug_handler(state = AppState)]
/// async fn handler(
///     State(app_state): State<AppState>,
///     State(inner_state): State<InnerState>,
/// ) {}
///
/// #[derive(Clone)]
/// struct AppState {
///     inner: InnerState,
/// }
///
/// #[derive(Clone)]
/// struct InnerState {}
///
/// impl FromRef<AppState> for InnerState {
///     fn from_ref(state: &AppState) -> Self {
///         state.inner.clone()
///     }
/// }
/// ```
///
/// # Performance
///
/// This macro has no effect when compiled with the release profile. (eg. `cargo build --release`)
///
/// [`axum`]: https://docs.rs/axum/latest
/// [`Handler`]: https://docs.rs/axum/latest/axum/handler/trait.Handler.html
/// [`axum::extract::State`]: https://docs.rs/axum/0.6/axum/extract/struct.State.html
/// [`debug_handler`]: macro@debug_handler
#[proc_macro_attribute]
pub fn debug_handler(_attr: TokenStream, input: TokenStream) -> TokenStream {
    #[cfg(not(debug_assertions))]
    return input;

    #[cfg(debug_assertions)]
    return expand_attr_with(_attr, input, debug_handler::expand);
}

/// Private API: Do no use this!
///
/// Attribute macro to be placed on test functions that'll generate two functions:
///
/// 1. One identical to the function it was placed on.
/// 2. One where calls to `Router::nest` has been replaced with `Router::nest_service`
///
/// This makes it easy to that `nest` and `nest_service` behaves in the same way, without having to
/// manually write identical tests for both methods.
#[cfg(feature = "__private")]
#[proc_macro_attribute]
#[doc(hidden)]

Review comment (suggestion):
```suggestion
/// This macro does not work for associated functions that aren't methods — functions defined in an `impl` block that
/// don't take `self`:
```

Code after:
///
/// #[debug_handler(state = AppState)]
/// async fn handler(
///     State(app_state): State<AppState>,
///     State(inner_state): State<InnerState>,
/// ) {}
///
/// #[derive(Clone)]
/// struct AppState {
///     inner: InnerState,
/// }
///
/// #[derive(Clone)]
/// struct InnerState {}
///
/// impl FromRef<AppState> for InnerState {
///     fn from_ref(state: &AppState) -> Self {
///         state.inner.clone()
///     }
/// }
/// ```
///
/// # Limitations
///
/// This macro does not work for associated functions — functions defined in an `impl` block that
/// don't take `self`:
///
/// ```compile_fail
/// use axum::{debug_handler, extract::Path};
///
/// struct App {}
///
/// impl App {
///     #[debug_handler]
///     async fn handler(Path(_): Path<String>) {}
/// }
/// ```
///
/// This will yield an error similar to this:
///
/// ```text
/// error[E0425]: cannot find function `__axum_macros_check_handler_0_from_request_check` in this scope
//    --> src/main.rs:xx:xx
//     |
//  xx |     pub async fn handler(Path(_): Path<String>)  {}
//     |                                   ^^^^ not found in this scope
/// ```
///
/// # Performance
///
/// This macro has no effect when compiled with the release profile. (eg. `cargo build --release`)
Repository: tokio-rs/axum
File: axum/src/typed_header.rs (Rust)

Code before:
    use crate::{response::IntoResponse, routing::get, test_helpers::*, Router};

    #[crate::test]
    async fn typed_header() {
        async fn handle(
            TypedHeader(user_agent): TypedHeader<headers::UserAgent>,
            TypedHeader(content_encoding): TypedHeader<headers::ContentEncoding>,
        ) -> impl IntoResponse {
            format!("{user_agent:?}, {content_encoding:?}")
        }

        let app = Router::new().route("/", get(handle));

        let client = TestClient::new(app);

        let res = client
            .get("/")
            .header("user-agent", "foobar")
            .header("content-encoding", "gzip, br")
            .header("content-encoding", "deflate")
            .send()
            .await;
        let body = res.text().await;
        assert_eq!(
            body,
            r#"UserAgent("foobar"), ContentEncoding("gzip, br, deflate")"#
        );

        let res = client.get("/").header("user-agent", "foobar").send().await;
        let body = res.text().await;
        assert_eq!(body, r#"UserAgent("foobar"), ContentEncoding("")"#);

        let res = client
            .get("/")
            .header("content-encoding", "gzip")
            .send()
            .await;
        let body = res.text().await;
        assert_eq!(body, "Header of type `user-agent` was missing");
    }
}


Review comment (bug):
I'm not sure we should be relying on the `Debug` representation of external types for tests.

Code after:
    use super::*;
    use crate::{response::IntoResponse, routing::get, test_helpers::*, Router};

    #[crate::test]
    async fn typed_header() {
        async fn handle(
            TypedHeader(user_agent): TypedHeader<headers::UserAgent>,
            TypedHeader(cookies): TypedHeader<headers::Cookie>,
        ) -> impl IntoResponse {
            let user_agent = user_agent.as_str();
            let cookies = cookies.iter().collect::<Vec<_>>();
            format!("User-Agent={user_agent:?}, Cookie={cookies:?}")
        }

        let app = Router::new().route("/", get(handle));

        let client = TestClient::new(app);

        let res = client
            .get("/")
            .header("user-agent", "foobar")
            .header("cookie", "a=1; b=2")
            .header("cookie", "c=3")
            .send()
            .await;
        let body = res.text().await;
        assert_eq!(
            body,
            r#"User-Agent="foobar", Cookie=[("a", "1"), ("b", "2"), ("c", "3")]"#
        );

        let res = client.get("/").header("user-agent", "foobar").send().await;
        let body = res.text().await;
        assert_eq!(body, r#"User-Agent="foobar", Cookie=[]"#);

        let res = client.get("/").header("cookie", "a=1").send().await;
        let body = res.text().await;
        assert_eq!(body, "Header of type `user-agent` was missing");
    }
}
Repository: tokio-rs/axum
File: axum/src/routing/mod.rs (Rust)

Code before:
    fallback: Fallback<S, B>,
    prev_route_id: RouteId,
}

impl<S, B> Clone for Router<S, B> {
    fn clone(&self) -> Self {
        Self {
            routes: self.routes.clone(),
            node: Arc::clone(&self.node),
            fallback: self.fallback.clone(),
            prev_route_id: self.prev_route_id,
        }
    }
}

impl<S, B> Default for Router<S, B>
where
    B: HttpBody + Send + 'static,
    S: Clone + Send + Sync + 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<S, B> fmt::Debug for Router<S, B>
where
    S: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Router")
            .field("routes", &self.routes)
            .field("node", &self.node)
            .field("fallback", &self.fallback)
            .finish()
    }
}

pub(crate) const NEST_TAIL_PARAM: &str = "__private__axum_nest_tail_param";
pub(crate) const NEST_TAIL_PARAM_CAPTURE: &str = "/*__private__axum_nest_tail_param";

impl<S, B> Router<S, B>
where
    B: HttpBody + Send + 'static,
    S: Clone + Send + Sync + 'static,
{
    /// Create a new `Router`.
    ///
    /// Unless you add additional routes this will respond with `404 Not Found` to
    /// all requests.
    pub fn new() -> Self {

Review comment (bug):
Do we want to print the new `prev_route_id` field in the `Debug` impl?

Code after:
    fallback: Fallback<S, B>,
    prev_route_id: RouteId,
}

impl<S, B> Clone for Router<S, B> {
    fn clone(&self) -> Self {
        Self {
            routes: self.routes.clone(),
            node: Arc::clone(&self.node),
            fallback: self.fallback.clone(),
            prev_route_id: self.prev_route_id,
        }
    }
}

impl<S, B> Default for Router<S, B>
where
    B: HttpBody + Send + 'static,
    S: Clone + Send + Sync + 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<S, B> fmt::Debug for Router<S, B> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Router")
            .field("routes", &self.routes)
            .field("node", &self.node)
            .field("fallback", &self.fallback)
            .finish()
    }
}

pub(crate) const NEST_TAIL_PARAM: &str = "__private__axum_nest_tail_param";
pub(crate) const NEST_TAIL_PARAM_CAPTURE: &str = "/*__private__axum_nest_tail_param";

impl<S, B> Router<S, B>
where
    B: HttpBody + Send + 'static,
    S: Clone + Send + Sync + 'static,
{
    /// Create a new `Router`.
    ///
    /// Unless you add additional routes this will respond with `404 Not Found` to
    /// all requests.
    pub fn new() -> Self {
        Self {
            routes: Default::default(),
            node: Default::default(),
Repository: tokio-rs/axum
File: axum-extra/src/typed_header.rs (Rust)

Code before:
//! Extractor and response for typed headers.

use axum::{
    async_trait,
    extract::FromRequestParts,
    response::{IntoResponse, IntoResponseParts, Response, ResponseParts},
};
use headers::Header;
use http::{request::Parts, HeaderValue};
use std::{convert::Infallible, ops::Deref};

pub use headers;

/// Extractor and response that works with typed header values from [`headers`].
///
/// # As extractor
///
/// In general, it's recommended to extract only the needed headers via `TypedHeader` rather than
/// removing all headers with the `HeaderMap` extractor.
///
/// ```rust,no_run
/// use axum::{
///     routing::get,
///     Router,
/// };
/// use headers::UserAgent;
/// use axum_extra::typed_header::TypedHeader;
///
/// async fn users_teams_show(
///     TypedHeader(user_agent): TypedHeader<UserAgent>,
/// ) {
///     // ...
/// }
///
/// let app = Router::new().route("/users/:user_id/team/:team_id", get(users_teams_show));
/// # let _: Router = app;
/// ```

Review comment (suggestion):
I think it would be more convenient for this to be `axum_extra::headers` instead of `axum_extra::typed_header::headers`. Then the `typed_header` module also doesn't need to be public either, I think.

Code after:
//! Extractor and response for typed headers.

use axum::{
    async_trait,
    extract::FromRequestParts,
    response::{IntoResponse, IntoResponseParts, Response, ResponseParts},
};
use headers::{Header, HeaderMapExt};
use http::request::Parts;
use std::{convert::Infallible, ops::Deref};

/// Extractor and response that works with typed header values from [`headers`].
///
/// # As extractor
///
/// In general, it's recommended to extract only the needed headers via `TypedHeader` rather than
/// removing all headers with the `HeaderMap` extractor.
///
/// ```rust,no_run
/// use axum::{
///     routing::get,
///     Router,
/// };
/// use headers::UserAgent;
/// use axum_extra::TypedHeader;
///
/// async fn users_teams_show(
///     TypedHeader(user_agent): TypedHeader<UserAgent>,
/// ) {
///     // ...
/// }
///
/// let app = Router::new().route("/users/:user_id/team/:team_id", get(users_teams_show));
/// # let _: Router = app;
/// ```
///
/// # As response
Repository: tokio-rs/axum
File: examples/diesel-async-postgres/src/main.rs (Rust)

Code before:
//! Run with
//!
//! ```sh
//! export DATABASE_URL=postgres://localhost/your_db
//! diesel migration run
//! cargo0 run -p example-diesel-postgres//!
//! ```
//!
//! Checkout the [diesel webpage](https://diesel.rs) for
//! longer guides about diesel
//!
//! Checkout the [crates.io source code](https://github.com/rust-lang/crates.io/)
//! for a real world application using axum and diesel

use axum::{
    async_trait,
    extract::{FromRef, FromRequestParts, State},
    http::{request::Parts, StatusCode},
    response::Json,
    routing::{get, post},
    Router,
};
use diesel::prelude::*;
use diesel_async::{
    pooled_connection::AsyncDieselConnectionManager, AsyncPgConnection, RunQueryDsl,
};
use std::net::SocketAddr;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

// normally part of your generated schema.rs file
table! {

Review comment (suggestion):
```suggestion
//! cargo run -p example-diesel-async-postgres
```

Code after:
//! Run with
//!
//! ```sh
//! export DATABASE_URL=postgres://localhost/your_db
//! diesel migration run
//! cargo run -p example-diesel-async-postgres
//! ```
//!
//! Checkout the [diesel webpage](https://diesel.rs) for
//! longer guides about diesel
//!
//! Checkout the [crates.io source code](https://github.com/rust-lang/crates.io/)
//! for a real world application using axum and diesel

use axum::{
    async_trait,
    extract::{FromRef, FromRequestParts, State},
    http::{request::Parts, StatusCode},
    response::Json,
    routing::{get, post},
    Router,
};
use diesel::prelude::*;
use diesel_async::{
    pooled_connection::AsyncDieselConnectionManager, AsyncPgConnection, RunQueryDsl,
};
use std::net::SocketAddr;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

// normally part of your generated schema.rs file
table! {