From 46220d26f7fd20d952dc5720d4940ac324b05544 Mon Sep 17 00:00:00 2001 From: "Mohamed A. Salah" Date: Sat, 30 Dec 2023 17:36:02 +0200 Subject: [PATCH] resolve clippy warning --- src/handlers/day1.rs | 2 +- src/handlers/day12.rs | 6 +++--- src/handlers/day15.rs | 28 ++++++++++++++-------------- src/handlers/day19.rs | 3 +-- src/handlers/day20.rs | 6 +++--- src/handlers/day21.rs | 42 ++++++++++++++++++++++++++++-------------- src/handlers/day22.rs | 14 ++++---------- src/handlers/day7.rs | 8 ++------ src/handlers/mod.rs | 17 +++++++++-------- 9 files changed, 65 insertions(+), 61 deletions(-) diff --git a/src/handlers/day1.rs b/src/handlers/day1.rs index 8706465..3cc3a45 100644 --- a/src/handlers/day1.rs +++ b/src/handlers/day1.rs @@ -39,7 +39,7 @@ mod tests { let client = TestClient::new(app); let res = client.get("/1/3/5").send().await; assert_eq!(res.status(), StatusCode::OK); - let expected = ((3 ^ 5) as i32).pow(3); + let expected = (3_i32 ^ 5_i32).pow(3); assert_eq!(res.text().await, format!("{expected}")); } diff --git a/src/handlers/day12.rs b/src/handlers/day12.rs index 37ca30f..6a689c0 100644 --- a/src/handlers/day12.rs +++ b/src/handlers/day12.rs @@ -75,7 +75,7 @@ async fn ulids_to_uuids(Json(ulids): Json>) -> Json> { let uuids: Vec = ulids .iter() .filter_map(|ulid| { - if let Ok(ulid) = Ulid::from_string(&ulid) { + if let Ok(ulid) = Ulid::from_string(ulid) { let uuid: Uuid = ulid.into(); Some(uuid.to_string()) } else { @@ -109,7 +109,7 @@ async fn ulids_weekday( let dates: Vec> = ulids .iter() .filter_map(|ulid| { - if let Ok(ulid) = Ulid::from_string(&ulid) { + if let Ok(ulid) = Ulid::from_string(ulid) { let day: DateTime = ulid.datetime().into(); Some(day) } else { @@ -130,7 +130,7 @@ async fn ulids_weekday( in_the_future: dates.iter().filter(|date| date > &&Utc::now()).count(), lsb_is_1: ulids .iter() - .map(|ulid| Ulid::from_string(&ulid).unwrap()) + .map(|ulid| Ulid::from_string(ulid).unwrap()) .filter(|ulid| ulid.0 & 1 == 1) .count(), })) diff --git a/src/handlers/day15.rs b/src/handlers/day15.rs index f6c855e..294e11c 100644 --- a/src/handlers/day15.rs +++ b/src/handlers/day15.rs @@ -37,7 +37,7 @@ async fn nice_validator(Json(password_input): Json) -> impl IntoR return (StatusCode::OK, Json(json!({"result": "nice"}))); } } - return (StatusCode::BAD_REQUEST, Json(json!({"result": "naughty"}))); + (StatusCode::BAD_REQUEST, Json(json!({"result": "naughty"}))) } fn contains_upper_lower_digit(s: &str) -> bool { @@ -61,7 +61,7 @@ fn integers_sum_to_2023(s: &str) -> bool { let mut total_sum = 0; for c in s.chars() { - if let Some(_) = c.to_digit(10) { + if c.is_ascii_digit() { current_num.push(c); } else { total_sum += current_num.parse::().unwrap_or_default(); @@ -91,7 +91,7 @@ fn contains_sandwich(s: &str) -> bool { fn contains_unicode_in_range(s: &str) -> bool { for c in s.chars() { - if c >= '\u{2980}' && c <= '\u{2BFF}' { + if ('\u{2980}'..='\u{2BFF}').contains(&c) { return true; } } @@ -222,13 +222,13 @@ async fn game_validator(Json(password_input): Json) -> impl IntoR ); } - return ( + ( StatusCode::OK, Json(PasswordGameResult { result: "nice", reason: "that's a nice password", }), - ); + ) } #[cfg(test)] @@ -356,22 +356,22 @@ mod tests { #[tokio::test] async fn test_contains_emoji() { - assert_eq!(contains_emoji("hello"), false); - assert_eq!(contains_emoji("hello 😳"), true); - assert_eq!(contains_emoji("2000.23.A j ;) o ;) y ⦄AzA"), false); + assert!(!contains_emoji("hello")); + assert!(contains_emoji("hello 😳")); + assert!(!contains_emoji("2000.23.A j ;) o ;) y ⦄AzA")); } #[tokio::test] async fn test_joy() { - assert_eq!(contains_j_o_y_in_order("2000.23.A joy joy"), false); - assert_eq!(contains_j_o_y_in_order("2020.3.A j ;) o ;) y"), true); + assert!(!contains_j_o_y_in_order("2000.23.A joy joy")); + assert!(contains_j_o_y_in_order("2020.3.A j ;) o ;) y")); } #[tokio::test] async fn test_contains_five_digits() { - assert_eq!(contains_at_least_five_digits("hello"), false); - assert_eq!(contains_at_least_five_digits("123hello"), false); - assert_eq!(contains_at_least_five_digits("12345hello"), true); - assert_eq!(contains_at_least_five_digits("1skdj3skdjf34jskdjf4"), true); + assert!(!contains_at_least_five_digits("hello")); + assert!(!contains_at_least_five_digits("123hello")); + assert!(contains_at_least_five_digits("12345hello")); + assert!(contains_at_least_five_digits("1skdj3skdjf34jskdjf4")); } } diff --git a/src/handlers/day19.rs b/src/handlers/day19.rs index 821068c..95a580e 100644 --- a/src/handlers/day19.rs +++ b/src/handlers/day19.rs @@ -167,8 +167,7 @@ async fn connect_to_room_handler( let mut rooms = state.rooms.write().unwrap(); let room_state = rooms.entry(room_id).or_insert_with(RoomState::new); room_state.insert_user(username.clone()); - let room_sender = room_state.tx.clone(); - room_sender + room_state.tx.clone() }; // create room receiver to subscribe to any new message sent to the room channel diff --git a/src/handlers/day20.rs b/src/handlers/day20.rs index da37625..4884d41 100644 --- a/src/handlers/day20.rs +++ b/src/handlers/day20.rs @@ -81,7 +81,7 @@ async fn cookie(file: Bytes) -> Result { "--format=%cn,%H", BRANCH_NAME, /* "--", "santa.txt"*/ ]) - .current_dir(&extracted_temp_dir.path()) + .current_dir(extracted_temp_dir.path()) .output() .map_err(|e| { tracing::error!("error while unpacking the archive file {e}"); @@ -100,7 +100,7 @@ async fn cookie(file: Bytes) -> Result { { let output = Command::new("git") .args(["checkout", commit, "--force"]) - .current_dir(&extracted_temp_dir.path()) + .current_dir(extracted_temp_dir.path()) .output() .unwrap(); @@ -121,7 +121,7 @@ async fn cookie(file: Bytes) -> Result { } } } - return false; + false }); if found_santa { return Ok(format!("{author} {commit}")); diff --git a/src/handlers/day21.rs b/src/handlers/day21.rs index 97bab12..d83e2aa 100644 --- a/src/handlers/day21.rs +++ b/src/handlers/day21.rs @@ -1,15 +1,21 @@ -use std::{env, error::Error, thread, time::Duration}; +use std::{error::Error, thread, time::Duration}; -use axum::{extract::Path, http::StatusCode, routing::get, Router}; +use axum::{ + extract::{Path, State}, + http::StatusCode, + routing::get, + Router, +}; use dms_coordinates::DMS; use s2::{cell::Cell, cellid::CellID}; use serde::Deserialize; -pub fn router() -> Router { +pub fn router(geocoding_api_key: String) -> Router { Router::new() .route("/21/health", get(|| async { StatusCode::OK })) .route("/21/coords/:binary", get(coords)) .route("/21/country/:binary", get(country)) + .with_state(geocoding_api_key) } async fn coords(Path(binary): Path) -> Result { @@ -42,7 +48,10 @@ async fn coords(Path(binary): Path) -> Result { )) } -async fn country(Path(binary): Path) -> Result { +async fn country( + Path(binary): Path, + State(geocoding_api_key): State, +) -> Result { let b = u64::from_str_radix(binary.as_str(), 2).map_err(|e| { tracing::error!("error converting binary to u64 {e}"); StatusCode::BAD_REQUEST @@ -50,14 +59,16 @@ async fn country(Path(binary): Path) -> Result { let cell_id = CellID(b); let center = Cell::from(cell_id).center(); - Ok( - fetch_country_from_latlong(center.latitude().deg(), center.longitude().deg()) - .await - .map_err(|e| { - tracing::error!("error while fetching country {e}"); - StatusCode::INTERNAL_SERVER_ERROR - })?, + fetch_country_from_latlong( + geocoding_api_key, + center.latitude().deg(), + center.longitude().deg(), ) + .await + .map_err(|e| { + tracing::error!("error while fetching country {e}"); + StatusCode::INTERNAL_SERVER_ERROR + }) } #[derive(Deserialize)] @@ -70,8 +81,11 @@ pub struct Address { pub country: String, } -async fn fetch_country_from_latlong(lat: f64, long: f64) -> Result> { - let geocode_api_key = env::var("GEOCODING_API_KEY")?; +async fn fetch_country_from_latlong( + geocode_api_key: String, + lat: f64, + long: f64, +) -> Result> { let endpoint = format!("https://geocode.maps.co/reverse?lat={lat}&lon={long}&api_key={geocode_api_key}"); let country = loop { @@ -97,7 +111,7 @@ mod tests { #[tokio::test] async fn day21_health() { - let app = router(); + let app = router("test_api_key".to_string()); let client = TestClient::new(app); let res = client.get("/21/health").send().await; assert_eq!(res.status(), StatusCode::OK); diff --git a/src/handlers/day22.rs b/src/handlers/day22.rs index 9580ba2..945d990 100644 --- a/src/handlers/day22.rs +++ b/src/handlers/day22.rs @@ -18,11 +18,8 @@ async fn integers(content: String) -> impl IntoResponse { let mut result: HashSet = HashSet::new(); for line in content.lines() { if let Ok(num) = line.trim().parse::() { - match result.take(&num) { - None => { - result.insert(num); - } - _ => {} + if result.take(&num).is_none() { + result.insert(num); } } } @@ -34,11 +31,8 @@ async fn rocket(content: String) -> impl IntoResponse { let mut result: HashSet = HashSet::new(); for line in content.lines() { if let Ok(num) = line.trim().parse::() { - match result.take(&num) { - None => { - result.insert(num); - } - _ => {} + if result.take(&num).is_none() { + result.insert(num); } } } diff --git a/src/handlers/day7.rs b/src/handlers/day7.rs index fd10d51..f82ea52 100644 --- a/src/handlers/day7.rs +++ b/src/handlers/day7.rs @@ -14,9 +14,7 @@ pub fn router() -> axum::Router { #[axum::debug_handler] async fn santa_cookie(TypedHeader(cookie): TypedHeader) -> Result, StatusCode> { - let recipe = cookie - .get("recipe") - .ok_or_else(|| StatusCode::BAD_REQUEST)?; + let recipe = cookie.get("recipe").ok_or(StatusCode::BAD_REQUEST)?; let de = general_purpose::STANDARD.decode(recipe).map_err(|e| { eprintln!("ERR: error while decoding recipe from base64 {e}"); @@ -45,9 +43,7 @@ struct CookieResult { async fn secret_cookie( TypedHeader(cookie): TypedHeader, ) -> Result, StatusCode> { - let recipe = cookie - .get("recipe") - .ok_or_else(|| StatusCode::BAD_REQUEST)?; + let recipe = cookie.get("recipe").ok_or(StatusCode::BAD_REQUEST)?; let de = general_purpose::STANDARD.decode(recipe).map_err(|e| { eprintln!("ERR: error while decoding recipe from base64 {e}"); diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index ed82391..75a0e81 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -18,7 +18,7 @@ mod day6; mod day7; mod day8; -pub fn router(pool: Pool) -> axum::Router { +pub fn router(pool: Pool, geocoding_api_key: String) -> axum::Router { axum::Router::new() .nest("/", day0::router()) .nest("/", day1::router()) @@ -35,7 +35,7 @@ pub fn router(pool: Pool) -> axum::Router { .nest("/", day18::router(pool)) .nest("/", day19::router()) .nest("/", day20::router()) - .nest("/", day21::router()) + .nest("/", day21::router(geocoding_api_key)) .nest("/", day22::router()) } @@ -47,10 +47,11 @@ mod tests { use sqlx::PgPool; const DATABASE_URL: &str = "postgres://postgres:password@localhost:5432/shuttle"; + const GEOCODING_API_KEY: &str = "test_api_key"; #[tokio::test] async fn day0_health() { let pool = PgPool::connect(DATABASE_URL).await.unwrap(); - let app = router(pool); + let app = router(pool, GEOCODING_API_KEY.to_string()); let client = TestClient::new(app); let res = client.get("/-1/health").send().await; @@ -60,7 +61,7 @@ mod tests { #[tokio::test] async fn day1_health() { let pool = PgPool::connect(DATABASE_URL).await.unwrap(); - let app = router(pool); + let app = router(pool, GEOCODING_API_KEY.to_string()); let client = TestClient::new(app); let res = client.get("/1/health").send().await; @@ -70,7 +71,7 @@ mod tests { #[tokio::test] async fn day4_health() { let pool = PgPool::connect(DATABASE_URL).await.unwrap(); - let app = router(pool); + let app = router(pool, GEOCODING_API_KEY.to_string()); let client = TestClient::new(app); let res = client.get("/4/health").send().await; @@ -80,7 +81,7 @@ mod tests { #[tokio::test] async fn day6_health() { let pool = PgPool::connect(DATABASE_URL).await.unwrap(); - let app = router(pool); + let app = router(pool, GEOCODING_API_KEY.to_string()); let client = TestClient::new(app); let res = client.get("/6/health").send().await; @@ -90,7 +91,7 @@ mod tests { #[tokio::test] async fn day7_health() { let pool = PgPool::connect(DATABASE_URL).await.unwrap(); - let app = router(pool); + let app = router(pool, GEOCODING_API_KEY.to_string()); let client = TestClient::new(app); let res = client.get("/7/health").send().await; @@ -100,7 +101,7 @@ mod tests { #[tokio::test] async fn day8_health() { let pool = PgPool::connect(DATABASE_URL).await.unwrap(); - let app = router(pool); + let app = router(pool, GEOCODING_API_KEY.to_string()); let client = TestClient::new(app); let res = client.get("/8/health").send().await;