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

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

Към профила на Мариян Момчилов

Резултати

  • 0 точки от тестове
  • 3 бонус точки
  • 3 точки общо
  • 0 успешни тест(а)
  • 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 {
$(
let method_str = stringify!($method);
let handler_str = stringify!($handler);
let (path, param) = get_path_and_param(req.path);
if req.method == method_str && path == handler_str {
__node_helper!($method, $handler $( ,param, $param_ty )? );
}
)*
Response::not_found()
}
};
}
#[macro_export]
macro_rules! __node_helper {
($method:ident, $handler:ident, $e: expr, $param_ty:ty ) => {
if let Some(p) = $e {
let value = p.parse::<$param_ty>();
if let Ok(parsed_value) = value {
let result = $handler(parsed_value);
if let Ok(body) = result {
return Response::ok(body);
}
}
}
return Response::bad_request();
};
($method:ident, $handler:ident) => {
let result = $handler();
if let Ok(body) = result {
return Response::ok(body);
} else {
return Response::bad_request();
}
};
}
fn get_path_and_param<'a>(s: &'a str) -> (&'a str, Option<&'a str>) {
let mut spl = s.split("/");
let mut potential_path = spl.next();
if let Some("") = potential_path {
potential_path = spl.next();
}
(potential_path.unwrap_or(s), spl.next())
}

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

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 pin-project-lite v0.2.16
   Compiling parking_lot_core v0.9.12
   Compiling futures-core v0.3.31
   Compiling futures-sink v0.3.31
   Compiling futures-channel v0.3.31
   Compiling futures-task v0.3.31
   Compiling slab v0.4.11
   Compiling smallvec v1.15.1
   Compiling memchr v2.7.6
   Compiling scopeguard v1.2.0
   Compiling cfg-if v1.0.4
   Compiling futures-io v0.3.31
   Compiling pin-utils v0.1.0
   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 futures-util v0.3.31
   Compiling socket2 v0.6.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-96b0vs/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 `get_path_and_param` is never used
  --> src/lib.rs:89:4
   |
89 | fn get_path_and_param<'a>(s: &'a str) -> (&'a str, Option<&'a str>) {
   |    ^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(dead_code)]` on by default

warning: `solution` (lib) generated 2 warnings
error[E0425]: cannot find function `hello` in this scope
 --> tests/solution_test.rs:7:13
  |
7 |         GET hello;
  |             ^^^^^ not found in this scope

error[E0425]: cannot find function `square` in this scope
 --> tests/solution_test.rs:8:13
  |
8 |         GET square(x : i32);
  |             ^^^^^^ not found in this scope

error[E0425]: cannot find function `hello` in this scope
  --> tests/solution_test.rs:22:13
   |
22 |         GET hello;
   |             ^^^^^ not found in this scope

error[E0425]: cannot find function `square` in this scope
  --> tests/solution_test.rs:23:13
   |
23 |         GET square(x : i32);
   |             ^^^^^^ not found in this scope

error[E0425]: cannot find function `hello` in this scope
  --> tests/solution_test.rs:37:13
   |
37 |         GET hello;
   |             ^^^^^ not found in this scope

error[E0425]: cannot find function `square` in this scope
  --> tests/solution_test.rs:38:13
   |
38 |         GET square(x : i32);
   |             ^^^^^^ not found in this scope

error[E0425]: cannot find function `hello` in this scope
  --> tests/solution_test.rs:52:13
   |
52 |         GET hello;
   |             ^^^^^ not found in this scope

error[E0425]: cannot find function `square` in this scope
  --> tests/solution_test.rs:53:13
   |
53 |         GET square(x : i32);
   |             ^^^^^^ not found in this scope

For more information about this error, try `rustc --explain E0425`.
error: could not compile `solution` (test "solution_test") due to 8 previous errors

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

Мариян качи първо решение на 11.01.2026 16:20 (преди 17 дена)

Мариян качи решение на 11.01.2026 16:21 (преди 17 дена)

-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! api_routes {
(
$(
$method:ident $handler:ident $( ( $param_name:ident : $param_ty:ty ) )?;
)*
) => {
pub fn route(req: Request) -> Response {
$(
let method_str = stringify!($method);
let handler_str = stringify!($handler);
let (path, param) = get_path_and_param(req.path);
if req.method == method_str && path == handler_str {
__node_helper!($method, $handler $( ,param, $param_ty )? );
}
)*
Response::not_found()
}
};
}
#[macro_export]
macro_rules! __node_helper {
($method:ident, $handler:ident, $e: expr, $param_ty:ty ) => {
if let Some(p) = $e {
let value = p.parse::<$param_ty>();
if let Ok(parsed_value) = value {
let result = $handler(parsed_value);
if let Ok(body) = result {
return Response::ok(body);
}
}
}
return Response::bad_request();
};
($method:ident, $handler:ident) => {
let result = $handler();
if let Ok(body) = result {
return Response::ok(body);
} else {
return Response::bad_request();
}
};
}
fn get_path_and_param<'a>(s: &'a str) -> (&'a str, Option<&'a str>) {
let mut spl = s.split("/");
let mut potential_path = spl.next();
if let Some("") = potential_path {
potential_path = spl.next();
}
(potential_path.unwrap_or(s), spl.next())
-}
-
-// =========================================================
-// HANDLER ФУНКЦИИ (ПОПЪЛВАТ СЕ ОТ СТУДЕНТА)
-// =========================================================
-
-fn hello() -> Result<String, ApiError> {
- Ok("Hello, world".to_string())
-}
-
-fn square(x: i32) -> Result<String, ApiError> {
- Ok((x * x).to_string())
}

Решението ти е вярно, но трябваше да предадеш и имплементация на функциите hello и square.
Първата предадена версия е изцяло коректна, така че ще ти дам точки за нея.