From a5bfbe11cc633982053441f782ff73f85f9d6699 Mon Sep 17 00:00:00 2001 From: Isaac Whitfield Date: Mon, 15 Jul 2019 13:36:18 -0700 Subject: [PATCH] Update all formatting of Rust projects --- frameworks/Rust/hyper/src/db.rs | 13 +- frameworks/Rust/hyper/src/main.rs | 17 +- frameworks/Rust/hyper/src/main_db.rs | 35 ++-- frameworks/Rust/hyper/src/server.rs | 14 +- frameworks/Rust/iron/src/main.rs | 202 +++++++++++---------- frameworks/Rust/nickel/src/main.rs | 35 ++-- frameworks/Rust/rocket/src/db.rs | 10 +- frameworks/Rust/rocket/src/main.rs | 44 +++-- frameworks/Rust/rouille/src/main.rs | 24 +-- frameworks/Rust/saphir/src/main.rs | 23 ++- frameworks/Rust/thruster/src/context.rs | 68 +++---- frameworks/Rust/tokio-minihttp/src/main.rs | 54 +++--- 12 files changed, 283 insertions(+), 256 deletions(-) diff --git a/frameworks/Rust/hyper/src/db.rs b/frameworks/Rust/hyper/src/db.rs index 2dfda100ad8..23056a0dbac 100644 --- a/frameworks/Rust/hyper/src/db.rs +++ b/frameworks/Rust/hyper/src/db.rs @@ -15,7 +15,11 @@ pub struct Fortune { pub message: String, } -pub fn connect(addr: SocketAddr, config: Config, handle: Handle) -> impl Future { +pub fn connect( + addr: SocketAddr, + config: Config, + handle: Handle, +) -> impl Future { TcpStream::connect(&addr, &handle) .map_err(|e| panic!("error connecting to postgresql: {}", e)) .and_then(move |tcp| { @@ -29,12 +33,7 @@ pub fn connect(addr: SocketAddr, config: Config, handle: Handle) -> impl Future< client .prepare("SELECT id, message FROM fortune") .map_err(|_| ()) - .map(move |fortune| { - Db { - client, - fortune, - } - }) + .map(move |fortune| Db { client, fortune }) }) } diff --git a/frameworks/Rust/hyper/src/main.rs b/frameworks/Rust/hyper/src/main.rs index 8411aa4edbf..7a71cacddfc 100644 --- a/frameworks/Rust/hyper/src/main.rs +++ b/frameworks/Rust/hyper/src/main.rs @@ -7,12 +7,11 @@ extern crate serde_derive; extern crate serde_json; extern crate tokio_core; - use futures::Future; -use hyper::{Body, Response, StatusCode}; -use hyper::header::{CONTENT_LENGTH, CONTENT_TYPE, SERVER, HeaderValue}; +use hyper::header::{HeaderValue, CONTENT_LENGTH, CONTENT_TYPE, SERVER}; use hyper::service::service_fn_ok; +use hyper::{Body, Response, StatusCode}; mod server; @@ -23,7 +22,6 @@ struct JsonResponse<'a> { message: &'a str, } - fn main() { // It seems most of the other benchmarks create static header values // for performance, so just play by the same rules here... @@ -65,7 +63,9 @@ fn main() { Body::from(HELLO_WORLD) } "/json" => { - let rep = JsonResponse { message: "Hello, world!" }; + let rep = JsonResponse { + message: "Hello, world!", + }; let rep_body = serde_json::to_vec(&rep).unwrap(); headers.insert(CONTENT_LENGTH, json_len.clone()); headers.insert(CONTENT_TYPE, json_ct.clone()); @@ -76,7 +76,7 @@ fn main() { *res.status_mut() = StatusCode::NOT_FOUND; *res.headers_mut() = headers; return res; - }, + } }; headers.insert(SERVER, server_header.clone()); @@ -88,9 +88,8 @@ fn main() { // Spawn the `serve_connection` future into the runtime. handle.spawn( - http - .serve_connection(socket, svc) - .map_err(|e| eprintln!("connection error: {}", e)) + http.serve_connection(socket, svc) + .map_err(|e| eprintln!("connection error: {}", e)), ); }) } diff --git a/frameworks/Rust/hyper/src/main_db.rs b/frameworks/Rust/hyper/src/main_db.rs index 2de4aca069f..f7d7898c7c5 100644 --- a/frameworks/Rust/hyper/src/main_db.rs +++ b/frameworks/Rust/hyper/src/main_db.rs @@ -8,7 +8,7 @@ use std::fmt::Write; use std::net::ToSocketAddrs; use futures::{future, Future}; -use hyper::header::{CONTENT_TYPE, SERVER, HeaderValue}; +use hyper::header::{HeaderValue, CONTENT_TYPE, SERVER}; use hyper::service::service_fn; use hyper::{Body, Response}; @@ -37,8 +37,8 @@ fn main() { let server_header = HeaderValue::from_static("hyper"); // Before handling any requests, we should grab a DB connection. - let db_fut = db::connect(psql_addr, psql_config.clone(), handle.clone()) - .map(move |mut db_conn| { + let db_fut = + db::connect(psql_addr, psql_config.clone(), handle.clone()).map(move |mut db_conn| { let html_ct = html_ct.clone(); let server_header = server_header.clone(); @@ -57,35 +57,28 @@ fn main() { match req.uri.path() { "/fortune" => { - future::Either::A(db_conn - .tell_fortune() - .map(move |fortunes| { - let mut buf = String::with_capacity(2048); - let _ = write!(&mut buf, "{}", FortunesTemplate { - fortunes, - }); - let mut res = Response::new(Body::from(buf)); - *res.headers_mut() = headers; - res - })) - }, + future::Either::A(db_conn.tell_fortune().map(move |fortunes| { + let mut buf = String::with_capacity(2048); + let _ = write!(&mut buf, "{}", FortunesTemplate { fortunes }); + let mut res = Response::new(Body::from(buf)); + *res.headers_mut() = headers; + res + })) + } _ => { let mut res = Response::new(Body::empty()); *res.status_mut() = hyper::StatusCode::NOT_FOUND; *res.headers_mut() = headers; future::Either::B(future::ok(res)) - }, + } } }); - // Spawn the `serve_connection` future into the runtime. handle2.spawn( - http - .serve_connection(socket, svc) - .map_err(|e| eprintln!("connection error: {}", e)) + http.serve_connection(socket, svc) + .map_err(|e| eprintln!("connection error: {}", e)), ); - }); handle.spawn(db_fut); }); diff --git a/frameworks/Rust/hyper/src/server.rs b/frameworks/Rust/hyper/src/server.rs index d6b9f6bea88..cfd0a2e46b2 100644 --- a/frameworks/Rust/hyper/src/server.rs +++ b/frameworks/Rust/hyper/src/server.rs @@ -4,8 +4,8 @@ use std::thread; use futures::{Future, Stream}; use hyper::server::conn::Http; -use tokio_core::reactor::{Core, Handle}; use tokio_core::net::{TcpListener, TcpStream}; +use tokio_core::reactor::{Core, Handle}; pub(crate) fn run(per_connection: F) where @@ -35,11 +35,11 @@ where // Bind to 0.0.0.0:8080 let addr = SocketAddr::from(([0, 0, 0, 0], 8080)); - let tcp = reuse_listener(&addr, &handle) - .expect("couldn't bind to addr"); + let tcp = reuse_listener(&addr, &handle).expect("couldn't bind to addr"); // For every accepted connection, spawn an HTTP task - let server = tcp.incoming() + let server = tcp + .incoming() .for_each(move |(sock, _addr)| { let _ = sock.set_nodelay(true); per_connection(sock, &mut http, &handle); @@ -66,7 +66,7 @@ fn reuse_listener(addr: &SocketAddr, handle: &Handle) -> io::Result builder.reuse_address(true)?; builder.bind(addr)?; - builder.listen(1024).and_then(|l| { - TcpListener::from_listener(l, addr, handle) - }) + builder + .listen(1024) + .and_then(|l| TcpListener::from_listener(l, addr, handle)) } diff --git a/frameworks/Rust/iron/src/main.rs b/frameworks/Rust/iron/src/main.rs index 9440e819801..86ae0f67ed0 100755 --- a/frameworks/Rust/iron/src/main.rs +++ b/frameworks/Rust/iron/src/main.rs @@ -1,26 +1,28 @@ extern crate iron; extern crate persistent; -#[macro_use] extern crate router; +#[macro_use] +extern crate router; extern crate serde; extern crate serde_json; -#[macro_use] extern crate serde_derive; +#[macro_use] +extern crate serde_derive; extern crate hyper; -extern crate rand; -extern crate r2d2; +extern crate mustache; extern crate postgres; +extern crate r2d2; extern crate r2d2_postgres; -extern crate mustache; +extern crate rand; extern crate rustc_serialize; +use hyper::header::{ContentType, Server}; +use iron::modifiers::Header; use iron::prelude::*; use iron::status; -use iron::modifiers::Header; use iron::typemap::Key; -use hyper::header::{Server, ContentType}; -use rand::distributions::{Range, IndependentSample}; -use r2d2_postgres::{PostgresConnectionManager, TlsMode}; -use persistent::{Read}; +use persistent::Read; use r2d2::Pool; +use r2d2_postgres::{PostgresConnectionManager, TlsMode}; +use rand::distributions::{IndependentSample, Range}; #[derive(Serialize, Deserialize)] struct Message { @@ -31,61 +33,74 @@ struct Message { #[derive(Serialize, Deserialize, Clone)] struct DatabaseRow { id: i32, - randomNumber: i32 + randomNumber: i32, } struct CachedRows; -impl Key for CachedRows { type Value = Vec; } +impl Key for CachedRows { + type Value = Vec; +} pub type PostgresPool = Pool; struct DbPool; -impl Key for DbPool { type Value = PostgresPool; } +impl Key for DbPool { + type Value = PostgresPool; +} struct FortuneTemplate; -impl Key for FortuneTemplate { type Value = mustache::Template; } +impl Key for FortuneTemplate { + type Value = mustache::Template; +} #[derive(RustcEncodable)] struct FortuneRow { id: i32, - message: String + message: String, } fn main() { let r2d2_config = r2d2::Config::default(); let pg_conn_manager = PostgresConnectionManager::new( "postgres://benchmarkdbuser:benchmarkdbpass@tfb-database/hello_world", - TlsMode::None).unwrap(); + TlsMode::None, + ) + .unwrap(); let pool = r2d2::Pool::new(r2d2_config, pg_conn_manager).unwrap(); - let template = mustache::compile_str(" + let template = mustache::compile_str( + " Fortunes {{#.}} {{/.}} -
idmessage
{{id}}{{message}}
").unwrap(); + ", + ) + .unwrap(); let mut cached_rows: Vec = Vec::with_capacity(10000); let conn = pool.get().unwrap(); for num in 1..10000 { - let rows = &conn.query("SELECT id, randomnumber FROM World WHERE id = $1",&[&num]).unwrap(); + let rows = &conn + .query("SELECT id, randomnumber FROM World WHERE id = $1", &[&num]) + .unwrap(); let row = rows.get(0); cached_rows.push(DatabaseRow { id: row.get(0), - randomNumber: row.get(1) + randomNumber: row.get(1), }); } let app = router!( - json: get "/json" => json_handler, - single_db_query: get "/db" => single_db_query_handler, - plaintext: get "/plaintext" => plaintext_handler, - queries: get "/queries" => queries_handler, - cachedworlds: get "/cached-worlds" => cached_queries_handler, - fortune: get "/fortune" => fortune_handler, - updates: get "/updates" => updates_handler - ); + json: get "/json" => json_handler, + single_db_query: get "/db" => single_db_query_handler, + plaintext: get "/plaintext" => plaintext_handler, + queries: get "/queries" => queries_handler, + cachedworlds: get "/cached-worlds" => cached_queries_handler, + fortune: get "/fortune" => fortune_handler, + updates: get "/updates" => updates_handler + ); let mut middleware = Chain::new(app); middleware.link(Read::::both(pool)); middleware.link(Read::::both(template)); @@ -96,25 +111,22 @@ fn main() { } fn json_handler(_: &mut Request) -> IronResult { - let message: Message = Message { - message: "Hello, World!".to_owned() + let message: Message = Message { + message: "Hello, World!".to_owned(), }; let content_type = Header(ContentType::json()); let server = Header(Server("Iron".to_owned())); - Ok(Response::with( - (status::Ok, + Ok(Response::with(( + status::Ok, serde_json::to_string(&message).unwrap(), content_type, - server - ))) + server, + ))) } fn plaintext_handler(_: &mut Request) -> IronResult { let server = Header(Server("Iron".to_owned())); - Ok(Response::with(( - status::Ok, - "Hello, World!", - server))) + Ok(Response::with((status::Ok, "Hello, World!", server))) } fn single_db_query_handler(req: &mut Request) -> IronResult { @@ -127,8 +139,8 @@ fn single_db_query_handler(req: &mut Request) -> IronResult { status::Ok, serde_json::to_string(&row).unwrap(), server, - content_type - ))) + content_type, + ))) } fn queries_handler(req: &mut Request) -> IronResult { @@ -141,23 +153,22 @@ fn queries_handler(req: &mut Request) -> IronResult { Ok(m) => match m { e @ 1...500 => e, e if e > 500 => 500, - _ => 1 + _ => 1, }, - _ => 1 + _ => 1, }, - _ => 1 + _ => 1, }; let mut res: Vec = Vec::with_capacity(param); for _ in 0..param { let conn = pool.get().unwrap(); res.push(random_row(conn)) - }; - Ok( - Response::with(( - status::Ok, - serde_json::to_string(&res).unwrap(), - server, - content_type + } + Ok(Response::with(( + status::Ok, + serde_json::to_string(&res).unwrap(), + server, + content_type, ))) } @@ -171,26 +182,25 @@ fn cached_queries_handler(req: &mut Request) -> IronResult { Ok(m) => match m { e @ 1...500 => e, e if e > 500 => 500, - _ => 1 + _ => 1, }, - _ => 1 + _ => 1, }, - _ => 1 + _ => 1, }; let mut res: Vec = Vec::with_capacity(param); for _ in 0..param { let mut rng = rand::thread_rng(); - let between = Range::new(1,10000); + let between = Range::new(1, 10000); let num = between.ind_sample(&mut rng); res.push(cached_rows[num].to_owned()) - }; - Ok( - Response::with(( - status::Ok, - serde_json::to_string(&res).unwrap(), - server, - content_type + } + Ok(Response::with(( + status::Ok, + serde_json::to_string(&res).unwrap(), + server, + content_type, ))) } @@ -200,31 +210,27 @@ fn fortune_handler(req: &mut Request) -> IronResult { let template = req.get::>().unwrap(); let pool = req.get::>().unwrap(); let conn = pool.get().unwrap(); - let query_res = &conn.query("SELECT id, message FROM Fortune",&[]).unwrap(); + let query_res = &conn.query("SELECT id, message FROM Fortune", &[]).unwrap(); let query_res_iter = query_res.iter(); - let mut rows: Vec = query_res_iter.map(|row| FortuneRow { - id: row.get(0), - message: row.get(1) - }).collect(); + let mut rows: Vec = query_res_iter + .map(|row| FortuneRow { + id: row.get(0), + message: row.get(1), + }) + .collect(); rows.push(FortuneRow { id: 0, - message: "Additional fortune added at request time.".to_string() + message: "Additional fortune added at request time.".to_string(), }); rows.sort_by(|it, next| it.message.cmp(&next.message)); let mut res = vec![]; template.render(&mut res, &rows).unwrap(); - Ok( - Response::with(( - status::Ok, - res, - server, - content_type - ))) + Ok(Response::with((status::Ok, res, server, content_type))) } fn updates_handler(req: &mut Request) -> IronResult { let mut rng = rand::thread_rng(); - let between = Range::new(1,10000); + let between = Range::new(1, 10000); let content_type = Header(ContentType::json()); let server = Header(Server("Iron".to_owned())); let pool = req.get::>().unwrap(); @@ -234,58 +240,64 @@ fn updates_handler(req: &mut Request) -> IronResult { Ok(m) => match m { e @ 1...500 => e, e if e > 500 => 500, - _ => 1 + _ => 1, }, - _ => 1 + _ => 1, }, - _ => 1 + _ => 1, }; let mut dbres: Vec = Vec::with_capacity(param); for _ in 0..param { let conn = pool.get().unwrap(); dbres.push(random_row(conn)) - }; + } let conn = pool.get().unwrap(); let trans = conn.transaction().unwrap(); // Sorting guarantees no deadlocks between multiple concurrent threads - dbres.sort_by_key(|it| it.id ); + dbres.sort_by_key(|it| it.id); let mut res: Vec = Vec::with_capacity(param); for row in dbres { let num = between.ind_sample(&mut rng); - trans.execute("UPDATE World SET randomnumber = $1 WHERE id = $2", &[&num, &row.id]).unwrap(); + trans + .execute( + "UPDATE World SET randomnumber = $1 WHERE id = $2", + &[&num, &row.id], + ) + .unwrap(); res.push(DatabaseRow { id: row.id, - randomNumber: num + randomNumber: num, }) } trans.commit().unwrap(); - Ok( - Response::with(( - status::Ok, - serde_json::to_string(&res).unwrap(), - server, - content_type + Ok(Response::with(( + status::Ok, + serde_json::to_string(&res).unwrap(), + server, + content_type, ))) } fn random_row(conn: r2d2::PooledConnection) -> DatabaseRow { let mut rng = rand::thread_rng(); - let between = Range::new(1,10000); + let between = Range::new(1, 10000); let num = between.ind_sample(&mut rng); - let rows = &conn.query("SELECT id, randomnumber FROM World WHERE id = $1",&[&num]).unwrap(); + let rows = &conn + .query("SELECT id, randomnumber FROM World WHERE id = $1", &[&num]) + .unwrap(); let row = rows.get(0); DatabaseRow { id: row.get(0), - randomNumber: row.get(1) + randomNumber: row.get(1), } } fn get_param<'a>(querystring: &'a str, param: &'a str) -> Option<&'a str> { - let n = querystring.split("&").find( - |&it| !(it.find(param).is_none()) - ); + let n = querystring + .split("&") + .find(|&it| !(it.find(param).is_none())); match n { Some(n) => n.split("=").nth(1), - _ => n + _ => n, } } diff --git a/frameworks/Rust/nickel/src/main.rs b/frameworks/Rust/nickel/src/main.rs index 7d389928f5d..eea5095da68 100644 --- a/frameworks/Rust/nickel/src/main.rs +++ b/frameworks/Rust/nickel/src/main.rs @@ -2,9 +2,10 @@ extern crate nickel; extern crate serde; extern crate serde_json; -#[macro_use] extern crate serde_derive; +#[macro_use] +extern crate serde_derive; -use nickel::{Nickel, HttpRouter, MediaType}; +use nickel::{HttpRouter, MediaType, Nickel}; #[derive(Serialize, Deserialize)] struct Message { @@ -15,20 +16,24 @@ fn main() { let mut server = Nickel::new(); let mut router = Nickel::router(); - router.get("/json", - middleware!{ |_, mut response| - response.set(MediaType::Json); - let message: Message = Message{ - message: "Hello, World!".to_string(), - }; - serde_json::to_string(&message).unwrap() - }); + router.get( + "/json", + middleware! { |_, mut response| + response.set(MediaType::Json); + let message: Message = Message{ + message: "Hello, World!".to_string(), + }; + serde_json::to_string(&message).unwrap() + }, + ); - router.get("/plaintext", - middleware! { |_, mut response| - response.set(MediaType::Txt); - "Hello, World!" - }); + router.get( + "/plaintext", + middleware! { |_, mut response| + response.set(MediaType::Txt); + "Hello, World!" + }, + ); server.utilize(router); server.listen("0.0.0.0:8080").unwrap(); diff --git a/frameworks/Rust/rocket/src/db.rs b/frameworks/Rust/rocket/src/db.rs index 380abe109ce..253a4b13654 100644 --- a/frameworks/Rust/rocket/src/db.rs +++ b/frameworks/Rust/rocket/src/db.rs @@ -1,9 +1,9 @@ -use std::ops::Deref; -use rocket::http::Status; -use rocket::request::{self, FromRequest}; -use rocket::{Request, State, Outcome}; use diesel::pg::PgConnection; use diesel::r2d2::{ConnectionManager, Pool, PooledConnection}; +use rocket::http::Status; +use rocket::request::{self, FromRequest}; +use rocket::{Outcome, Request, State}; +use std::ops::Deref; type PgPool = Pool>; @@ -16,7 +16,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for DbConn { let pool = request.guard::>()?; match pool.get() { Ok(conn) => Outcome::Success(DbConn(conn)), - Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())) + Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())), } } } diff --git a/frameworks/Rust/rocket/src/main.rs b/frameworks/Rust/rocket/src/main.rs index 387f40bdd7f..b6ead4d271d 100644 --- a/frameworks/Rust/rocket/src/main.rs +++ b/frameworks/Rust/rocket/src/main.rs @@ -1,10 +1,13 @@ #![feature(proc_macro_hygiene, decl_macro)] extern crate rand; -#[macro_use] extern crate rocket; +#[macro_use] +extern crate rocket; extern crate rocket_contrib; -#[macro_use] extern crate diesel; -#[macro_use] extern crate serde_derive; +#[macro_use] +extern crate diesel; +#[macro_use] +extern crate serde_derive; use diesel::prelude::*; use diesel::result::Error; @@ -28,7 +31,7 @@ fn plaintext() -> &'static str { #[get("/json")] fn json() -> Json { let message = models::Message { - message: "Hello, World!" + message: "Hello, World!", }; Json(message) } @@ -68,7 +71,7 @@ fn queries(conn: db::DbConn, q: u16) -> Json> { let result = world .filter(id.eq(random_number())) .first::(&*conn) - .expect("error loading world"); + .expect("error loading world"); results.push(result); } @@ -82,12 +85,12 @@ fn fortunes(conn: db::DbConn) -> Template { let mut context = fortune .load::(&*conn) .expect("error loading fortunes"); - - context.push(models::Fortune { + + context.push(models::Fortune { id: 0, - message: "Additional fortune added at request time.".to_string() + message: "Additional fortune added at request time.".to_string(), }); - + context.sort_by(|a, b| a.message.cmp(&b.message)); Template::render("fortunes", &context) @@ -136,16 +139,19 @@ fn updates(conn: db::DbConn, q: u16) -> Json> { fn main() { rocket::ignite() - .mount("/", routes![ - json, - plaintext, - db, - queries, - queries_empty, - fortunes, - updates, - updates_empty, - ]) + .mount( + "/", + routes![ + json, + plaintext, + db, + queries, + queries_empty, + fortunes, + updates, + updates_empty, + ], + ) .manage(db::init_pool()) .attach(Template::fairing()) .launch(); diff --git a/frameworks/Rust/rouille/src/main.rs b/frameworks/Rust/rouille/src/main.rs index a27e5c3f441..b0616fe75e4 100644 --- a/frameworks/Rust/rouille/src/main.rs +++ b/frameworks/Rust/rouille/src/main.rs @@ -1,17 +1,19 @@ -#[macro_use] extern crate rouille; -#[macro_use] extern crate serde_json; +#[macro_use] +extern crate rouille; +#[macro_use] +extern crate serde_json; fn main() { rouille::start_server("0.0.0.0:8080", move |req| { router!(req, - (GET) (/plaintext) => { - rouille::Response::from_data("text/plain", "Hello, World!") - }, - (GET) (/json) => { - let json = json!({"message": "Hello, World!"}); - rouille::Response::from_data("application/json", json.to_string()) - }, - _ => rouille::Response::empty_404() - ) + (GET) (/plaintext) => { + rouille::Response::from_data("text/plain", "Hello, World!") + }, + (GET) (/json) => { + let json = json!({"message": "Hello, World!"}); + rouille::Response::from_data("application/json", json.to_string()) + }, + _ => rouille::Response::empty_404() + ) }); } diff --git a/frameworks/Rust/saphir/src/main.rs b/frameworks/Rust/saphir/src/main.rs index 963cbae1de9..4271e1dbf5f 100644 --- a/frameworks/Rust/saphir/src/main.rs +++ b/frameworks/Rust/saphir/src/main.rs @@ -1,8 +1,8 @@ extern crate saphir; #[macro_use] extern crate serde_derive; -extern crate serde_json; extern crate serde; +extern crate serde_json; use saphir::*; @@ -19,28 +19,31 @@ fn main() { let server = server_builder .configure_router(|router| { let plaintext = BasicController::new("^/plaintext", ()); - plaintext.add(Method::GET, reg!("^/$"), |_, _, res| { + plaintext.add(Method::GET, reg!("^/$"), |_, _, res| { res.header(header::CONTENT_TYPE, "text/plain") .header(header::SERVER, "Saphir") .status(StatusCode::OK) - .body(HELLO_WORLD); + .body(HELLO_WORLD); }); let json = BasicController::new("^/json", ()); - json.add(Method::GET, reg!("^/$"), |_, _, res| { - let body = ResponseJsonBody{ message: "hello, world!" }; - let json_str = ::serde_json::to_string(&body).expect("this body serialization should never fail"); + json.add(Method::GET, reg!("^/$"), |_, _, res| { + let body = ResponseJsonBody { + message: "hello, world!", + }; + let json_str = ::serde_json::to_string(&body) + .expect("this body serialization should never fail"); res.header(header::CONTENT_TYPE, "application/json") .header(header::SERVER, "Saphir") .status(StatusCode::OK) .body(json_str); }); - router.add(plaintext) - .add(json) + router.add(plaintext).add(json) }) .configure_listener(|listener_config| { - listener_config.set_uri("http://0.0.0.0:8080") + listener_config + .set_uri("http://0.0.0.0:8080") .set_request_timeout_ms(5000) // 10 sec .set_panic_handler(|panic| { println!("HA HA! : {:?}", panic); @@ -49,4 +52,4 @@ fn main() { .build(); server.run().unwrap(); -} \ No newline at end of file +} diff --git a/frameworks/Rust/thruster/src/context.rs b/frameworks/Rust/thruster/src/context.rs index 695271f19a7..7fe93ef1900 100644 --- a/frameworks/Rust/thruster/src/context.rs +++ b/frameworks/Rust/thruster/src/context.rs @@ -1,51 +1,51 @@ -use std::collections::{HashMap}; use smallvec::SmallVec; +use std::collections::HashMap; use thruster::{Context, Request, Response}; pub struct Ctx { - pub body: String, - pub method: String, - pub path: String, - pub request_body: String, - pub params: HashMap, - pub headers: SmallVec<[(String, String); 8]>, - pub status_code: u32, - response: Response + pub body: String, + pub method: String, + pub path: String, + pub request_body: String, + pub params: HashMap, + pub headers: SmallVec<[(String, String); 8]>, + pub status_code: u32, + response: Response, } impl Ctx { - pub fn set_header(&mut self, key: &str, val: &str) { - self.response.header(key, val); - } + pub fn set_header(&mut self, key: &str, val: &str) { + self.response.header(key, val); + } } impl Context for Ctx { - fn get_response(mut self) -> Response { - self.response.status_code(200, "OK"); + fn get_response(mut self) -> Response { + self.response.status_code(200, "OK"); - self.response.body(&self.body); + self.response.body(&self.body); - self.response - } + self.response + } - fn set_body(&mut self, body: String) { - self.body = body; - } + fn set_body(&mut self, body: String) { + self.body = body; + } } pub fn generate_context(request: Request) -> Ctx { - let method = request.method().to_owned(); - let path = request.path().to_owned(); - let request_body = request.raw_body().to_owned(); - - Ctx { - body: "".to_owned(), - method: method, - path: path, - params: request.params, - request_body: request_body, - headers: SmallVec::new(), - status_code: 200, - response: Response::new() - } + let method = request.method().to_owned(); + let path = request.path().to_owned(); + let request_body = request.raw_body().to_owned(); + + Ctx { + body: "".to_owned(), + method: method, + path: path, + params: request.params, + request_body: request_body, + headers: SmallVec::new(), + status_code: 200, + response: Response::new(), + } } diff --git a/frameworks/Rust/tokio-minihttp/src/main.rs b/frameworks/Rust/tokio-minihttp/src/main.rs index ac576d722d0..2d459ddd0f2 100644 --- a/frameworks/Rust/tokio-minihttp/src/main.rs +++ b/frameworks/Rust/tokio-minihttp/src/main.rs @@ -18,11 +18,11 @@ use std::io; use futures::future::{self, Either}; use futures::stream; -use futures::{Future,Stream}; -use futures_cpupool::{CpuPool, CpuFuture}; -use r2d2_postgres::{TlsMode, PostgresConnectionManager}; +use futures::{Future, Stream}; +use futures_cpupool::{CpuFuture, CpuPool}; +use r2d2_postgres::{PostgresConnectionManager, TlsMode}; use rand::Rng; -use tokio_minihttp::{Request, Response, Http}; +use tokio_minihttp::{Http, Request, Response}; use tokio_proto::TcpServer; use tokio_service::Service; use url::Url; @@ -48,8 +48,8 @@ impl Service for Techempower { type Request = Request; type Response = Response; type Error = std::io::Error; - type Future = Either, - Box>>; + type Future = + Either, Box>>; fn call(&self, req: Request) -> Self::Future { // Bare-bones router @@ -64,7 +64,6 @@ impl Service for Techempower { Either::A(future::ok(resp)) } } - } } @@ -73,16 +72,18 @@ impl Techempower { let mut resp = Response::new(); resp.header("Content-Type", "text/plain") .body("Hello, World!"); - return resp + return resp; } fn json(&self) -> Response { - let json = Message { message: "Hello, World!" }; + let json = Message { + message: "Hello, World!", + }; let mut resp = Response::new(); resp.header("Content-Type", "application/json") .body(&serde_json::to_string(&json).unwrap()); - return resp + return resp; } fn db(&self) -> Box> { @@ -91,16 +92,18 @@ impl Techempower { let mut resp = Response::new(); resp.header("Content-Type", "application/json") .body(&serde_json::to_string(&msg).unwrap()); - return resp + return resp; })) } fn queries(&self, req: &Request) -> Box> { let url = format!("http://localhost{}", req.path()); let url = Url::parse(&url).unwrap(); - let queries = url.query_pairs().find(|pair| { - pair.0 == "queries" - }).and_then(|(_, value)| value.parse::().ok()).unwrap_or(1); + let queries = url + .query_pairs() + .find(|pair| pair.0 == "queries") + .and_then(|(_, value)| value.parse::().ok()) + .unwrap_or(1); let queries = cmp::max(1, queries); let queries = cmp::min(500, queries); @@ -117,7 +120,7 @@ impl Techempower { let mut resp = Response::new(); resp.header("Content-Type", "application/json") .body(&serde_json::to_string(&json).unwrap()); - return resp + return resp; })) } @@ -125,12 +128,14 @@ impl Techempower { let random_id = rand::thread_rng().gen_range(1, 10_001); let db = self.db_pool.clone(); self.thread_pool.spawn_fn(move || { - let conn = db.get().map_err(|e| { - io::Error::new(io::ErrorKind::Other, format!("timeout: {}", e)) - })?; - - let stmt = conn.prepare_cached("SELECT id,randomNumber \ - FROM World WHERE id = $1")?; + let conn = db + .get() + .map_err(|e| io::Error::new(io::ErrorKind::Other, format!("timeout: {}", e)))?; + + let stmt = conn.prepare_cached( + "SELECT id,randomNumber \ + FROM World WHERE id = $1", + )?; let rows = stmt.query(&[&random_id])?; let row = rows.get(0); @@ -148,9 +153,12 @@ fn main() { let dbhost = match option_env!("DBHOST") { Some(it) => it, - _ => "tfb-database" + _ => "tfb-database", }; - let db_url = format!("postgres://benchmarkdbuser:benchmarkdbpass@{}/hello_world", dbhost); + let db_url = format!( + "postgres://benchmarkdbuser:benchmarkdbpass@{}/hello_world", + dbhost + ); let db_config = r2d2::Config::default(); let db_manager = PostgresConnectionManager::new(&db_url[..], TlsMode::None).unwrap(); let db_pool = r2d2::Pool::new(db_config, db_manager).unwrap();