Решение на упр.12 задача 1 от Ясин Йосифов

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

Към профила на Ясин Йосифов

Резултати

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

Код

use std::str::FromStr;
#[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! __helper {
( $func:ident ( $arg:expr ) ) => { $func($arg) };
( $func:ident () ) => { $func() };
}
macro_rules! __help_convert {
( ) => ()
}
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) {
let mut iter = req.path.split('/');
if iter.next() == Some(stringify!($handler)) || iter.next() == Some(stringify!($handler)) {
let result = __helper! {$handler($(
{
let arg: $param_ty;
if let Some(a) = iter.next() {
if let Ok(a) = FromStr::from_str(a) {
arg = a;
} else {
return Response::bad_request();
}
} else {
return Response::bad_request();
}
arg
}
)*)};
match result {
Ok(s) => return Response::ok(s),
Err(ApiError::BadRequest) => return Response::bad_request(),
Err(ApiError::NotFound) => return Response::not_found(),
}
}
}
)*
Response::not_found()
}
};
}
// =========================================================
// HANDLER ФУНКЦИИ (ПОПЪЛВАТ СЕ ОТ СТУДЕНТА)
// =========================================================
fn hello() -> Result<String, ApiError> {
// Върнете "Hello, world!"
Ok("Hello, world".to_string())
}
fn square(x: i32) -> Result<String, ApiError> {
// Върнете квадрата на x като низ
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 pin-project-lite v0.2.16
   Compiling futures-sink v0.3.31
   Compiling futures-core v0.3.31
   Compiling parking_lot_core v0.9.12
   Compiling futures-channel v0.3.31
   Compiling scopeguard v1.2.0
   Compiling slab v0.4.11
   Compiling cfg-if v1.0.4
   Compiling smallvec v1.15.1
   Compiling futures-io v0.3.31
   Compiling pin-utils v0.1.0
   Compiling memchr v2.7.6
   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-30apfx/solution)
warning: field `body` is never read
 --> tests/../src/lib.rs:7:9
  |
4 | pub struct Request<'a> {
  |            ------- field in this struct
...
7 |     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:32:5
   |
31 | pub enum ApiError {
   |          -------- variants in this enum
32 |     BadRequest,
   |     ^^^^^^^^^^
33 |     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:57:16
    |
57  |           pub fn route(req: Request) -> Response {
    |                  ^^^^^
...
111 | / api_routes! {
112 | |   GET hello;
113 | |   GET square(x : i32);
114 | | }
    | |_- 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 17.08s
     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 коментара)

Ясин качи първо решение на 14.01.2026 23:25 (преди 14 дена)