use super::*;
use crate::group_key::GroupKey;
use crate::hash_seed::{seeded_map, SeededMap};
use std::hash::Hash;
pub(super) const PRESIZE_PREFIX: usize = 1024;
const PRESIZE_UNIQUE_PERCENT: usize = 90;
const PRESIZE_MARGIN_DIVISOR: usize = 20;
const SHRINK_FACTOR: usize = 2;
const SHRINK_SLACK: usize = 8;
#[derive(Clone, Copy, Debug)]
struct Slot(NodeId);
enum SlotKind {
One(NodeId),
Many(usize),
}
impl Slot {
fn one(id: NodeId) -> Self {
assert!(
id >= 0,
"a posted node id is a persisted, non-negative id, got {id}"
);
Slot(id)
}
fn many(index: usize) -> Self {
debug_assert!(
NodeId::try_from(index).is_ok(),
"a slab index fits a node id"
);
Slot(!(index as NodeId))
}
fn kind(self) -> SlotKind {
if self.0 >= 0 {
SlotKind::One(self.0)
} else {
SlotKind::Many((!self.0) as usize)
}
}
fn ids<'a>(&'a self, slab: &'a Slab) -> &'a [NodeId] {
match self.kind() {
SlotKind::One(_) => std::slice::from_ref(&self.0),
SlotKind::Many(index) => slab.list(index),
}
}
fn insert(&mut self, id: NodeId, slab: &mut Slab) {
match self.kind() {
SlotKind::One(held) if held == id => {}
SlotKind::One(held) => {
let pair = if held < id { [held, id] } else { [id, held] };
*self = slab.alloc(pair.to_vec());
}
SlotKind::Many(index) => slab.insert_sorted(index, id),
}
}
fn remove(&mut self, id: NodeId, slab: &mut Slab) -> bool {
match self.kind() {
SlotKind::One(held) if held == id => true,
SlotKind::One(_) => false,
SlotKind::Many(index) => {
if let Some(only) = slab.remove_sorted(index, id) {
*self = Slot::one(only);
}
false
}
}
}
}
#[derive(Debug, Default)]
struct Slab {
lists: Vec<Vec<NodeId>>,
free: Vec<usize>,
}
impl Slab {
fn alloc(&mut self, ids: Vec<NodeId>) -> Slot {
let index = self.free.pop().unwrap_or_else(|| {
self.lists.push(Vec::new());
self.lists.len() - 1
});
self.lists[index] = ids;
Slot::many(index)
}
fn list(&self, index: usize) -> &[NodeId] {
&self.lists[index]
}
fn insert_sorted(&mut self, index: usize, id: NodeId) {
let ids = &mut self.lists[index];
if let Err(at) = ids.binary_search(&id) {
ids.insert(at, id);
}
}
fn remove_sorted(&mut self, index: usize, id: NodeId) -> Option<NodeId> {
let ids = &mut self.lists[index];
let at = ids.binary_search(&id).ok()?;
ids.remove(at);
if let [only] = ids.as_slice() {
let only = *only;
self.lists[index] = Vec::new();
self.free.push(index);
Some(only)
} else {
if ids.capacity() > SHRINK_FACTOR * ids.len() + SHRINK_SLACK {
ids.shrink_to_fit();
}
None
}
}
fn shrink_to_fit(&mut self) {
self.lists.iter_mut().for_each(Vec::shrink_to_fit);
self.lists.shrink_to_fit();
self.free.shrink_to_fit();
}
}
#[derive(Debug)]
struct Table<K> {
map: SeededMap<K, Slot>,
slab: Slab,
}
impl<K> Default for Table<K> {
fn default() -> Self {
Self {
map: seeded_map(),
slab: Slab::default(),
}
}
}
impl<K: Eq + Hash> Table<K> {
fn reserve(&mut self, additional: usize) {
self.map.reserve(additional);
}
fn post(&mut self, key: K, id: NodeId) {
assert!(
id >= 0,
"a posted node id is a persisted, non-negative id, got {id}"
);
let slot = self.map.entry(key).or_insert_with(|| Slot::one(id));
slot.insert(id, &mut self.slab);
}
fn unpost(&mut self, key: &K, id: NodeId) {
let Some(slot) = self.map.get_mut(key) else {
return;
};
if slot.remove(id, &mut self.slab) {
self.map.remove(key);
}
}
fn get(&self, key: &K) -> Option<&[NodeId]> {
self.map.get(key).map(|slot| slot.ids(&self.slab))
}
fn shrink_to_fit(&mut self) {
self.slab.shrink_to_fit();
self.map.shrink_to_fit();
}
fn len(&self) -> usize {
self.map.len()
}
fn posted(&self) -> usize {
self.map
.values()
.map(|slot| slot.ids(&self.slab).len())
.sum()
}
fn keys(&self) -> impl Iterator<Item = &K> {
self.map.keys()
}
}
#[derive(Debug, Default)]
pub(super) struct PairPostings {
ints: Table<i64>,
others: Table<GroupKey>,
}
impl PairPostings {
pub(super) fn post(&mut self, gk: &GroupKey, id: NodeId) {
match gk.as_int() {
Some(i) => self.ints.post(i, id),
None => self.others.post(gk.clone(), id),
}
}
pub(super) fn unpost(&mut self, gk: &GroupKey, id: NodeId) {
match gk.as_int() {
Some(i) => self.ints.unpost(&i, id),
None => self.others.unpost(gk, id),
}
}
pub(super) fn bucket(&self, gk: &GroupKey) -> Option<&[NodeId]> {
match gk.as_int() {
Some(i) => self.ints.get(&i),
None => self.others.get(gk),
}
}
fn reserve_in_busiest(&mut self, additional: impl FnOnce(usize) -> usize) {
if self.ints.len() >= self.others.len() {
let more = additional(self.ints.len());
self.ints.reserve(more);
} else {
let more = additional(self.others.len());
self.others.reserve(more);
}
}
pub(super) fn presize(&mut self, prefix: usize, total: usize, distinct: Option<u64>) {
if prefix == 0 || total <= prefix {
return;
}
if let Some(distinct) = distinct {
let distinct = usize::try_from(distinct).unwrap_or(usize::MAX);
let want = distinct
.saturating_add(distinct / PRESIZE_MARGIN_DIVISOR)
.min(total);
self.reserve_in_busiest(|held| want.saturating_sub(held));
return;
}
let buckets = self.ints.len() + self.others.len();
let ids = self.ints.posted() + self.others.posted();
if buckets == 0 || buckets * 100 < ids * PRESIZE_UNIQUE_PERCENT {
return;
}
let rest = total - prefix;
self.reserve_in_busiest(|held| held.saturating_mul(rest) / prefix);
}
#[cfg(test)]
pub(super) fn capacities(&self) -> (usize, usize) {
(self.ints.map.capacity(), self.others.map.capacity())
}
pub(super) fn shrink_to_fit(&mut self) {
self.ints.shrink_to_fit();
self.others.shrink_to_fit();
}
pub(super) fn ids(&self, gk: &GroupKey) -> &[NodeId] {
self.bucket(gk).unwrap_or(&[])
}
pub(super) fn keys_sorted(&self) -> Vec<GroupKey> {
let mut keys: Vec<GroupKey> = self
.ints
.keys()
.map(|i| GroupKey::from_int(*i))
.chain(self.others.keys().cloned())
.collect();
keys.sort();
keys
}
#[cfg(test)]
pub(super) fn len(&self) -> usize {
self.ints.len() + self.others.len()
}
}
#[cfg(test)]
mod tests;