Optimize type casting

This commit is contained in:
spikecodes 2021-03-08 18:49:06 -08:00
parent 213babb057
commit bf783c2f3a
No known key found for this signature in database
GPG Key ID: 004CECFF9B463BCB
8 changed files with 32 additions and 28 deletions

View File

@ -1,3 +1,7 @@
// Global specifiers
#![forbid(unsafe_code)]
#![warn(clippy::pedantic, clippy::all)]
// Reference local files // Reference local files
mod post; mod post;
mod proxy; mod proxy;
@ -48,10 +52,10 @@ impl<State: Clone + Send + Sync + 'static> Middleware<State> for NormalizePath {
if path.ends_with('/') { if path.ends_with('/') {
Ok(next.run(request).await) Ok(next.run(request).await)
} else { } else {
let normalized = if query != "" { let normalized = if query.is_empty() {
format!("{}/?{}", path.replace("//", "/"), query)
} else {
format!("{}/", path.replace("//", "/")) format!("{}/", path.replace("//", "/"))
} else {
format!("{}/?{}", path.replace("//", "/"), query)
}; };
Ok(redirect(normalized)) Ok(redirect(normalized))
} }

View File

@ -1,5 +1,5 @@
// CRATES // CRATES
use crate::utils::*; use crate::utils::{Author, Comment, Flags, Flair, FlairPart, Media, Post, Preferences, cookie, error, format_num, format_url, param, request, rewrite_urls, template, time, val};
use tide::Request; use tide::Request;
use async_recursion::async_recursion; use async_recursion::async_recursion;
@ -68,7 +68,7 @@ async fn parse_post(json: &serde_json::Value) -> Post {
let post: &serde_json::Value = &json["data"]["children"][0]; let post: &serde_json::Value = &json["data"]["children"][0];
// Grab UTC time as unix timestamp // Grab UTC time as unix timestamp
let (rel_time, created) = time(post["data"]["created_utc"].as_f64().unwrap_or_default()); let (rel_time, created) = time(post["data"]["created_utc"].as_i64().unwrap_or_default());
// Parse post score and upvote ratio // Parse post score and upvote ratio
let score = post["data"]["score"].as_i64().unwrap_or_default(); let score = post["data"]["score"].as_i64().unwrap_or_default();
let ratio: f64 = post["data"]["upvote_ratio"].as_f64().unwrap_or(1.0) * 100.0; let ratio: f64 = post["data"]["upvote_ratio"].as_f64().unwrap_or(1.0) * 100.0;
@ -149,10 +149,10 @@ async fn parse_comments(json: &serde_json::Value, post_link: &str, post_author:
let kind = comment["kind"].as_str().unwrap_or_default().to_string(); let kind = comment["kind"].as_str().unwrap_or_default().to_string();
let data = &comment["data"]; let data = &comment["data"];
let unix_time = data["created_utc"].as_f64().unwrap_or_default(); let unix_time = data["created_utc"].as_i64().unwrap_or_default();
let (rel_time, created) = time(unix_time); let (rel_time, created) = time(unix_time);
let edited = match data["edited"].as_f64() { let edited = match data["edited"].as_i64() {
Some(stamp) => time(stamp), Some(stamp) => time(stamp),
None => (String::new(), String::new()), None => (String::new(), String::new()),
}; };
@ -196,7 +196,7 @@ async fn parse_comments(json: &serde_json::Value, post_link: &str, post_author:
distinguished: val(&comment, "distinguished"), distinguished: val(&comment, "distinguished"),
}, },
score: if data["score_hidden"].as_bool().unwrap_or_default() { score: if data["score_hidden"].as_bool().unwrap_or_default() {
"".to_string() "\u{2022}".to_string()
} else { } else {
format_num(score) format_num(score)
}, },

View File

@ -15,7 +15,7 @@ pub async fn handler(req: Request<()>, format: &str, params: Vec<&str>) -> tide:
async fn request(url: String) -> tide::Result { async fn request(url: String) -> tide::Result {
match surf::get(url).await { match surf::get(url).await {
Ok(res) => { Ok(res) => {
let content_length = res.header("Content-Length").map(|v| v.to_string()).unwrap_or_default(); let content_length = res.header("Content-Length").map(std::string::ToString::to_string).unwrap_or_default();
let content_type = res.content_type().map(|m| m.to_string()).unwrap_or_default(); let content_type = res.content_type().map(|m| m.to_string()).unwrap_or_default();
Ok( Ok(

View File

@ -84,7 +84,7 @@ async fn search_subreddits(q: &str) -> Vec<Subreddit> {
name: val(subreddit, "display_name_prefixed"), name: val(subreddit, "display_name_prefixed"),
url: val(subreddit, "url"), url: val(subreddit, "url"),
description: val(subreddit, "public_description"), description: val(subreddit, "public_description"),
subscribers: subreddit["data"]["subscribers"].as_u64().unwrap_or_default() as i64, subscribers: subreddit["data"]["subscribers"].as_i64().unwrap_or_default(),
}) })
.collect::<Vec<Subreddit>>(), .collect::<Vec<Subreddit>>(),
_ => Vec::new(), _ => Vec::new(),

View File

@ -13,7 +13,7 @@ struct SettingsTemplate {
#[derive(serde::Deserialize, Default)] #[derive(serde::Deserialize, Default)]
#[serde(default)] #[serde(default)]
pub struct SettingsForm { pub struct Form {
theme: Option<String>, theme: Option<String>,
front_page: Option<String>, front_page: Option<String>,
layout: Option<String>, layout: Option<String>,
@ -33,7 +33,7 @@ pub async fn get(req: Request<()>) -> tide::Result {
// Set cookies using response "Set-Cookie" header // Set cookies using response "Set-Cookie" header
pub async fn set(mut req: Request<()>) -> tide::Result { pub async fn set(mut req: Request<()>) -> tide::Result {
let form: SettingsForm = req.body_form().await.unwrap_or_default(); let form: Form = req.body_form().await.unwrap_or_default();
let mut res = redirect("/settings".to_string()); let mut res = redirect("/settings".to_string());
@ -58,7 +58,7 @@ pub async fn set(mut req: Request<()>) -> tide::Result {
// Set cookies using response "Set-Cookie" header // Set cookies using response "Set-Cookie" header
pub async fn restore(req: Request<()>) -> tide::Result { pub async fn restore(req: Request<()>) -> tide::Result {
let form: SettingsForm = req.query()?; let form: Form = req.query()?;
let path = match form.redirect { let path = match form.redirect {
Some(value) => format!("/{}/", value), Some(value) => format!("/{}/", value),

View File

@ -1,5 +1,5 @@
// CRATES // CRATES
use crate::utils::*; use crate::utils::{Post, Preferences, Subreddit, cookie, error, format_num, format_url, param, redirect, request, rewrite_urls, template, val};
use askama::Template; use askama::Template;
use tide::{http::Cookie, Request}; use tide::{http::Cookie, Request};
use time::{Duration, OffsetDateTime}; use time::{Duration, OffsetDateTime};
@ -108,10 +108,10 @@ pub async fn subscriptions(req: Request<()>) -> tide::Result {
// Redirect back to subreddit // Redirect back to subreddit
// check for redirect parameter if unsubscribing from outside sidebar // check for redirect parameter if unsubscribing from outside sidebar
let redirect_path = param(&format!("/?{}", query), "redirect"); let redirect_path = param(&format!("/?{}", query), "redirect");
let path = if !redirect_path.is_empty() { let path = if redirect_path.is_empty() {
format!("/{}/", redirect_path)
} else {
format!("/r/{}", sub) format!("/r/{}", sub)
} else {
format!("/{}/", redirect_path)
}; };
let mut res = redirect(path); let mut res = redirect(path);
@ -139,9 +139,9 @@ pub async fn wiki(req: Request<()>) -> tide::Result {
let path: String = format!("/r/{}/wiki/{}.json?raw_json=1", sub, page); let path: String = format!("/r/{}/wiki/{}.json?raw_json=1", sub, page);
match request(path).await { match request(path).await {
Ok(res) => template(WikiTemplate { Ok(response) => template(WikiTemplate {
sub, sub,
wiki: rewrite_urls(res["data"]["content_html"].as_str().unwrap_or_default()), wiki: rewrite_urls(response["data"]["content_html"].as_str().unwrap_or_default()),
page, page,
prefs: Preferences::new(req), prefs: Preferences::new(req),
}), }),
@ -159,8 +159,8 @@ async fn subreddit(sub: &str) -> Result<Subreddit, String> {
// If success, receive JSON in response // If success, receive JSON in response
Ok(res) => { Ok(res) => {
// Metadata regarding the subreddit // Metadata regarding the subreddit
let members: i64 = res["data"]["subscribers"].as_u64().unwrap_or_default() as i64; let members: i64 = res["data"]["subscribers"].as_i64().unwrap_or_default();
let active: i64 = res["data"]["accounts_active"].as_u64().unwrap_or_default() as i64; let active: i64 = res["data"]["accounts_active"].as_i64().unwrap_or_default();
// Fetch subreddit icon either from the community_icon or icon_img value // Fetch subreddit icon either from the community_icon or icon_img value
let community_icon: &str = res["data"]["community_icon"].as_str().map_or("", |s| s.split('?').collect::<Vec<&str>>()[0]); let community_icon: &str = res["data"]["community_icon"].as_str().map_or("", |s| s.split('?').collect::<Vec<&str>>()[0]);

View File

@ -1,5 +1,5 @@
// CRATES // CRATES
use crate::utils::*; use crate::utils::{Post, Preferences, User, error, format_url, param, request, template};
use askama::Template; use askama::Template;
use tide::Request; use tide::Request;
use time::OffsetDateTime; use time::OffsetDateTime;
@ -55,7 +55,7 @@ async fn user(name: &str) -> Result<User, String> {
// If success, receive JSON in response // If success, receive JSON in response
Ok(res) => { Ok(res) => {
// Grab creation date as unix timestamp // Grab creation date as unix timestamp
let created: i64 = res["data"]["created"].as_f64().unwrap_or(0.0).round() as i64; let created: i64 = res["data"]["created"].as_i64().unwrap_or(0);
// nested_val function used to parse JSON from Reddit APIs // nested_val function used to parse JSON from Reddit APIs
let about = |item| res["data"]["subreddit"][item].as_str().unwrap_or_default().to_string(); let about = |item| res["data"]["subreddit"][item].as_str().unwrap_or_default().to_string();

View File

@ -123,7 +123,7 @@ impl Media {
let url = if post_type == "self" || post_type == "link" { let url = if post_type == "self" || post_type == "link" {
url_val.as_str().unwrap_or_default().to_string() url_val.as_str().unwrap_or_default().to_string()
} else { } else {
format_url(url_val.as_str().unwrap_or_default()).to_string() format_url(url_val.as_str().unwrap_or_default())
}; };
( (
@ -221,7 +221,7 @@ impl Post {
for post in post_list { for post in post_list {
let data = &post["data"]; let data = &post["data"];
let (rel_time, created) = time(data["created_utc"].as_f64().unwrap_or_default()); let (rel_time, created) = time(data["created_utc"].as_i64().unwrap_or_default());
let score = data["score"].as_i64().unwrap_or_default(); let score = data["score"].as_i64().unwrap_or_default();
let ratio: f64 = data["upvote_ratio"].as_f64().unwrap_or(1.0) * 100.0; let ratio: f64 = data["upvote_ratio"].as_f64().unwrap_or(1.0) * 100.0;
let title = val(post, "title"); let title = val(post, "title");
@ -249,7 +249,7 @@ impl Post {
distinguished: val(post, "distinguished"), distinguished: val(post, "distinguished"),
}, },
score: if data["hide_score"].as_bool().unwrap_or_default() { score: if data["hide_score"].as_bool().unwrap_or_default() {
"".to_string() "\u{2022}".to_string()
} else { } else {
format_num(score) format_num(score)
}, },
@ -459,8 +459,8 @@ pub fn format_num(num: i64) -> String {
} }
// Parse a relative and absolute time from a UNIX timestamp // Parse a relative and absolute time from a UNIX timestamp
pub fn time(created: f64) -> (String, String) { pub fn time(created: i64) -> (String, String) {
let time = OffsetDateTime::from_unix_timestamp(created.round() as i64); let time = OffsetDateTime::from_unix_timestamp(created);
let time_delta = OffsetDateTime::now_utc() - time; let time_delta = OffsetDateTime::now_utc() - time;
// If the time difference is more than a month, show full date // If the time difference is more than a month, show full date