use std::{
any::Any,
collections::HashMap,
hash::Hash,
sync::{Arc, OnceLock},
};
use super::groups::Lines;
pub(super) type KeyIndex<K> = Arc<OnceLock<HashMap<K, usize>>>;
pub(super) struct RowKeys<K> {
key: Arc<dyn Fn(usize) -> K + Send + Sync>,
count: usize,
lines: Arc<Lines>,
index: KeyIndex<K>,
}
impl<K> Clone for RowKeys<K> {
fn clone(&self) -> Self {
Self {
key: self.key.clone(),
count: self.count,
lines: self.lines.clone(),
index: self.index.clone(),
}
}
}
impl<K: Clone + Eq + Hash> RowKeys<K> {
pub fn new(key: Arc<dyn Fn(usize) -> K + Send + Sync>, count: usize, lines: Arc<Lines>, index: KeyIndex<K>) -> Self {
Self {
key,
count,
lines,
index,
}
}
pub fn len(&self) -> usize {
self.lines.ranks()
}
pub fn count(&self) -> usize {
self.count
}
pub fn get(&self, rank: usize) -> Option<K> {
self.lines.row_of_rank(rank).map(|index| (self.key)(index))
}
pub fn at(&self, index: usize) -> K {
(self.key)(index)
}
pub fn index_of(&self, key: &K) -> Option<usize> {
self
.index
.get_or_init(|| (0..self.count).map(|index| ((self.key)(index), index)).collect())
.get(key)
.copied()
}
pub fn rank_of(&self, key: &K) -> Option<usize> {
self.lines.rank_of_index(self.index_of(key)?)
}
pub fn ranked(&self, first: usize, last: usize) -> Vec<K> {
(first..=last).filter_map(|rank| self.get(rank)).collect()
}
pub fn shown_among<'a>(&self, keys: impl IntoIterator<Item = &'a K>) -> usize
where
K: 'a,
{
let mut seen = std::collections::HashSet::new();
keys
.into_iter()
.filter(|key| seen.insert(*key))
.filter(|key| self.rank_of(key).is_some())
.count()
}
}
#[derive(Default)]
pub(super) struct KeptIndex(Option<(Arc<dyn Any + Send + Sync>, Arc<dyn Any + Send + Sync>)>);
impl KeptIndex {
pub fn for_rows<R: Send + Sync + 'static, K: Send + Sync + 'static>(&mut self, rows: &Arc<Vec<R>>) -> KeyIndex<K> {
if let Some((kept_rows, index)) = &self.0
&& let Some(kept_rows) = kept_rows.downcast_ref::<Arc<Vec<R>>>()
&& Arc::ptr_eq(kept_rows, rows)
&& let Some(index) = index.downcast_ref::<KeyIndex<K>>()
{
return index.clone();
}
let index: KeyIndex<K> = Arc::new(OnceLock::new());
self.0 = Some((Arc::new(rows.clone()), Arc::new(index.clone())));
index
}
}