Решение на упр.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,
}
// =========================================================
// TODO: МАКРОС api_routes!
// Имплементирайте генерирането на функцията route()
// =========================================================
macro_rules! api_routes {
(
$(
$method:ident $handler:ident $( ( $param_name:ident : $param_ty:ty ) )?;
)*
) => {
pub fn route(req: Request) -> Response {
$(
api_routes!(@route req, $method, $handler $( ($param_name : $param_ty) )?);
)*
Response::not_found()
}
};
(@route $req:expr, $method:ident, $handler:ident) => {
{
let handler_path = concat!("/", stringify!($handler));
if $req.method == stringify!($method) && $req.path == handler_path {
return match $handler() {
Ok(body) => Response::ok(body),
Err(ApiError::BadRequest) => Response::bad_request(),
Err(ApiError::NotFound) => Response::not_found(),
};
}
}
};
(@route $req:expr, $method:ident, $handler:ident ($param_name:ident : $param_ty:ty)) => {
{
let handler_path = concat!("/", stringify!($handler));
let handler_prefix = concat!("/", stringify!($handler), "/");
if $req.method == stringify!($method) &&
($req.path.starts_with(handler_prefix) || $req.path == handler_path) {
if $req.path == handler_path {
return Response::bad_request();
}
let param_str = &$req.path[handler_prefix.len()..];
match param_str.parse::<$param_ty>() {
Ok(param_value) => {
return match $handler(param_value) {
Ok(body) => Response::ok(body),
Err(ApiError::BadRequest) => Response::bad_request(),
Err(ApiError::NotFound) => Response::not_found(),
};
}
Err(_) => {
return Response::bad_request();
}
}
}
}
};
}
// =========================================================
// HANDLER ФУНКЦИИ (ПОПЪЛВАТ СЕ ОТ СТУДЕНТА)
// =========================================================
fn hello() -> Result<String, ApiError> {
Ok("Hello, world".to_string())
}
fn square(x: i32) -> Result<String, ApiError> {
Ok((x * x).to_string())
}
Лог от изпълнението
Updating crates.io index
Locking 46 packages to latest compatible versions
Compiling proc-macro2 v1.0.105
Compiling unicode-ident v1.0.22
Compiling quote v1.0.43
Compiling libc v0.2.180
Compiling syn v2.0.114
Compiling parking_lot_core v0.9.12
Compiling futures-sink v0.3.31
Compiling futures-core v0.3.31
Compiling pin-project-lite v0.2.16
Compiling futures-channel v0.3.31
Compiling futures-io v0.3.31
Compiling memchr v2.7.6
Compiling pin-utils v0.1.0
Compiling smallvec v1.15.1
Compiling scopeguard v1.2.0
Compiling futures-task v0.3.31
Compiling cfg-if v1.0.4
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 socket2 v0.6.1
Compiling futures-macro v0.3.31
Compiling tokio-macros v2.6.0
Compiling futures-util v0.3.31
Compiling mio v1.1.1
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-1jgtj6p/solution)
warning: unused macro definition: `api_routes`
--> src/lib.rs:45:14
|
45 | macro_rules! api_routes {
| ^^^^^^^^^^
|
= note: `#[warn(unused_macros)]` on by default
warning: function `hello` is never used
--> src/lib.rs:107:4
|
107 | fn hello() -> Result<String, ApiError> {
| ^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: function `square` is never used
--> src/lib.rs:111:4
|
111 | fn square(x: i32) -> Result<String, ApiError> {
| ^^^^^^
warning: `solution` (lib) generated 3 warnings
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:36:5
|
35 | pub enum ApiError {
| -------- variants in this enum
36 | BadRequest,
| ^^^^^^^^^^
37 | NotFound,
| ^^^^^^^^
|
= note: `ApiError` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
warning: `solution` (test "solution_test") generated 2 warnings
Finished `test` profile [unoptimized + debuginfo] target(s) in 16.91s
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
