feat: replace fastrand by rapidhash with custom generator

This commit is contained in:
2025-04-05 15:08:13 +02:00
parent f5b2737178
commit ba231bda39
3 changed files with 40 additions and 14 deletions

8
Cargo.lock generated
View File

@@ -3,14 +3,14 @@
version = 4
[[package]]
name = "fastrand"
version = "2.3.0"
name = "rapidhash"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
checksum = "9813f789f95ee4fe6b4d01834404d7cccacbc3f6c029343af910b3c2835eb9f1"
[[package]]
name = "rpg"
version = "1.0.0"
dependencies = [
"fastrand",
"rapidhash",
]

View File

@@ -4,4 +4,4 @@ version = "1.0.0"
edition = "2021"
[dependencies]
fastrand = "2.3.0"
rapidhash = "1.4.0"

View File

@@ -1,4 +1,30 @@
use std::env;
use std::hash::Hasher;
use std::time::{SystemTime, UNIX_EPOCH};
use std::{env, ops::Range};
use rapidhash::RapidInlineHasher;
pub struct HashRng {
state: u64,
counter: u64,
}
impl HashRng {
pub fn new() -> Self {
let seed = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos() as u64; // Tronqué à u64
Self { state: seed, counter: 0 }
}
pub fn next_in_range(&mut self, range: Range<usize>) -> usize {
let mut hasher = RapidInlineHasher::new(self.state);
hasher.write_u64(self.state);
hasher.write_u64(self.counter);
self.counter = self.counter.wrapping_add(1);
range.start + (hasher.finish() as usize % (range.end - range.start))
}
}
fn main() {
let num_pseudonyms = env::args()
@@ -9,12 +35,12 @@ fn main() {
let adjectives = include_str!("../data/adjectives.txt").lines().collect::<Vec<_>>();
let nouns = include_str!("../data/nouns.txt").lines().collect::<Vec<_>>();
(0..num_pseudonyms).for_each(|_| {
println!(
"{}-{}-{}",
adjectives[fastrand::usize(0..adjectives.len())],
nouns[fastrand::usize(0..nouns.len())],
fastrand::u32(0..1000)
);
});
let mut rng = HashRng::new();
for _ in 0..num_pseudonyms {
let adjective = adjectives[rng.next_in_range(0..adjectives.len())];
let noun = nouns[rng.next_in_range(0..nouns.len())];
let number = rng.next_in_range(0..1000);
println!("{adjective}-{noun}-{number}");
}
}