use crate::execution::matching::PartitionKey;
use datafusion_common::Result;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
macro_rules! typed_id {
($name:ident, $raw:ty) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub(crate) struct $name($raw);
impl $name {
pub(crate) const fn new(value: $raw) -> Self {
Self(value)
}
}
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
};
($name:ident, $raw:ty, get) => {
typed_id!($name, $raw);
impl $name {
pub(crate) const fn get(self) -> $raw {
self.0
}
}
};
}
typed_id!(MatchProgramId, u64);
typed_id!(ExecutionPartitionId, usize);
typed_id!(MatchPartitionId, usize, get);
typed_id!(ActiveProgramGeneration, u64, get);
typed_id!(CollectionHeadGeneration, u64, get);
static NEXT_MATCH_PROGRAM_ID: AtomicU64 = AtomicU64::new(1);
impl MatchProgramId {
pub(crate) fn try_allocate() -> Result<Self> {
NEXT_MATCH_PROGRAM_ID
.try_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
current.checked_add(1)
})
.map(Self::new)
.map_err(|_| {
datafusion_common::DataFusionError::Execution(
"MATCH_RECOGNIZE executable program ID space exhausted".to_string(),
)
})
}
}
#[derive(Debug, Clone)]
pub(crate) enum PartitionKeyBinding {
HeadLocal(CollectionHeadGeneration),
Canonical(PartitionKey),
}
impl PartitionKeyBinding {
pub(crate) fn canonical(&self) -> Option<&PartitionKey> {
match self {
Self::Canonical(key) => Some(key),
Self::HeadLocal(_) => None,
}
}
pub(crate) fn same_owner(&self, other: &Self) -> bool {
match (self, other) {
(Self::HeadLocal(left), Self::HeadLocal(right)) => left == right,
(Self::Canonical(left), Self::Canonical(right)) => Arc::ptr_eq(left, right),
_ => false,
}
}
}
impl From<PartitionKey> for PartitionKeyBinding {
fn from(key: PartitionKey) -> Self {
Self::Canonical(key)
}
}