Решение на упр.12 задача 1 от Стилиян Иванов

Обратно към всички решения

Към профила на Стилиян Иванов

Резултати

  • 4 точки от тестове
  • 0 бонус точки
  • 4 точки общо
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)

Код

#[derive(Debug)]
pub struct Request<'a> {
pub method: &'a str,
pub path: &'a str,
pub body: Option<&'a str>,
}
#[derive(Debug, PartialEq)]
pub struct Response {
pub status: u16,
pub body: String,
}
impl Response {
pub fn ok(body: String) -> Self {
Self { status: 200, body }
}
pub fn bad_request() -> Self {
Self { status: 400, body: String::new() }
}
pub fn not_found() -> Self {
Self { status: 404, body: String::new() }
}
}
#[derive(Debug)]
pub enum ApiError {
BadRequest,
NotFound,
}
macro_rules! api_routes {
( $($method:ident $handler:ident $(($p_name:ident : $p_ty:ty))?;)* ) => {
pub fn route(req: Request) -> Response {
$(
api_routes!(@handle req, $method, $handler, $(($p_name : $p_ty))?);
)*
Response::not_found()
}
};
(@handle $req:ident, $method:ident, $handler:ident, ($p_name:ident : $p_ty:ty)) => {
if $req.method == stringify!($method) {
let base = format!("/{}", stringify!($handler));
if $req.path == base {
return Response::bad_request();
}
let prefix = format!("{}/", base);
if $req.path.starts_with(&prefix) {
let segment = &$req.path[prefix.len()..];
match segment.parse::<$p_ty>() {
Ok(val) => {
return match $handler(val) {
Ok(body) => Response::ok(body),
Err(ApiError::BadRequest) => Response::bad_request(),
Err(ApiError::NotFound) => Response::not_found(),
};
}
Err(_) => return Response::bad_request(),
}
}
}
};
(@handle $req:ident, $method:ident, $handler:ident, ) => {
if $req.method == stringify!($method) && $req.path == format!("/{}", stringify!($handler)) {
return match $handler() {
Ok(body) => Response::ok(body),
Err(ApiError::BadRequest) => Response::bad_request(),
Err(ApiError::NotFound) => Response::not_found(),
};
}
};
}
fn hello() -> Result<String, ApiError> {
Ok("Hello, world".to_string())
}
fn square(x: i32) -> Result<String, ApiError> {
Ok((x * x).to_string())
}
api_routes! {
GET hello;
GET square(x : i32);
}

Лог от изпълнението

Updating crates.io index
     Locking 46 packages to latest compatible versions
   Compiling proc-macro2 v1.0.105
   Compiling libc v0.2.180
   Compiling unicode-ident v1.0.22
   Compiling quote v1.0.43
   Compiling syn v2.0.114
   Compiling parking_lot_core v0.9.12
   Compiling futures-core v0.3.31
   Compiling futures-sink v0.3.31
   Compiling pin-project-lite v0.2.16
   Compiling futures-channel v0.3.31
   Compiling memchr v2.7.6
   Compiling smallvec v1.15.1
   Compiling futures-io v0.3.31
   Compiling futures-task v0.3.31
   Compiling cfg-if v1.0.4
   Compiling scopeguard v1.2.0
   Compiling pin-utils v0.1.0
   Compiling slab v0.4.11
   Compiling lock_api v0.4.14
   Compiling errno v0.3.14
   Compiling signal-hook-registry v1.4.8
   Compiling parking_lot v0.12.5
   Compiling mio v1.1.1
   Compiling futures-macro v0.3.31
   Compiling tokio-macros v2.6.0
   Compiling socket2 v0.6.1
   Compiling futures-util v0.3.31
   Compiling bytes v1.11.0
   Compiling tokio v1.49.0
   Compiling futures-executor v0.3.31
   Compiling futures v0.3.31
   Compiling solution v0.1.0 (/tmp/d20260115-4108951-fx1hac/solution)
warning: field `body` is never read
 --> tests/../src/lib.rs:5:9
  |
2 | pub struct Request<'a> {
  |            ------- field in this struct
...
5 |     pub body: Option<&'a str>,
  |         ^^^^
  |
  = note: `Request` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
  = note: `#[warn(dead_code)]` on by default

warning: variants `BadRequest` and `NotFound` are never constructed
  --> tests/../src/lib.rs:30:5
   |
29 | pub enum ApiError {
   |          -------- variants in this enum
30 |     BadRequest,
   |     ^^^^^^^^^^
31 |     NotFound,
   |     ^^^^^^^^
   |
   = note: `ApiError` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis

warning: function `route` is never used
  --> tests/../src/lib.rs:36:16
   |
36 |           pub fn route(req: Request) -> Response {
   |                  ^^^^^
...
86 | / api_routes! {
87 | |     GET hello;
88 | |     GET square(x : i32);
89 | | }
   | |_- in this macro invocation
   |
   = note: this warning originates in the macro `api_routes` (in Nightly builds, run with -Z macro-backtrace for more info)

warning: `solution` (test "solution_test") generated 3 warnings
    Finished `test` profile [unoptimized + debuginfo] target(s) in 16.20s
     Running tests/solution_test.rs (target/debug/deps/solution_test-a1d9df8614168e84)

running 4 tests
test solution_test::test_hello ... ok
test solution_test::test_missing_arg ... ok
test solution_test::test_not_found ... ok
test solution_test::test_square ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

История (1 версия и 0 коментара)

Стилиян качи първо решение на 09.01.2026 01:34 (преди 19 дена)