-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
day07.rs
66 lines (61 loc) · 2 KB
/
day07.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use axum::{http::StatusCode, response::IntoResponse, routing::get, Json, Router};
use axum_extra::{headers::Cookie, TypedHeader};
use base64::{engine::general_purpose, Engine as _};
use std::collections::HashMap;
pub(crate) fn router() -> Router {
Router::new()
.route("/7/decode", get(decode))
.route("/7/bake", get(bake))
}
async fn decode(
TypedHeader(cookie): TypedHeader<Cookie>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
let recipe = cookie
.get("recipe")
.ok_or((StatusCode::BAD_REQUEST, "recipe cookie missing".to_string()))?;
let decoded = general_purpose::STANDARD
.decode(recipe)
.map_err(|e| (StatusCode::BAD_REQUEST, format!("{e:?}")))?;
let json =
String::from_utf8(decoded).map_err(|e| (StatusCode::BAD_REQUEST, format!("{e:?}")))?;
Ok(json)
}
#[derive(serde::Deserialize)]
struct Bake {
recipe: HashMap<String, i64>,
pantry: HashMap<String, i64>,
}
#[derive(serde::Serialize)]
struct Cookies {
cookies: i64,
pantry: HashMap<String, i64>,
}
async fn bake(
TypedHeader(cookie): TypedHeader<Cookie>,
) -> Result<Json<Cookies>, (StatusCode, String)> {
let recipe = cookie
.get("recipe")
.ok_or((StatusCode::BAD_REQUEST, "recipe cookie missing".to_string()))?;
let decoded = general_purpose::STANDARD
.decode(recipe)
.map_err(|e| (StatusCode::BAD_REQUEST, format!("{e:?}")))?;
let Bake {
mut recipe,
mut pantry,
} = serde_json::from_slice(&decoded)
.map_err(|e| (StatusCode::BAD_REQUEST, format!("{e:?}")))?;
recipe.retain(|_, v| v != &0);
if let Some(cookies) = recipe
.iter()
.map(|(i, a)| pantry.get(i).map(|p| p / a))
.collect::<Option<Vec<_>>>()
.and_then(|v| v.into_iter().min())
{
for (i, a) in recipe {
*pantry.get_mut(&i).unwrap() -= a * cookies;
}
Ok(Json(Cookies { cookies, pantry }))
} else {
Ok(Json(Cookies { cookies: 0, pantry }))
}
}