use rand::{distributions::Alphanumeric, Rng};
use sha1::Sha1;
use std::{env, iter, time};
use constellation::*;
fn main() {
init(Resources::default());
let processes = env::args()
.nth(1)
.and_then(|arg| arg.parse::<usize>().ok())
.unwrap_or(10);
let processes = (0..processes)
.map(|i| {
let child = spawn(
Resources::default(),
serde_closure::FnOnce!([i] move |parent| {
println!("process {}: commencing hashing", i);
let mut rng = rand::thread_rng();
let mut lowest: Option<(String,[u8;20])> = None;
let start = time::Instant::now();
while start.elapsed() < time::Duration::new(10,0) {
let string: String = iter::repeat(()).map(|()| rng.sample(Alphanumeric)).take(7).collect();
let hash = Sha1::from(&string).digest().bytes();
if lowest.is_none() || lowest.as_ref().unwrap().1 >= hash {
lowest = Some((string,hash));
}
}
let lowest = lowest.unwrap();
println!("process {}: lowest hash was {} from string \"{}\"", i, hex::encode(lowest.1), lowest.0);
let sender = Sender::<(String,[u8;20])>::new(parent);
sender.send(lowest).block();
}),
)
.block()
.expect("spawn() failed to allocate process");
Receiver::<(String, [u8; 20])>::new(child)
})
.collect::<Vec<_>>();
let result = processes
.into_iter()
.map(|receiver| receiver.recv().block().unwrap())
.min_by_key(|&(_, hash)| hash)
.unwrap();
println!(
"overall lowest hash was {} from string \"{}\"",
hex::encode(result.1),
result.0
);
}