datafusion-match-recognize 0.55.0

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.

//! Row coordinates shared by planning, NFA compilation, and execution.
//!
//! Absolute coordinates remain wide across Arrow collections. End-exclusive
//! positions and relative offsets use separate types so a physical row cannot
//! also act as a control sentinel.
//!
//! Inline hints expose these small operations to consumers in other crates,
//! allowing row loops to optimize the wrappers and their checked arithmetic.

use std::fmt;

/// Zero-based absolute position in the complete input stream.
///
/// A value identifies a physical row only when it lies inside a validated
/// `PhysicalExtent`. NFA state may also carry the end-exclusive position for
/// a zero-width virtual-end acceptance; the surrounding row-kind contract, not
/// a numeric sentinel, distinguishes that position from physical input.
///
/// Coordinate domains cannot be mixed without an explicit conversion:
///
/// ```text
/// // Does not compile: AbsoluteRow and PhysicalEndExclusive are distinct types.
/// use crate::core::{AbsoluteRow, PhysicalEndExclusive};
///
/// let row = AbsoluteRow::new(4);
/// let end = PhysicalEndExclusive::new(row);
/// assert_eq!(row, end);
/// ```
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AbsoluteRow(u64);

impl AbsoluteRow {
    /// The first absolute row.
    pub const ZERO: Self = Self(0);
    /// The largest representable absolute coordinate.
    #[cfg(test)]
    pub const MAX: Self = Self(u64::MAX);

    /// Construct an absolute row from a `u64` coordinate.
    #[inline]
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Return the underlying wide coordinate.
    #[inline]
    pub const fn as_u64(self) -> u64 {
        self.0
    }

    /// Advance by a checked number of physical rows.
    #[inline]
    pub const fn checked_add(self, rows: PhysicalRowCount) -> Option<Self> {
        match self.0.checked_add(rows.0) {
            Some(value) => Some(Self(value)),
            None => None,
        }
    }

    /// Move backward by a checked number of physical rows.
    #[inline]
    pub const fn checked_sub(self, rows: PhysicalRowCount) -> Option<Self> {
        match self.0.checked_sub(rows.0) {
            Some(value) => Some(Self(value)),
            None => None,
        }
    }

    /// Return this row's non-negative distance from `origin`.
    #[inline]
    pub const fn checked_offset_from(
        self,
        origin: AbsoluteRow,
    ) -> Option<PhysicalRowCount> {
        match self.0.checked_sub(origin.0) {
            Some(value) => Some(PhysicalRowCount(value)),
            None => None,
        }
    }
}

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

/// Number of physical rows in an extent or between two positions.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PhysicalRowCount(u64);

impl PhysicalRowCount {
    /// An empty physical extent.
    pub const ZERO: Self = Self(0);

    /// Construct a physical row count.
    #[inline]
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Return the underlying wide count.
    #[inline]
    pub const fn as_u64(self) -> u64 {
        self.0
    }

    /// Add two counts without wrapping.
    #[inline]
    pub const fn checked_add(self, other: Self) -> Option<Self> {
        match self.0.checked_add(other.0) {
            Some(value) => Some(Self(value)),
            None => None,
        }
    }
}

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

/// Absolute position immediately after a physical row extent.
///
/// This is deliberately distinct from [`AbsoluteRow`]. It can identify an
/// empty extent boundary without claiming that a physical row exists there.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PhysicalEndExclusive(AbsoluteRow);

impl PhysicalEndExclusive {
    /// Wrap an absolute coordinate as an end-exclusive boundary.
    #[inline]
    pub const fn new(position: AbsoluteRow) -> Self {
        Self(position)
    }

    /// Return the boundary's absolute coordinate.
    #[inline]
    pub const fn position(self) -> AbsoluteRow {
        self.0
    }
}

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

/// Validated half-open physical row extent in absolute coordinates.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PhysicalExtent {
    start: AbsoluteRow,
    end: PhysicalEndExclusive,
}

impl PhysicalExtent {
    /// Validate a half-open extent.
    #[inline]
    pub const fn try_new(start: AbsoluteRow, end: PhysicalEndExclusive) -> Option<Self> {
        if start.as_u64() <= end.position().as_u64() {
            Some(Self { start, end })
        } else {
            None
        }
    }

    /// Return the start coordinate, even when the extent is empty.
    #[inline]
    pub const fn start(self) -> AbsoluteRow {
        self.start
    }

    /// Return the end-exclusive absolute boundary.
    #[inline]
    pub const fn end(self) -> PhysicalEndExclusive {
        self.end
    }
}

#[cfg(test)]
mod tests {
    use super::{AbsoluteRow, PhysicalEndExclusive, PhysicalExtent, PhysicalRowCount};

    #[test]
    fn absolute_arithmetic_rejects_overflow_and_underflow() {
        assert_eq!(
            AbsoluteRow::new(u64::MAX).checked_add(PhysicalRowCount::new(1)),
            None
        );
        assert_eq!(
            AbsoluteRow::ZERO.checked_sub(PhysicalRowCount::new(1)),
            None
        );
        assert_eq!(
            AbsoluteRow::new(4).checked_offset_from(AbsoluteRow::new(5)),
            None
        );
    }

    #[test]
    fn physical_extents_validate_order() {
        let start = AbsoluteRow::new(10);
        let end = PhysicalEndExclusive::new(AbsoluteRow::new(13));
        let extent = PhysicalExtent::try_new(start, end)
            .expect("10..13 is a valid half-open extent");

        assert_eq!(extent.start(), start);
        assert_eq!(extent.end(), end);
        assert_eq!(extent.end().position(), AbsoluteRow::new(13));
        assert!(
            PhysicalExtent::try_new(start, PhysicalEndExclusive::new(start)).is_some()
        );
        assert!(
            PhysicalExtent::try_new(
                start,
                PhysicalEndExclusive::new(AbsoluteRow::new(9)),
            )
            .is_none()
        );
    }
}