use num_cpus;
use rayon_core::scope;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::{BuildHasherDefault, Hash};
use std::sync::Mutex;
use twox_hash::XxHash64;
#[allow(clippy::drop_copy)]
pub fn frequency_finder<T>(list: &[T]) -> HashMap<T, u64, BuildHasherDefault<XxHash64>>
where
T: Copy + Hash + Eq + Sync + Send + Debug,
{
let logical_cores = num_cpus::get();
let range: usize = list.len() / logical_cores;
let split_index: usize = logical_cores * range;
let remainder: usize = list.len() % logical_cores;
let map_mtx: Mutex<HashMap<T, u64, BuildHasherDefault<XxHash64>>> =
Mutex::new(Default::default());
let map_ref = &map_mtx;
scope(|s| {
for idx in 1..=logical_cores {
s.spawn(move |_| {
let mut map_guard = map_ref.lock().unwrap();
for item in list.iter().take(idx * range).skip((idx - 1) * range) {
match map_guard.get_mut(item) {
Some(val) => *val += 1,
None => drop(map_guard.insert(*item, 1)),
}
}
});
}
s.spawn(move |_| {
let mut map_guard = map_ref.lock().unwrap();
for item in list.iter().skip(split_index).take(remainder) {
match map_guard.get_mut(item) {
Some(val) => *val += 1,
None => drop(map_guard.insert(*item, 1)),
}
}
})
});
Mutex::into_inner(map_mtx).unwrap()
}