From d43b49e7e467a310723fe9135b9297db95bef57e Mon Sep 17 00:00:00 2001 From: spikecodes <19519553+spikecodes@users.noreply.github.com> Date: Fri, 1 Jan 2021 12:33:57 -0800 Subject: [PATCH] Optimize Rust code with Clippy --- src/main.rs | 6 +++--- src/post.rs | 42 +++++++++++++++++++++--------------------- src/proxy.rs | 2 +- src/search.rs | 12 ++++++------ src/subreddit.rs | 28 ++++++++++++---------------- src/user.rs | 16 ++++++++-------- src/utils.rs | 38 ++++++++++++++++++++------------------ 7 files changed, 71 insertions(+), 73 deletions(-) diff --git a/src/main.rs b/src/main.rs index 1a6c7b2..ddee86c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -31,7 +31,7 @@ async fn main() -> std::io::Result<()> { if args.len() > 1 { for arg in args { if arg.starts_with("--address=") || arg.starts_with("-a=") { - let split: Vec<&str> = arg.split("=").collect(); + let split: Vec<&str> = arg.split('=').collect(); address = split[1].to_string(); } } @@ -48,7 +48,7 @@ async fn main() -> std::io::Result<()> { .default_service(web::get().to(utils::error)) // GENERAL SERVICES .route("/style.css/", web::get().to(style)) - .route("/favicon.ico/", web::get().to(|| HttpResponse::Ok())) + .route("/favicon.ico/", web::get().to(HttpResponse::Ok)) .route("/robots.txt/", web::get().to(robots)) // PROXY SERVICE .route("/proxy/{url:.*}/", web::get().to(proxy::handler)) @@ -72,7 +72,7 @@ async fn main() -> std::io::Result<()> { .route("/r/{sub}/comments/{id}/{title}/{comment_id}/", web::get().to(post::item)) }) .bind(address.clone()) - .expect(format!("Cannot bind to the address: {}", address).as_str()) + .unwrap_or_else(|_| panic!("Cannot bind to the address: {}", address)) .run() .await } diff --git a/src/post.rs b/src/post.rs index 152c1e7..668912b 100644 --- a/src/post.rs +++ b/src/post.rs @@ -18,7 +18,7 @@ struct PostTemplate { pub async fn item(req: HttpRequest) -> Result { let path = format!("{}.json?{}&raw_json=1", req.path(), req.query_string()); - let sort = param(&path, "sort").await; + let sort = param(&path, "sort"); let id = req.match_info().get("id").unwrap_or("").to_string(); // Log the post ID being fetched in debug mode @@ -80,22 +80,22 @@ async fn parse_post(json: serde_json::Value) -> Result { // Build a post using data parsed from Reddit post API let post = Post { - title: val(post_data, "title").await, - community: val(post_data, "subreddit").await, - body: val(post_data, "selftext_html").await, - author: val(post_data, "author").await, + title: val(post_data, "title"), + community: val(post_data, "subreddit"), + body: val(post_data, "selftext_html"), + author: val(post_data, "author"), author_flair: Flair( - val(post_data, "author_flair_text").await, - val(post_data, "author_flair_background_color").await, - val(post_data, "author_flair_text_color").await, + val(post_data, "author_flair_text"), + val(post_data, "author_flair_background_color"), + val(post_data, "author_flair_text_color"), ), - url: val(post_data, "permalink").await, + url: val(post_data, "permalink"), score: format_num(score), post_type: media.0, flair: Flair( - val(post_data, "link_flair_text").await, - val(post_data, "link_flair_background_color").await, - if val(post_data, "link_flair_text_color").await == "dark" { + val(post_data, "link_flair_text"), + val(post_data, "link_flair_background_color"), + if val(post_data, "link_flair_text_color") == "dark" { "black".to_string() } else { "white".to_string() @@ -128,25 +128,25 @@ async fn parse_comments(json: serde_json::Value) -> Result, &'stati } let score = comment["data"]["score"].as_i64().unwrap_or(0); - let body = val(comment, "body_html").await; + let body = val(comment, "body_html"); let replies: Vec = if comment["data"]["replies"].is_object() { - parse_comments(comment["data"]["replies"].clone()).await.unwrap_or(Vec::new()) + parse_comments(comment["data"]["replies"].clone()).await.unwrap_or_default() } else { Vec::new() }; comments.push(Comment { - id: val(comment, "id").await, - body: body, - author: val(comment, "author").await, + id: val(comment, "id"), + body, + author: val(comment, "author"), score: format_num(score), time: Utc.timestamp(unix_time, 0).format("%b %e %Y %H:%M UTC").to_string(), - replies: replies, + replies, flair: Flair( - val(comment, "author_flair_text").await, - val(comment, "author_flair_background_color").await, - val(comment, "author_flair_text_color").await, + val(comment, "author_flair_text"), + val(comment, "author_flair_background_color"), + val(comment, "author_flair_text_color"), ), }); } diff --git a/src/proxy.rs b/src/proxy.rs index 8ba015f..71a1a5a 100644 --- a/src/proxy.rs +++ b/src/proxy.rs @@ -23,7 +23,7 @@ pub async fn handler(web::Path(url): web::Path) -> Result .send() .await .map_err(Error::from) - .and_then(|res| Ok(HttpResponse::build(res.status()).streaming(res))) + .map(|res| HttpResponse::build(res.status()).streaming(res)) } else { Ok(HttpResponse::Ok().body("")) } diff --git a/src/search.rs b/src/search.rs index 2e0a063..957aef7 100644 --- a/src/search.rs +++ b/src/search.rs @@ -18,11 +18,11 @@ struct SearchTemplate { // SERVICES pub async fn find(req: HttpRequest) -> Result { let path = format!("{}.json?{}", req.path(), req.query_string()); - let q = param(&path, "q").await; - let sort = if param(&path, "sort").await.is_empty() { + let q = param(&path, "q"); + let sort = if param(&path, "sort").is_empty() { "relevance".to_string() } else { - param(&path, "sort").await + param(&path, "sort") }; let sub = req.match_info().get("sub").unwrap_or("").to_string(); @@ -36,9 +36,9 @@ pub async fn find(req: HttpRequest) -> Result { let s = SearchTemplate { posts: items.0, query: q, - sub: sub, - sort: (sort, param(&path, "t").await), - ends: (param(&path, "after").await, items.1), + sub, + sort: (sort, param(&path, "t")), + ends: (param(&path, "after"), items.1), } .render() .unwrap(); diff --git a/src/subreddit.rs b/src/subreddit.rs index 718976b..ac5ff27 100644 --- a/src/subreddit.rs +++ b/src/subreddit.rs @@ -21,7 +21,7 @@ pub async fn page(req: HttpRequest) -> Result { let sub = req.match_info().get("sub").unwrap_or("popular").to_string(); let sort = req.match_info().get("sort").unwrap_or("hot").to_string(); - let sub_result = if !&sub.contains("+") && sub != "popular" { + let sub_result = if !&sub.contains('+') && sub != "popular" { subreddit(&sub).await } else { Ok(Subreddit::default()) @@ -31,14 +31,14 @@ pub async fn page(req: HttpRequest) -> Result { if posts.is_err() { error(posts.err().unwrap().to_string()).await } else { - let sub = sub_result.unwrap_or(Subreddit::default()); + let sub = sub_result.unwrap_or_default(); let items = posts.unwrap(); let s = SubredditTemplate { - sub: sub, + sub, posts: items.0, - sort: (sort, param(&path, "t").await), - ends: (param(&path, "after").await, items.1), + sort: (sort, param(&path, "t")), + ends: (param(&path, "after"), items.1), } .render() .unwrap(); @@ -47,7 +47,7 @@ pub async fn page(req: HttpRequest) -> Result { } // SUBREDDIT -async fn subreddit(sub: &String) -> Result { +async fn subreddit(sub: &str) -> Result { // Build the Reddit JSON API url let url: String = format!("r/{}/about.json?raw_json=1", sub); @@ -67,18 +67,14 @@ async fn subreddit(sub: &String) -> Result { let active = res["data"]["accounts_active"].as_u64().unwrap_or(0); // Fetch subreddit icon either from the community_icon or icon_img value - let community_icon: &str = res["data"]["community_icon"].as_str().unwrap_or("").split("?").collect::>()[0]; - let icon = if community_icon.is_empty() { - val(&res, "icon_img").await - } else { - community_icon.to_string() - }; + let community_icon: &str = res["data"]["community_icon"].as_str().unwrap_or("").split('?').collect::>()[0]; + let icon = if community_icon.is_empty() { val(&res, "icon_img") } else { community_icon.to_string() }; let sub = Subreddit { - name: val(&res, "display_name").await, - title: val(&res, "title").await, - description: val(&res, "public_description").await, - info: val(&res, "description_html").await.replace("\\", ""), + name: val(&res, "display_name"), + title: val(&res, "title"), + description: val(&res, "public_description"), + info: val(&res, "description_html").replace("\\", ""), icon: format_url(icon).await, members: format_num(members.try_into().unwrap_or(0)), active: format_num(active.try_into().unwrap_or(0)), diff --git a/src/user.rs b/src/user.rs index cd089fc..6324522 100644 --- a/src/user.rs +++ b/src/user.rs @@ -19,7 +19,7 @@ pub async fn profile(req: HttpRequest) -> Result { let path = format!("{}.json?{}&raw_json=1", req.path(), req.query_string()); // Retrieve other variables from Libreddit request - let sort = param(&path, "sort").await; + let sort = param(&path, "sort"); let username = req.match_info().get("username").unwrap_or("").to_string(); // Request user profile data and user posts/comments from Reddit @@ -35,8 +35,8 @@ pub async fn profile(req: HttpRequest) -> Result { let s = UserTemplate { user: user.unwrap(), posts: posts_unwrapped.0, - sort: (sort, param(&path, "t").await), - ends: (param(&path, "after").await, posts_unwrapped.1), + sort: (sort, param(&path, "t")), + ends: (param(&path, "after"), posts_unwrapped.1), } .render() .unwrap(); @@ -50,7 +50,7 @@ pub async fn profile(req: HttpRequest) -> Result { // } // USER -async fn user(name: &String) -> Result { +async fn user(name: &str) -> Result { // Build the Reddit JSON API path let path: String = format!("user/{}/about.json", name); @@ -71,11 +71,11 @@ async fn user(name: &String) -> Result { // Parse the JSON output into a User struct Ok(User { name: name.to_string(), - title: nested_val(&res, "subreddit", "title").await, - icon: format_url(nested_val(&res, "subreddit", "icon_img").await).await, + title: nested_val(&res, "subreddit", "title"), + icon: format_url(nested_val(&res, "subreddit", "icon_img")).await, karma: res["data"]["total_karma"].as_i64().unwrap(), created: Utc.timestamp(created, 0).format("%b %e, %Y").to_string(), - banner: nested_val(&res, "subreddit", "banner_img").await, - description: nested_val(&res, "subreddit", "public_description").await, + banner: nested_val(&res, "subreddit", "banner_img"), + description: nested_val(&res, "subreddit", "public_description"), }) } diff --git a/src/utils.rs b/src/utils.rs index 852b0e0..f559b76 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -94,7 +94,7 @@ pub struct ErrorTemplate { // // Grab a query param from a url -pub async fn param(path: &String, value: &str) -> String { +pub fn param(path: &str, value: &str) -> String { let url = Url::parse(format!("https://reddit.com/{}", path).as_str()).unwrap(); let pairs: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect(); pairs.get(value).unwrap_or(&String::new()).to_owned() @@ -129,12 +129,12 @@ pub fn format_num(num: i64) -> String { // // val() function used to parse JSON from Reddit APIs -pub async fn val(j: &serde_json::Value, k: &str) -> String { +pub fn val(j: &serde_json::Value, k: &str) -> String { String::from(j["data"][k].as_str().unwrap_or("")) } // nested_val() function used to parse JSON from Reddit APIs -pub async fn nested_val(j: &serde_json::Value, n: &str, k: &str) -> String { +pub fn nested_val(j: &serde_json::Value, n: &str, k: &str) -> String { String::from(j["data"][n][k].as_str().unwrap()) } @@ -157,32 +157,32 @@ pub async fn fetch_posts(path: String, fallback_title: String) -> Result<(Vec = Vec::new(); for post in post_list { - let img = if val(post, "thumbnail").await.starts_with("https:/") { - format_url(val(post, "thumbnail").await).await + let img = if val(post, "thumbnail").starts_with("https:/") { + format_url(val(post, "thumbnail")).await } else { String::new() }; let unix_time: i64 = post["data"]["created_utc"].as_f64().unwrap().round() as i64; let score = post["data"]["score"].as_i64().unwrap(); - let title = val(post, "title").await; + let title = val(post, "title"); posts.push(Post { title: if title.is_empty() { fallback_title.to_owned() } else { title }, - community: val(post, "subreddit").await, - body: val(post, "body_html").await, - author: val(post, "author").await, + community: val(post, "subreddit"), + body: val(post, "body_html"), + author: val(post, "author"), author_flair: Flair( - val(post, "author_flair_text").await, - val(post, "author_flair_background_color").await, - val(post, "author_flair_text_color").await, + val(post, "author_flair_text"), + val(post, "author_flair_background_color"), + val(post, "author_flair_text_color"), ), score: format_num(score), post_type: "link".to_string(), media: img, flair: Flair( - val(post, "link_flair_text").await, - val(post, "link_flair_background_color").await, - if val(post, "link_flair_text_color").await == "dark" { + val(post, "link_flair_text"), + val(post, "link_flair_background_color"), + if val(post, "link_flair_text_color") == "dark" { "black".to_string() } else { "white".to_string() @@ -192,7 +192,7 @@ pub async fn fetch_posts(path: String, fallback_title: String) -> Result<(Vec Result { let json: Value = from_str(body.as_str()).unwrap_or(Value::Null); if !success { - println!("! {} - {}", url, "Page not found"); + #[cfg(debug_assertions)] + dbg!(format!("{} - Page not found", url)); Err("Page not found") } else if json == Value::Null { - println!("! {} - {}", url, "Failed to parse page JSON data"); + #[cfg(debug_assertions)] + dbg!(format!("{} - Failed to parse page JSON data", url)); Err("Failed to parse page JSON data") } else { Ok(json)