use std::hash::Hash;
use relate_core::tokens::{workspace_accounting, WorkspaceCharge};
use relate_core::{Result, Value};
use crate::group_key::{row_key, GroupKey, KeyClass, WordTag};
use crate::hash_seed::{seeded_set, SeededSet};
use crate::tiered_set::{TieredWordSet, WordHash};
use crate::workspace::{
charge_set_delta, distinct_row_insert_delta, distinct_row_set_bytes, group_key_insert_delta,
group_key_set_bytes, DISTINCT_PEAK_FAMILY,
};
fn word_hash(tag: WordTag) -> WordHash {
match tag {
WordTag::Node | WordTag::Rel => WordHash::Id,
WordTag::Bool | WordTag::Int | WordTag::FloatBits => WordHash::Value,
}
}
struct Spill {
parked: [Option<TieredWordSet>; WordTag::ALL.len()],
singles: SeededSet<GroupKey>,
rows: SeededSet<Vec<GroupKey>>,
}
impl Default for Spill {
fn default() -> Self {
Self {
parked: Default::default(),
singles: seeded_set(),
rows: seeded_set(),
}
}
}
impl Spill {
fn slot(tag: WordTag) -> usize {
tag.index()
}
fn word_tier_mut(&mut self, tag: WordTag) -> &mut Option<TieredWordSet> {
&mut self.parked[Self::slot(tag)]
}
fn word_tiers(&self) -> impl Iterator<Item = &TieredWordSet> {
self.parked.iter().flatten()
}
fn parked_sum<N: std::iter::Sum>(&self, read: impl FnMut(&TieredWordSet) -> N) -> N {
self.word_tiers().map(read).sum()
}
fn len(&self) -> usize {
self.parked_sum(TieredWordSet::len) + self.singles.len() + self.rows.len()
}
fn general_bytes(&self) -> u64 {
group_key_set_bytes(&self.singles) + distinct_row_set_bytes(&self.rows)
}
fn clone_contents(&self) -> Self {
Self {
parked: self
.parked
.each_ref()
.map(|tier| tier.as_ref().map(TieredWordSet::clone_contents)),
singles: self.singles.clone(),
rows: self.rows.clone(),
}
}
fn try_clone(&self) -> Result<Self> {
let mut parked: [Option<TieredWordSet>; WordTag::ALL.len()] = Default::default();
for (copy, tier) in parked.iter_mut().zip(&self.parked) {
*copy = tier.as_ref().map(TieredWordSet::try_clone).transpose()?;
}
Ok(Self {
parked,
singles: self.singles.clone(),
rows: self.rows.clone(),
})
}
}
pub(crate) struct DistinctSet {
null: bool,
word_tag: Option<WordTag>,
words: TieredWordSet,
spill: Option<Box<Spill>>,
charge: WorkspaceCharge,
}
impl Default for DistinctSet {
fn default() -> Self {
Self {
null: false,
word_tag: None,
words: TieredWordSet::new(WordHash::Value),
spill: None,
charge: WorkspaceCharge::empty(),
}
}
}
impl DistinctSet {
pub(crate) fn clone_contents(&self) -> Self {
Self {
null: self.null,
word_tag: self.word_tag,
words: self.words.clone_contents(),
spill: self
.spill
.as_ref()
.map(|spill| Box::new(spill.clone_contents())),
charge: WorkspaceCharge::empty(),
}
}
#[cfg(test)]
fn word_bytes(&self) -> u64 {
self.words.bytes()
+ self
.spill_ref()
.map_or(0, |spill| spill.parked_sum(TieredWordSet::bytes))
}
pub(crate) fn try_clone(&self) -> Result<Self> {
let words = self.words.try_clone()?;
let spill = self
.spill
.as_ref()
.map(|spill| spill.try_clone().map(Box::new))
.transpose()?;
let general = self.spill_ref().map_or(0, Spill::general_bytes);
Ok(Self {
null: self.null,
word_tag: self.word_tag,
words,
spill,
charge: WorkspaceCharge::retain_with(|| general)?,
})
}
pub(crate) fn insert_value(&mut self, value: &Value) -> Result<bool> {
let key = GroupKey::new(value);
match key.class() {
KeyClass::Null => Ok(!std::mem::replace(&mut self.null, true)),
KeyClass::Word(tag, word) => self.insert_word(tag, word),
KeyClass::General => self.insert_single(key),
}
}
pub(crate) fn insert_row(&mut self, row: &[Value]) -> Result<bool> {
match row {
[value] => self.insert_value(value),
_ => self.insert_row_key(row_key(row)),
}
}
pub(crate) fn len(&self) -> usize {
usize::from(self.null) + self.words.len() + self.spill_ref().map_or(0, Spill::len)
}
#[cfg(test)]
pub(crate) fn bytes(&self) -> u64 {
self.word_bytes() + self.spill_ref().map_or(0, Spill::general_bytes)
}
#[cfg(test)]
pub(crate) fn words_promoted(&self) -> bool {
self.words.promoted()
|| self
.spill_ref()
.is_some_and(|spill| spill.word_tiers().any(TieredWordSet::promoted))
}
#[cfg(test)]
pub(crate) fn charged(&self) -> u64 {
self.words.charged()
+ self
.spill_ref()
.map_or(0, |spill| spill.parked_sum(TieredWordSet::charged))
+ self.charge.bytes()
}
fn spill(spill: &mut Option<Box<Spill>>) -> &mut Spill {
spill.get_or_insert_with(Box::default)
}
fn spill_ref(&self) -> Option<&Spill> {
self.spill.as_deref()
}
fn insert_word(&mut self, tag: WordTag, word: u64) -> Result<bool> {
if self.word_tag != Some(tag) {
self.switch_word_tier(tag);
}
self.words.insert(word, DISTINCT_PEAK_FAMILY)
}
fn switch_word_tier(&mut self, tag: WordTag) {
if let Some(held) = self.word_tag.take() {
let mut active = std::mem::replace(&mut self.words, TieredWordSet::new(word_hash(tag)));
active.promote_inline();
if active.len() > 0 {
*Self::spill(&mut self.spill).word_tier_mut(held) = Some(active);
}
} else {
self.words = TieredWordSet::new(word_hash(tag));
}
if let Some(parked) = self
.spill
.as_deref_mut()
.and_then(|spill| spill.word_tier_mut(tag).take())
{
self.words = parked;
}
self.word_tag = Some(tag);
}
fn insert_single(&mut self, key: GroupKey) -> Result<bool> {
let singles = &mut Self::spill(&mut self.spill).singles;
insert_charged(&mut self.charge, singles, key, group_key_insert_delta)
}
fn insert_row_key(&mut self, key: Vec<GroupKey>) -> Result<bool> {
let rows = &mut Self::spill(&mut self.spill).rows;
insert_charged(&mut self.charge, rows, key, distinct_row_insert_delta)
}
}
fn insert_charged<K, B: ?Sized>(
charge: &mut WorkspaceCharge,
set: &mut SeededSet<K>,
key: K,
delta: impl FnOnce(usize, &B) -> u64,
) -> Result<bool>
where
K: Eq + Hash + Clone + std::borrow::Borrow<B>,
{
if !workspace_accounting() {
return Ok(set.insert(key));
}
let old_len = set.len();
if !set.insert(key.clone()) {
return Ok(false);
}
charge_set_delta(charge, DISTINCT_PEAK_FAMILY, || {
delta(old_len, std::borrow::Borrow::<B>::borrow(&key))
})
.inspect_err(|_| {
set.remove::<K>(&key);
})?;
Ok(true)
}
pub(crate) fn dedup_first_seen(vals: Vec<Value>) -> Result<Vec<Value>> {
let mut seen = DistinctSet::default();
let mut out = Vec::with_capacity(vals.len());
for value in vals {
if seen.insert_value(&value)? {
out.push(value);
}
}
drop(seen);
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn word_tag_all_is_listed_in_index_order() {
for (position, tag) in WordTag::ALL.into_iter().enumerate() {
assert_eq!(Spill::slot(tag), position, "{tag:?}");
}
}
}