From 40c4df0000dfdd6a0761a6133660944011dde22e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 31 Jul 2023 16:36:30 +0100 Subject: [PATCH] refactor: extract hasher service --- src/services/hasher.rs | 28 ++++++++++++++++++++++++++++ src/services/mod.rs | 1 + src/services/torrent_file.rs | 16 +--------------- 3 files changed, 30 insertions(+), 15 deletions(-) create mode 100644 src/services/hasher.rs diff --git a/src/services/hasher.rs b/src/services/hasher.rs new file mode 100644 index 00000000..3ee4f6e8 --- /dev/null +++ b/src/services/hasher.rs @@ -0,0 +1,28 @@ +//! Hashing service +use sha1::{Digest, Sha1}; + +// Calculate the sha1 hash of a string +#[must_use] +pub fn sha1(data: &str) -> String { + // Create a Sha1 object + let mut hasher = Sha1::new(); + + // Write input message + hasher.update(data.as_bytes()); + + // Read hash digest and consume hasher + let result = hasher.finalize(); + + // Convert the hash (a byte array) to a string of hex characters + hex::encode(result) +} + +#[cfg(test)] +mod tests { + use crate::services::hasher::sha1; + + #[test] + fn it_should_hash_an_string() { + assert_eq!(sha1("hello world"), "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"); + } +} diff --git a/src/services/mod.rs b/src/services/mod.rs index b19bab37..b2431aec 100644 --- a/src/services/mod.rs +++ b/src/services/mod.rs @@ -2,6 +2,7 @@ pub mod about; pub mod authentication; pub mod category; +pub mod hasher; pub mod proxy; pub mod settings; pub mod tag; diff --git a/src/services/torrent_file.rs b/src/services/torrent_file.rs index 9eb423c2..3d02951d 100644 --- a/src/services/torrent_file.rs +++ b/src/services/torrent_file.rs @@ -1,8 +1,8 @@ //! This module contains the services related to torrent file management. -use sha1::{Digest, Sha1}; use uuid::Uuid; use crate::models::torrent_file::{Torrent, TorrentFile}; +use crate::services::hasher::sha1; pub struct NewTorrentInfoRequest { pub name: String, @@ -48,17 +48,3 @@ pub fn generate_random_torrent(id: Uuid) -> Torrent { Torrent::from_new_torrent_info_request(torrent_info_request) } - -fn sha1(data: &str) -> String { - // Create a Sha1 object - let mut hasher = Sha1::new(); - - // Write input message - hasher.update(data.as_bytes()); - - // Read hash digest and consume hasher - let result = hasher.finalize(); - - // Convert the hash (a byte array) to a string of hex characters - hex::encode(result) -}