Skip to content

Commit

Permalink
refactor: extract hasher service
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Jul 31, 2023
1 parent b2870b9 commit 40c4df0
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 15 deletions.
28 changes: 28 additions & 0 deletions src/services/hasher.rs
Original file line number Diff line number Diff line change
@@ -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");
}
}
1 change: 1 addition & 0 deletions src/services/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
16 changes: 1 addition & 15 deletions src/services/torrent_file.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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)
}

0 comments on commit 40c4df0

Please sign in to comment.