use super::*;
use crate::group_key::GroupKey;
use crate::hash_seed::{seeded_map, SeededMap};
use std::hash::Hash;
#[derive(Debug)]
enum IdBag {
One(NodeId),
Many(Vec<NodeId>),
}
impl IdBag {
fn as_slice(&self) -> &[NodeId] {
match self {
IdBag::One(id) => std::slice::from_ref(id),
IdBag::Many(ids) => ids,
}
}
fn insert(&mut self, id: NodeId) {
match self {
IdBag::One(held) if *held == id => {}
IdBag::One(held) => {
let pair = if *held < id { [*held, id] } else { [id, *held] };
*self = IdBag::Many(pair.to_vec());
}
IdBag::Many(ids) => {
if let Err(at) = ids.binary_search(&id) {
ids.insert(at, id);
}
}
}
}
fn remove(&mut self, id: NodeId) -> bool {
match self {
IdBag::One(held) => *held == id,
IdBag::Many(ids) => {
if let Ok(at) = ids.binary_search(&id) {
ids.remove(at);
if let [only] = ids.as_slice() {
*self = IdBag::One(*only);
} else if ids.capacity() > 2 * ids.len() + 8 {
ids.shrink_to_fit();
}
}
false
}
}
}
fn shrink(&mut self) {
if let IdBag::Many(ids) = self {
ids.shrink_to_fit();
}
}
}
#[derive(Debug)]
struct Table<K>(SeededMap<K, IdBag>);
impl<K: Eq + Hash> Table<K> {
fn post(&mut self, key: K, id: NodeId) {
self.0
.entry(key)
.and_modify(|b| b.insert(id))
.or_insert(IdBag::One(id));
}
fn unpost(&mut self, key: &K, id: NodeId) {
if self.0.get_mut(key).is_some_and(|b| b.remove(id)) {
self.0.remove(key);
}
}
fn get(&self, key: &K) -> Option<&[NodeId]> {
self.0.get(key).map(IdBag::as_slice)
}
fn shrink_to_fit(&mut self) {
self.0.values_mut().for_each(IdBag::shrink);
self.0.shrink_to_fit();
}
#[cfg(test)]
fn len(&self) -> usize {
self.0.len()
}
fn keys(&self) -> impl Iterator<Item = &K> {
self.0.keys()
}
}
#[derive(Debug)]
pub(super) struct PairPostings {
ints: Table<i64>,
others: Table<GroupKey>,
}
impl Default for PairPostings {
fn default() -> Self {
Self {
ints: Table(seeded_map()),
others: Table(seeded_map()),
}
}
}
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),
}
}
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;