relate-executor 1.5.0

In-memory graph and Cypher physical executor
Documentation
//! Hash index and build table representation for HashJoin.

use std::mem::size_of;

use relate_core::{NodeId, Result};
use relate_names::SmallName;

use crate::hash_seed::IdMap;
use crate::row::Row;
use crate::UsedSet;

use super::row_join_key;

/// Composite or single join key over shared node variables.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum JoinKey {
    Single(NodeId),
    Multi(Vec<NodeId>),
}

/// The build table representation: either full rows, or multiplicity-only (subsuming ADR-0713).
pub(crate) enum BuildTable<'a> {
    Rows(IdMap<JoinKey, Vec<&'a (Row, UsedSet)>>),
    Multiplicity(IdMap<JoinKey, u64>),
}

/// The join's build side: indexed by JoinKey, memory charged via WorkspaceCharge.
pub(crate) struct HashIndex<'a> {
    pub(crate) table: BuildTable<'a>,
    #[allow(dead_code)]
    pub(crate) charge: relate_core::tokens::WorkspaceCharge,
    pub(crate) slots: usize,
}

impl<'a> HashIndex<'a> {
    pub(crate) fn build_multiplicity(
        rows: impl Iterator<Item = &'a (Row, UsedSet)>,
        join_vars: &[&SmallName],
    ) -> Result<Self> {
        let mut counts: IdMap<JoinKey, u64> = IdMap::default();
        let mut slots = 0;
        let mut charge = relate_core::tokens::WorkspaceCharge::empty();
        for pair in rows {
            let key = row_join_key(&pair.0, join_vars);
            *counts.entry(key).or_insert(0) += 1;
            slots += 1;
            charge.resize_with(|| {
                crate::workspace::map_entries_bytes(counts.len())
                    + crate::workspace::buffer_bytes(slots, 16)
            })?;
        }
        Ok(Self {
            table: BuildTable::Multiplicity(counts),
            charge,
            slots,
        })
    }

    pub(crate) fn build_rows(
        rows: impl Iterator<Item = &'a (Row, UsedSet)>,
        join_vars: &[&SmallName],
    ) -> Result<Self> {
        const SLOT: u64 = size_of::<&(Row, UsedSet)>() as u64;
        let mut by_key: IdMap<JoinKey, Vec<&'a (Row, UsedSet)>> = IdMap::default();
        let mut charge = relate_core::tokens::WorkspaceCharge::empty();
        let mut slots = 0;
        for pair in rows {
            let key = row_join_key(&pair.0, join_vars);
            by_key.entry(key).or_default().push(pair);
            slots += 1;
            charge.resize_with(|| {
                crate::workspace::map_entries_bytes(by_key.len())
                    + crate::workspace::buffer_bytes(slots, SLOT)
            })?;
        }
        Ok(Self {
            table: BuildTable::Rows(by_key),
            charge,
            slots,
        })
    }
}