datafusion-match-recognize 0.56.1

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
Documentation
// Licensed under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

//! Validated identifiers and compact offsets shared by planning and execution.

use std::fmt;

/// Checked numeric identifier for a user-defined pattern symbol.
///
/// The compiled NFA uses consecutive slots and reserves slot zero for its
/// `Empty` symbol/program placeholder. Epsilon edges are represented separately.
/// A `SymbolId` can therefore represent only user symbols, so the placeholder
/// cannot accidentally be passed where a user symbol is required.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SymbolId(usize);

impl SymbolId {
    /// Construct a user-symbol identifier for a checked table with consecutive indexes.
    ///
    /// `slot_count` includes the NFA's reserved empty slot at index zero.
    #[inline]
    pub const fn try_new(dense_index: usize, slot_count: usize) -> Option<Self> {
        if dense_index > 0 && dense_index < slot_count {
            Some(Self(dense_index))
        } else {
            None
        }
    }

    /// Bit in a packed row of user-symbol memberships. The empty slot has no bit.
    #[inline]
    pub const fn packed_membership_bit(self) -> Option<u64> {
        if self.0 <= u64::BITS as usize {
            Some(1u64 << (self.0 - 1))
        } else {
            None
        }
    }

    /// Return this symbol's index in the consecutive symbol table.
    #[inline]
    pub const fn index(self) -> usize {
        self.0
    }
}

impl fmt::Display for SymbolId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// Compact identifier for an aggregate in a fully built executable program.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AggregateId(usize);

impl AggregateId {
    /// Construct an aggregate identifier after checking its program bounds.
    pub const fn try_new(index: usize, aggregate_count: usize) -> Option<Self> {
        if index < aggregate_count {
            Some(Self(index))
        } else {
            None
        }
    }

    /// Return this aggregate's index in the executable program table.
    pub const fn index(self) -> usize {
        self.0
    }
}

impl fmt::Display for AggregateId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// Compact physical-row offset relative to a typed absolute origin.
///
/// This type is suitable for compact per-match state. Absolute row identities
/// remain [`crate::core::AbsoluteRow`] and are never narrowed to this representation.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PositionOffset(u32);

impl PositionOffset {
    /// Construct an offset only when the value is exactly representable.
    pub const fn try_new(value: u64) -> Option<Self> {
        if value <= u32::MAX as u64 {
            Some(Self(value as u32))
        } else {
            None
        }
    }

    /// Return the underlying compact offset.
    #[cfg(test)]
    pub const fn as_u32(self) -> u32 {
        self.0
    }
}

impl fmt::Display for PositionOffset {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[cfg(test)]
mod tests {
    use super::{AggregateId, PositionOffset, SymbolId};

    #[test]
    fn symbol_ids_exclude_empty_and_out_of_bounds_slots() {
        assert_eq!(SymbolId::try_new(0, 3), None);
        assert_eq!(SymbolId::try_new(1, 3).map(SymbolId::index), Some(1));
        assert_eq!(SymbolId::try_new(2, 3).map(SymbolId::index), Some(2));
        assert_eq!(SymbolId::try_new(3, 3), None);
    }

    #[test]
    fn aggregate_ids_validate_zero_based_program_bounds() {
        assert_eq!(AggregateId::try_new(0, 0), None);
        assert_eq!(AggregateId::try_new(0, 2).map(AggregateId::index), Some(0));
        assert_eq!(AggregateId::try_new(1, 2).map(AggregateId::index), Some(1));
        assert_eq!(AggregateId::try_new(2, 2), None);
    }

    #[test]
    fn position_offsets_are_checked_at_u32_max() {
        assert_eq!(
            PositionOffset::try_new(0).map(PositionOffset::as_u32),
            Some(0)
        );
        assert_eq!(
            PositionOffset::try_new(u32::MAX as u64).map(PositionOffset::as_u32),
            Some(u32::MAX)
        );
        assert_eq!(PositionOffset::try_new(u32::MAX as u64 + 1), None);
    }

    #[test]
    fn candidate_offsets_are_compact() {
        assert_eq!(size_of::<PositionOffset>(), size_of::<u32>());
    }
}