use serde::Deserialize;
+use std::fmt;
#[derive(Deserialize, Debug)]
struct GcdParameters {
n: u64,
}
#[cfg(axum)]
+impl GcdParameters {
+ fn gcd(&self) -> u64 {
+ assert!(self.n != 0 && self.m != 0);
+ let mut m = self.m;
+ let mut n = self.n;
+ while m != 0 {
+ if m < n {
+ std::mem::swap(&mut m, &mut n);
+ }
+ m %= n;
+ }
+ n
+ }
+}
+
+impl fmt::Display for GcdParameters {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(
+ f,
+ "The greatest common divisor of the numbers {} and {} is <b>{}</b>",
+ self.n,
+ self.m,
+ self.gcd(),
+ )
+ }
+}
#[tokio::main]
async fn main() {
- let app = Router::new().route("/", get(get_index).post(post_gcd));
+ let app = Router::new()
+ .route("/", get(get_index))
+ .route("/gcd", post(post_gcd));
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
axum::Server::bind(&addr)
#[cfg(axum)]
async fn get_index() -> Html<&'static str> {
- Html(
- r#"
- <!doctype html>
- <html>
- <head>
- <title>GCD Calculator</title>
- </head>
- <body>
- <form action"/gcd" method="post">
- <input type="text" name="n" />
- <input type="text" name="m" />
- <button type="submit">Compute GCD</button>
- </form>
- </body>
- </html>
- "#,
- )
+ Html(INDEX_HTML)
}
#[cfg(actix)]
fn get_index() -> HttpResponse {
- HttpResponse::Ok().content_type("text/html").body(
- r#"
- <title>GCD Calculator</title>
- <form action"/gcd" method="post">
- <input type="text" name="n" />
- <input type="text" name="m" />
- <button type="submit">Compute GCD</button>
- </form>
- "#,
- )
+ HttpResponse::Ok()
+ .content_type("text/html")
+ .body(INDEX_HTML)
}
#[cfg(axum)]
"Computing the GCD with zero is boring",
));
}
- let response = format!(
- "The greatest common divisor of the numbers {} and {} is <b>{}</b>.",
- input.n,
- input.m,
- gcd(input.n, input.m)
- );
- Ok(Html(response))
+ Ok(Html(input.to_string()))
}
#[cfg(actix)]
fn post_gcd(form: web::Form<GcdParameters>) -> HttpResponse {
if form.n == 0 || form.m == 0 {
+fn post_gcd(input: web::Form<GcdParameters>) -> HttpResponse {
+ if input.n == 0 || input.m == 0 {
return HttpResponse::BadRequest()
.content_type("text/html")
.body("Computing the GCD with zero is boring");
}
- let response = format!(
- "The greatest common divisor of the numbers {} and {} is <b>{}</b>",
- form.n,
- form.m,
- gcd(form.n, form.m)
- );
- HttpResponse::Ok().content_type("text/html").body(response)
+ HttpResponse::Ok()
+ .content_type("text/html")
+ .body(input.to_string())
}
-fn gcd(mut n: u64, mut m: u64) -> u64 {
- assert!(n != 0 && m != 0);
- while m != 0 {
- if m < n {
- std::mem::swap(&mut m, &mut n);
- }
- m %= n;
- }
- n
-}
+static INDEX_HTML: &str = r#"
+<!doctype html>
+<html>
+ <head>
+ <title>GCD Calculator</title>
+ </head>
+ <body>
+ <form action="/gcd" method="post">
+ <input type="text" name="n" />
+ <input type="text" name="m" />
+ <button type="submit">Compute GCD</button>
+ </form>
+ </body>
+</html>
+"#;