Решение на упр.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,
}
// =========================================================
// МАКРОС api_routes!
// =========================================================
macro_rules! api_routes {
(
$(
$method:ident $handler:ident $( ( $param_name:ident : $param_ty:ty ) )?;
)*
) => {
pub fn route(req: Request) -> Response {
$(
if req.method == stringify!($method) {
if let Some(resp) = api_routes!(@handle_route req, $handler $(, $param_name, $param_ty)?) {
return resp;
}
}
)*
Response::not_found()
}
};
// Private ръкав: Static paths (without parameters)
(@handle_route $req:expr, $handler:ident) => {
{
let route_path = concat!("/", stringify!($handler));
if $req.path == route_path {
Some(match $handler() {
Ok(body) => Response::ok(body),
Err(ApiError::BadRequest) => Response::bad_request(),
Err(ApiError::NotFound) => Response::not_found(),
})
} else {
None
}
}
};
// Private ръкав: Dynamic paths (with parameters)
(@handle_route $req:expr, $handler:ident, $param_name:ident, $param_ty:ty) => {
{
let root_path = concat!("/", stringify!($handler));
let prefix = concat!("/", stringify!($handler), "/");
if $req.path == root_path {
Some(Response::bad_request())
}
else if $req.path.starts_with(prefix) {
let param_str = &$req.path[prefix.len()..];
Some(match param_str.parse::<$param_ty>() {
Ok($param_name) => {
match $handler($param_name) {
Ok(body) => Response::ok(body),
Err(ApiError::BadRequest) => Response::bad_request(),
Err(ApiError::NotFound) => Response::not_found(),
}
}
Err(_) => Response::bad_request(),
})
}
else {
None
}
}
};
}
// =========================================================
// HANDLER ФУНКЦИИ
// =========================================================
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 quote v1.0.43
Compiling libc v0.2.180
Compiling unicode-ident v1.0.22
Compiling syn v2.0.114
Compiling futures-core v0.3.31
Compiling pin-project-lite v0.2.16
Compiling parking_lot_core v0.9.12
Compiling futures-sink v0.3.31
Compiling futures-channel v0.3.31
Compiling cfg-if v1.0.4
Compiling smallvec v1.15.1
Compiling pin-utils v0.1.0
Compiling slab v0.4.11
Compiling scopeguard v1.2.0
Compiling futures-io v0.3.31
Compiling futures-task v0.3.31
Compiling memchr v2.7.6
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-1dc8h3o/solution)
warning: field `body` is never read
--> tests/../src/lib.rs:9:9
|
6 | pub struct Request<'a> {
| ------- field in this struct
...
9 | 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:34:5
|
33 | pub enum ApiError {
| -------- variants in this enum
34 | BadRequest,
| ^^^^^^^^^^
35 | 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:48:16
|
48 | pub fn route(req: Request) -> Response {
| ^^^^^
...
124 | / api_routes! {
125 | | GET hello;
126 | | GET square(x : i32);
127 | | }
| |_- 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.54s
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
