Решение на упр.12 задача 1 от Георги Стоянов
Резултати
- 3 точки от тестове
- 0 бонус точки
- 3 точки общо
- 3 успешни тест(а)
- 1 неуспешни тест(а)
Код
#[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 $( ( $param_name:ident : $param_ty:ty ) )? ;
)*
) => {
pub fn route(req: Request) -> Response {
$(
api_routes!(@handle req, $method, $handler $(, $param_name : $param_ty )?);
)*
Response::not_found()
}
};
(@handle $req:ident, $method:ident, $handler:ident) => {{
if $req.method == stringify!($method)
&& $req.path == concat!("/", stringify!($handler))
{
return api_routes!(@to_response $handler());
}
}};
(@handle $req:ident, $method:ident, $handler:ident, $param_name:ident : $param_ty:ty) => {{
if $req.method == stringify!($method) {
let prefix = concat!("/", stringify!($handler));
if $req.path == prefix {
return Response::bad_request();
}
let prefix = concat!("/", stringify!($handler), "/");
if $req.path.starts_with(prefix) {
let rest = &$req.path[prefix.len()..];
if !rest.is_empty() && !rest.contains('/') {
let $param_name: $param_ty = match rest.parse::<$param_ty>() {
Ok(v) => v,
Err(_) => return Response::bad_request(),
};
return api_routes!(@to_response $handler($param_name));
}
}
}
}};
(@to_response $expr:expr) => {{
match $expr {
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 quote v1.0.43
Compiling libc v0.2.180
Compiling unicode-ident v1.0.22
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 futures-io v0.3.31
Compiling smallvec v1.15.1
Compiling scopeguard v1.2.0
Compiling slab v0.4.11
Compiling pin-utils v0.1.0
Compiling memchr v2.7.6
Compiling cfg-if v1.0.4
Compiling futures-task v0.3.31
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-147svnp/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:40:16
|
40 | pub fn route(req: Request) -> Response {
| ^^^^^
...
93 | / api_routes! {
94 | | GET hello;
95 | | GET square(x : i32);
96 | | }
| |_- 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.73s
Running tests/solution_test.rs (target/debug/deps/solution_test-a1d9df8614168e84)
running 4 tests
test solution_test::test_missing_arg ... ok
test solution_test::test_hello ... FAILED
test solution_test::test_not_found ... ok
test solution_test::test_square ... ok
failures:
---- solution_test::test_hello stdout ----
thread 'solution_test::test_hello' panicked at tests/solution_test.rs:16:5:
assertion `left == right` failed
left: Response { status: 200, body: "Hello, world!" }
right: Response { status: 200, body: "Hello, world" }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
solution_test::test_hello
test result: FAILED. 3 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--test solution_test`
