diff --git a/src/cache/cache.rs b/src/cache/cache.rs index 8573ba0d..ce842448 100644 --- a/src/cache/cache.rs +++ b/src/cache/cache.rs @@ -27,6 +27,7 @@ pub struct BytesCache { } impl BytesCache { + #[must_use] pub fn new() -> Self { Self { bytes_table: IndexMap::new(), @@ -36,6 +37,7 @@ impl BytesCache { } // With a total capacity in bytes. + #[must_use] pub fn with_capacity(capacity: usize) -> Self { let mut new = Self::new(); @@ -45,6 +47,7 @@ impl BytesCache { } // With a limit for individual entry sizes. + #[must_use] pub fn with_entry_size_limit(entry_size_limit: usize) -> Self { let mut new = Self::new(); @@ -77,6 +80,7 @@ impl BytesCache { } // Size of all the entry bytes combined. + #[must_use] pub fn total_size(&self) -> usize { let mut size: usize = 0; diff --git a/src/cache/image/manager.rs b/src/cache/image/manager.rs index 8a6960a1..bfef1589 100644 --- a/src/cache/image/manager.rs +++ b/src/cache/image/manager.rs @@ -19,6 +19,7 @@ pub enum Error { type UserQuotas = HashMap; +#[must_use] pub fn now_in_secs() -> u64 { match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) { Ok(n) => n.as_secs(), @@ -36,6 +37,7 @@ pub struct ImageCacheQuota { } impl ImageCacheQuota { + #[must_use] pub fn new(user_id: i64, max_usage: usize, period_secs: u64) -> Self { Self { user_id, @@ -66,6 +68,7 @@ impl ImageCacheQuota { self.date_start_secs = now_in_secs(); } + #[must_use] pub fn is_reached(&self) -> bool { self.usage >= self.max_usage } diff --git a/src/console/commands/import_tracker_statistics.rs b/src/console/commands/import_tracker_statistics.rs index 61206449..ae0c51cc 100644 --- a/src/console/commands/import_tracker_statistics.rs +++ b/src/console/commands/import_tracker_statistics.rs @@ -4,7 +4,7 @@ use std::env; use std::sync::Arc; use derive_more::{Display, Error}; -use text_colorizer::*; +use text_colorizer::Colorize; use crate::bootstrap::config::init_configuration; use crate::bootstrap::logging; diff --git a/src/databases/mysql.rs b/src/databases/mysql.rs index 97f699a7..38e07e8b 100644 --- a/src/databases/mysql.rs +++ b/src/databases/mysql.rs @@ -467,7 +467,7 @@ impl Database for MysqlDatabase { // flatten the nested vec (this will however remove the) let announce_urls = announce_urls.iter().flatten().collect::>(); - for tracker_url in announce_urls.iter() { + for tracker_url in &announce_urls { let _ = query("INSERT INTO torrust_torrent_announce_urls (torrent_id, tracker_url) VALUES (?, ?)") .bind(torrent_id) .bind(tracker_url) @@ -520,7 +520,7 @@ impl Database for MysqlDatabase { match insert_torrent_info_result { Ok(_) => { let _ = tx.commit().await; - Ok(torrent_id as i64) + Ok(torrent_id) } Err(e) => { let _ = tx.rollback().await; @@ -560,7 +560,12 @@ impl Database for MysqlDatabase { let torrent_files: Vec = db_torrent_files .into_iter() .map(|tf| TorrentFile { - path: tf.path.unwrap_or_default().split('/').map(|v| v.to_string()).collect(), + path: tf + .path + .unwrap_or_default() + .split('/') + .map(std::string::ToString::to_string) + .collect(), length: tf.length, md5sum: tf.md5sum, }) diff --git a/src/databases/sqlite.rs b/src/databases/sqlite.rs index 3dc022e5..936dd8d5 100644 --- a/src/databases/sqlite.rs +++ b/src/databases/sqlite.rs @@ -92,7 +92,7 @@ impl Database for SqliteDatabase { match insert_user_profile_result { Ok(_) => { let _ = tx.commit().await; - Ok(user_id as i64) + Ok(user_id) } Err(e) => { let _ = tx.rollback().await; @@ -410,7 +410,7 @@ impl Database for SqliteDatabase { .bind(root_hash) .execute(&self.pool) .await - .map(|v| v.last_insert_rowid() as i64) + .map(|v| v.last_insert_rowid()) .map_err(|e| match e { sqlx::Error::Database(err) => { if err.message().contains("info_hash") { @@ -462,7 +462,7 @@ impl Database for SqliteDatabase { // flatten the nested vec (this will however remove the) let announce_urls = announce_urls.iter().flatten().collect::>(); - for tracker_url in announce_urls.iter() { + for tracker_url in &announce_urls { let _ = query("INSERT INTO torrust_torrent_announce_urls (torrent_id, tracker_url) VALUES (?, ?)") .bind(torrent_id) .bind(tracker_url) @@ -515,7 +515,7 @@ impl Database for SqliteDatabase { match insert_torrent_info_result { Ok(_) => { let _ = tx.commit().await; - Ok(torrent_id as i64) + Ok(torrent_id) } Err(e) => { let _ = tx.rollback().await; @@ -555,7 +555,12 @@ impl Database for SqliteDatabase { let torrent_files: Vec = db_torrent_files .into_iter() .map(|tf| TorrentFile { - path: tf.path.unwrap_or_default().split('/').map(|v| v.to_string()).collect(), + path: tf + .path + .unwrap_or_default() + .split('/') + .map(std::string::ToString::to_string) + .collect(), length: tf.length, md5sum: tf.md5sum, }) diff --git a/src/errors.rs b/src/errors.rs index 571fd9fe..a4eb7943 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -192,7 +192,7 @@ impl ResponseError for ServiceError { impl From for ServiceError { fn from(e: sqlx::Error) -> Self { - eprintln!("{:?}", e); + eprintln!("{e:?}"); if let Some(err) = e.as_database_error() { return if err.code() == Some(Cow::from("2067")) { @@ -229,28 +229,28 @@ impl From for ServiceError { impl From for ServiceError { fn from(e: argon2::password_hash::Error) -> Self { - eprintln!("{}", e); + eprintln!("{e}"); ServiceError::InternalServerError } } impl From for ServiceError { fn from(e: std::io::Error) -> Self { - eprintln!("{}", e); + eprintln!("{e}"); ServiceError::InternalServerError } } impl From> for ServiceError { fn from(e: Box) -> Self { - eprintln!("{}", e); + eprintln!("{e}"); ServiceError::InternalServerError } } impl From for ServiceError { fn from(e: serde_json::Error) -> Self { - eprintln!("{}", e); + eprintln!("{e}"); ServiceError::InternalServerError } } diff --git a/src/models/response.rs b/src/models/response.rs index 059e1c3b..58ec31fb 100644 --- a/src/models/response.rs +++ b/src/models/response.rs @@ -48,6 +48,7 @@ pub struct TorrentResponse { } impl TorrentResponse { + #[must_use] pub fn from_listing(torrent_listing: TorrentListing) -> TorrentResponse { TorrentResponse { torrent_id: torrent_listing.torrent_id, @@ -57,7 +58,7 @@ impl TorrentResponse { description: torrent_listing.description, category: Category { category_id: 0, - name: "".to_string(), + name: String::new(), num_torrents: 0, }, upload_date: torrent_listing.date_uploaded, @@ -66,7 +67,7 @@ impl TorrentResponse { leechers: torrent_listing.leechers, files: vec![], trackers: vec![], - magnet_link: "".to_string(), + magnet_link: String::new(), } } } diff --git a/src/models/torrent_file.rs b/src/models/torrent_file.rs index be3b6101..befc6161 100644 --- a/src/models/torrent_file.rs +++ b/src/models/torrent_file.rs @@ -42,13 +42,15 @@ pub struct TorrentInfo { impl TorrentInfo { /// torrent file can only hold a pieces key or a root hash key: /// http://www.bittorrent.org/beps/bep_0030.html + #[must_use] pub fn get_pieces_as_string(&self) -> String { match &self.pieces { - None => "".to_string(), + None => String::new(), Some(byte_buf) => bytes_to_hex(byte_buf.as_ref()), } } + #[must_use] pub fn get_root_hash_as_i64(&self) -> i64 { match &self.root_hash { None => 0i64, @@ -56,10 +58,12 @@ impl TorrentInfo { } } + #[must_use] pub fn is_a_single_file_torrent(&self) -> bool { self.length.is_some() } + #[must_use] pub fn is_a_multiple_file_torrent(&self) -> bool { self.files.is_some() } @@ -90,6 +94,7 @@ pub struct Torrent { } impl Torrent { + #[must_use] pub fn from_db_info_files_and_announce_urls( torrent_info: DbTorrentInfo, torrent_files: Vec, @@ -170,6 +175,7 @@ impl Torrent { } } + #[must_use] pub fn calculate_info_hash_as_bytes(&self) -> [u8; 20] { let info_bencoded = ser::to_bytes(&self.info).unwrap(); let mut hasher = Sha1::new(); @@ -180,10 +186,12 @@ impl Torrent { sum_bytes } + #[must_use] pub fn info_hash(&self) -> String { bytes_to_hex(&self.calculate_info_hash_as_bytes()) } + #[must_use] pub fn file_size(&self) -> i64 { if self.info.length.is_some() { self.info.length.unwrap() @@ -201,6 +209,7 @@ impl Torrent { } } + #[must_use] pub fn announce_urls(&self) -> Vec { if self.announce_list.is_none() { return vec![self.announce.clone().unwrap()]; @@ -214,10 +223,12 @@ impl Torrent { .collect::>() } + #[must_use] pub fn is_a_single_file_torrent(&self) -> bool { self.info.is_a_single_file_torrent() } + #[must_use] pub fn is_a_multiple_file_torrent(&self) -> bool { self.info.is_a_multiple_file_torrent() } diff --git a/src/routes/torrent.rs b/src/routes/torrent.rs index 293e31b5..ffba1724 100644 --- a/src/routes/torrent.rs +++ b/src/routes/torrent.rs @@ -370,9 +370,9 @@ async fn get_torrent_request_from_payload(mut payload: Multipart) -> Result, app_da return Err(ServiceError::UsernameInvalid); } - let email = payload.email.as_ref().unwrap_or(&"".to_string()).to_string(); + let email = payload.email.as_ref().unwrap_or(&String::new()).to_string(); let user_id = app_data .database diff --git a/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/category_transferrer.rs b/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/category_transferrer.rs index f3d83d9b..795c9f34 100644 --- a/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/category_transferrer.rs +++ b/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/category_transferrer.rs @@ -22,12 +22,11 @@ pub async fn transfer_categories(source_database: Arc, tar .await .unwrap(); - if id != cat.category_id { - panic!( - "Error copying category {:?} from source DB to the target DB", - &cat.category_id - ); - } + assert!( + id == cat.category_id, + "Error copying category {:?} from source DB to the target DB", + &cat.category_id + ); println!("[v2] category: {:?} {:?} added.", id, &cat.name); } diff --git a/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/torrent_transferrer.rs b/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/torrent_transferrer.rs index 88a681f0..89b4fdd7 100644 --- a/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/torrent_transferrer.rs +++ b/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/torrent_transferrer.rs @@ -29,21 +29,22 @@ pub async fn transfer_torrents( let uploader = source_database.get_user_by_username(&torrent.uploader).await.unwrap(); - if uploader.username != torrent.uploader { - panic!( - "Error copying torrent with id {:?}. + assert!( + uploader.username == torrent.uploader, + "Error copying torrent with id {:?}. Username (`uploader`) in `torrust_torrents` table does not match `username` in `torrust_users` table", - &torrent.torrent_id - ); - } + &torrent.torrent_id + ); let filepath = format!("{}/{}.torrent", upload_path, &torrent.torrent_id); let torrent_from_file_result = read_torrent_from_file(&filepath); - if torrent_from_file_result.is_err() { - panic!("Error torrent file not found: {:?}", &filepath); - } + assert!( + torrent_from_file_result.is_ok(), + "Error torrent file not found: {:?}", + &filepath + ); let torrent_from_file = torrent_from_file_result.unwrap(); @@ -52,12 +53,11 @@ pub async fn transfer_torrents( .await .unwrap(); - if id != torrent.torrent_id { - panic!( - "Error copying torrent {:?} from source DB to the target DB", - &torrent.torrent_id - ); - } + assert!( + id == torrent.torrent_id, + "Error copying torrent {:?} from source DB to the target DB", + &torrent.torrent_id + ); println!("[v2][torrust_torrents] torrent with id {:?} added.", &torrent.torrent_id); @@ -144,7 +144,7 @@ pub async fn transfer_torrents( .flatten() .collect::>(); - for tracker_url in announce_urls.iter() { + for tracker_url in &announce_urls { println!( "[v2][torrust_torrent_announce_urls][announce-list] adding the torrent announce url for torrent id {:?} ...", &torrent.torrent_id diff --git a/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/tracker_key_transferrer.rs b/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/tracker_key_transferrer.rs index 51c451b0..1e475d8e 100644 --- a/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/tracker_key_transferrer.rs +++ b/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/tracker_key_transferrer.rs @@ -28,12 +28,11 @@ pub async fn transfer_tracker_keys(source_database: Arc, t .await .unwrap(); - if id != tracker_key.key_id { - panic!( - "Error copying tracker key {:?} from source DB to the target DB", - &tracker_key.key_id - ); - } + assert!( + id == tracker_key.key_id, + "Error copying tracker key {:?} from source DB to the target DB", + &tracker_key.key_id + ); println!( "[v2][torrust_tracker_keys] tracker key with id {:?} added.", diff --git a/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/user_transferrer.rs b/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/user_transferrer.rs index 76f5ff44..76791d32 100644 --- a/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/user_transferrer.rs +++ b/src/upgrades/from_v1_0_0_to_v2_0_0/transferrers/user_transferrer.rs @@ -27,9 +27,11 @@ pub async fn transfer_users( .await .unwrap(); - if id != user.user_id { - panic!("Error copying user {:?} from source DB to the target DB", &user.user_id); - } + assert!( + id == user.user_id, + "Error copying user {:?} from source DB to the target DB", + &user.user_id + ); println!("[v2][torrust_users] user: {:?} {:?} added.", &user.user_id, &user.username); diff --git a/src/upgrades/from_v1_0_0_to_v2_0_0/upgrader.rs b/src/upgrades/from_v1_0_0_to_v2_0_0/upgrader.rs index 0cc0ea53..6e8901f5 100644 --- a/src/upgrades/from_v1_0_0_to_v2_0_0/upgrader.rs +++ b/src/upgrades/from_v1_0_0_to_v2_0_0/upgrader.rs @@ -15,7 +15,7 @@ use std::env; use std::time::SystemTime; use chrono::prelude::{DateTime, Utc}; -use text_colorizer::*; +use text_colorizer::Colorize; use crate::upgrades::from_v1_0_0_to_v2_0_0::databases::{current_db, migrate_target_database, new_db, reset_target_database}; use crate::upgrades::from_v1_0_0_to_v2_0_0::transferrers::category_transferrer::transfer_categories; @@ -102,6 +102,7 @@ pub async fn upgrade(args: &Arguments, date_imported: &str) { /// Current datetime in ISO8601 without time zone. /// For example: 2022-11-10 10:35:15 +#[must_use] pub fn datetime_iso_8601() -> String { let dt: DateTime = SystemTime::now().into(); format!("{}", dt.format("%Y-%m-%d %H:%M:%S")) diff --git a/src/utils/hex.rs b/src/utils/hex.rs index 7903c741..3cc9f57e 100644 --- a/src/utils/hex.rs +++ b/src/utils/hex.rs @@ -1,11 +1,12 @@ use std::fmt::Write; use std::num::ParseIntError; +#[must_use] pub fn bytes_to_hex(bytes: &[u8]) -> String { let mut s = String::with_capacity(2 * bytes.len()); for byte in bytes { - write!(s, "{:02X}", byte).unwrap(); + write!(s, "{byte:02X}").unwrap(); } s diff --git a/src/utils/parse_torrent.rs b/src/utils/parse_torrent.rs index e272ede8..d15e5c82 100644 --- a/src/utils/parse_torrent.rs +++ b/src/utils/parse_torrent.rs @@ -8,7 +8,7 @@ pub fn decode_torrent(bytes: &[u8]) -> Result> { match de::from_bytes::(bytes) { Ok(torrent) => Ok(torrent), Err(e) => { - println!("{:?}", e); + println!("{e:?}"); Err(e.into()) } } @@ -18,7 +18,7 @@ pub fn encode_torrent(torrent: &Torrent) -> Result, Error> { match serde_bencode::to_bytes(torrent) { Ok(bencode_bytes) => Ok(bencode_bytes), Err(e) => { - eprintln!("{:?}", e); + eprintln!("{e:?}"); Err(e) } } diff --git a/src/utils/regex.rs b/src/utils/regex.rs index 4c5b55ff..22df6176 100644 --- a/src/utils/regex.rs +++ b/src/utils/regex.rs @@ -1,5 +1,6 @@ use regex::Regex; +#[must_use] pub fn validate_email_address(email_address_to_be_checked: &str) -> bool { let email_regex = Regex::new(r"^([a-z\d_+]([a-z\d_+.]*[a-z\d_+])?)@([a-z\d]+([\-.][a-z\d]+)*\.[a-z]{2,6})").unwrap(); diff --git a/tests/databases/tests.rs b/tests/databases/tests.rs index d74088ff..834fdc47 100644 --- a/tests/databases/tests.rs +++ b/tests/databases/tests.rs @@ -81,7 +81,7 @@ pub async fn it_can_add_a_torrent_and_tracker_stats_to_that_torrent(db: &Box (Arc, Arc } async fn source_db_connection(source_database_file: &str) -> Arc { - Arc::new(SqliteDatabaseV1_0_0::db_connection(&source_database_file).await) + Arc::new(SqliteDatabaseV1_0_0::db_connection(source_database_file).await) } async fn target_db_connection(target_database_file: &str) -> Arc { - Arc::new(SqliteDatabaseV2_0_0::db_connection(&target_database_file).await) + Arc::new(SqliteDatabaseV2_0_0::db_connection(target_database_file).await) } /// Reset databases from previous executions fn reset_databases(source_database_file: &str, target_database_file: &str) { if Path::new(source_database_file).exists() { - fs::remove_file(&source_database_file).expect("Can't remove the source DB file."); + fs::remove_file(source_database_file).expect("Can't remove the source DB file."); } if Path::new(target_database_file).exists() { - fs::remove_file(&target_database_file).expect("Can't remove the target DB file."); + fs::remove_file(target_database_file).expect("Can't remove the target DB file."); } }