lib2fas/helpers.rs
1use core::hash::{Hash, Hasher};
2use std::hash::DefaultHasher;
3use std::time::{SystemTime, UNIX_EPOCH};
4
5/// Returns the current time as the number of seconds since the Unix epoch.
6///
7/// # Returns
8/// - `Some(u64)`: The current timestamp in seconds.
9/// - `None`: If the system clock is unavailable or an error occurs.
10#[must_use]
11pub fn now() -> Option<u64> {
12 Some(SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs())
13}
14
15/// Calculates a 64-bit hash for the given data using the default hasher.
16///
17/// This function is useful for generating unique identifiers or fingerprints for data that
18/// implements the `Hash` trait. It uses Rust's `DefaultHasher`, which provides a simple and
19/// efficient hashing mechanism.
20///
21/// # Parameters
22/// - `data`: A reference to the data to be hashed. The type must implement the `Hash` trait.
23///
24/// # Returns
25/// - A 64-bit unsigned integer representing the hash of the input data.
26///
27/// # Example
28/// ```rust
29/// use std::collections::HashMap;
30/// use lib2fas::helpers::calculate_hash;
31///
32/// #[derive(Hash)]
33/// struct Example {
34/// id: u32,
35/// name: String,
36/// }
37///
38/// let example = Example {
39/// id: 42,
40/// name: String::from("example"),
41/// };
42/// let hash = calculate_hash(&example);
43/// println!("Hash for example: {}", hash);
44///
45/// // Example usage with a HashMap
46/// let mut map = HashMap::new();
47/// map.insert(hash, "Example Data");
48/// println!("Stored value: {}", map.get(&hash).unwrap());
49/// ```
50pub fn calculate_hash<T: Hash>(data: &T) -> u64 {
51 let mut hasher = DefaultHasher::new();
52 data.hash(&mut hasher);
53 hasher.finish()
54}
55
56#[cfg(test)]
57mod tests {
58 use crate::helpers::calculate_hash;
59
60 #[tokio::test]
61 async fn test_consistent_hash() {
62 assert_eq!(calculate_hash(&123), calculate_hash(&123));
63
64 assert_eq!(calculate_hash(&123), 14370432302296844161,);
65
66 assert_ne!(dbg!(calculate_hash(&123)), calculate_hash(&1234));
67 }
68}