Skip to content

Commit

Permalink
resolve clippy warning
Browse files Browse the repository at this point in the history
  • Loading branch information
m4salah committed Dec 30, 2023
1 parent 086e98c commit 46220d2
Show file tree
Hide file tree
Showing 9 changed files with 65 additions and 61 deletions.
2 changes: 1 addition & 1 deletion src/handlers/day1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"));
}

Expand Down
6 changes: 3 additions & 3 deletions src/handlers/day12.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ async fn ulids_to_uuids(Json(ulids): Json<Vec<String>>) -> Json<Vec<String>> {
let uuids: Vec<String> = 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 {
Expand Down Expand Up @@ -109,7 +109,7 @@ async fn ulids_weekday(
let dates: Vec<DateTime<Utc>> = ulids
.iter()
.filter_map(|ulid| {
if let Ok(ulid) = Ulid::from_string(&ulid) {
if let Ok(ulid) = Ulid::from_string(ulid) {
let day: DateTime<Utc> = ulid.datetime().into();
Some(day)
} else {
Expand All @@ -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(),
}))
Expand Down
28 changes: 14 additions & 14 deletions src/handlers/day15.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ async fn nice_validator(Json(password_input): Json<PasswordInput>) -> 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 {
Expand All @@ -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::<u32>().unwrap_or_default();
Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -222,13 +222,13 @@ async fn game_validator(Json(password_input): Json<PasswordInput>) -> impl IntoR
);
}

return (
(
StatusCode::OK,
Json(PasswordGameResult {
result: "nice",
reason: "that's a nice password",
}),
);
)
}

#[cfg(test)]
Expand Down Expand Up @@ -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"));
}
}
3 changes: 1 addition & 2 deletions src/handlers/day19.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions src/handlers/day20.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ async fn cookie(file: Bytes) -> Result<String, StatusCode> {
"--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}");
Expand All @@ -100,7 +100,7 @@ async fn cookie(file: Bytes) -> Result<String, StatusCode> {
{
let output = Command::new("git")
.args(["checkout", commit, "--force"])
.current_dir(&extracted_temp_dir.path())
.current_dir(extracted_temp_dir.path())
.output()
.unwrap();

Expand All @@ -121,7 +121,7 @@ async fn cookie(file: Bytes) -> Result<String, StatusCode> {
}
}
}
return false;
false
});
if found_santa {
return Ok(format!("{author} {commit}"));
Expand Down
42 changes: 28 additions & 14 deletions src/handlers/day21.rs
Original file line number Diff line number Diff line change
@@ -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<String>) -> Result<String, StatusCode> {
Expand Down Expand Up @@ -42,22 +48,27 @@ async fn coords(Path(binary): Path<String>) -> Result<String, StatusCode> {
))
}

async fn country(Path(binary): Path<String>) -> Result<String, StatusCode> {
async fn country(
Path(binary): Path<String>,
State(geocoding_api_key): State<String>,
) -> Result<String, StatusCode> {
let b = u64::from_str_radix(binary.as_str(), 2).map_err(|e| {
tracing::error!("error converting binary to u64 {e}");
StatusCode::BAD_REQUEST
})?;
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)]
Expand All @@ -70,8 +81,11 @@ pub struct Address {
pub country: String,
}

async fn fetch_country_from_latlong(lat: f64, long: f64) -> Result<String, Box<dyn Error>> {
let geocode_api_key = env::var("GEOCODING_API_KEY")?;
async fn fetch_country_from_latlong(
geocode_api_key: String,
lat: f64,
long: f64,
) -> Result<String, Box<dyn Error>> {
let endpoint =
format!("https://geocode.maps.co/reverse?lat={lat}&lon={long}&api_key={geocode_api_key}");
let country = loop {
Expand All @@ -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);
Expand Down
14 changes: 4 additions & 10 deletions src/handlers/day22.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,8 @@ async fn integers(content: String) -> impl IntoResponse {
let mut result: HashSet<usize> = HashSet::new();
for line in content.lines() {
if let Ok(num) = line.trim().parse::<usize>() {
match result.take(&num) {
None => {
result.insert(num);
}
_ => {}
if result.take(&num).is_none() {
result.insert(num);
}
}
}
Expand All @@ -34,11 +31,8 @@ async fn rocket(content: String) -> impl IntoResponse {
let mut result: HashSet<usize> = HashSet::new();
for line in content.lines() {
if let Ok(num) = line.trim().parse::<usize>() {
match result.take(&num) {
None => {
result.insert(num);
}
_ => {}
if result.take(&num).is_none() {
result.insert(num);
}
}
}
Expand Down
8 changes: 2 additions & 6 deletions src/handlers/day7.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ pub fn router() -> axum::Router {

#[axum::debug_handler]
async fn santa_cookie(TypedHeader(cookie): TypedHeader<Cookie>) -> Result<Json<Value>, 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}");
Expand Down Expand Up @@ -45,9 +43,7 @@ struct CookieResult {
async fn secret_cookie(
TypedHeader(cookie): TypedHeader<Cookie>,
) -> Result<Json<CookieResult>, 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}");
Expand Down
17 changes: 9 additions & 8 deletions src/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ mod day6;
mod day7;
mod day8;

pub fn router(pool: Pool<Postgres>) -> axum::Router {
pub fn router(pool: Pool<Postgres>, geocoding_api_key: String) -> axum::Router {
axum::Router::new()
.nest("/", day0::router())
.nest("/", day1::router())
Expand All @@ -35,7 +35,7 @@ pub fn router(pool: Pool<Postgres>) -> axum::Router {
.nest("/", day18::router(pool))
.nest("/", day19::router())
.nest("/", day20::router())
.nest("/", day21::router())
.nest("/", day21::router(geocoding_api_key))
.nest("/", day22::router())
}

Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand Down

0 comments on commit 46220d2

Please sign in to comment.