datafusion_expr_common/
interval_arithmetic.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Interval arithmetic library
19
20use std::borrow::Borrow;
21use std::fmt::{self, Display, Formatter};
22use std::ops::{AddAssign, SubAssign};
23
24use crate::operator::Operator;
25use crate::type_coercion::binary::{BinaryTypeCoercer, comparison_coercion_numeric};
26
27use arrow::compute::{CastOptions, cast_with_options};
28use arrow::datatypes::{
29    DataType, IntervalDayTime, IntervalMonthDayNano, IntervalUnit,
30    MAX_DECIMAL128_FOR_EACH_PRECISION, MAX_DECIMAL256_FOR_EACH_PRECISION,
31    MIN_DECIMAL128_FOR_EACH_PRECISION, MIN_DECIMAL256_FOR_EACH_PRECISION, TimeUnit,
32};
33use datafusion_common::rounding::{alter_fp_rounding_mode, next_down, next_up};
34use datafusion_common::{
35    DataFusionError, Result, ScalarValue, assert_eq_or_internal_err,
36    assert_or_internal_err, internal_err,
37};
38
39macro_rules! get_extreme_value {
40    ($extreme:ident, $value:expr) => {
41        match $value {
42            DataType::UInt8 => ScalarValue::UInt8(Some(u8::$extreme)),
43            DataType::UInt16 => ScalarValue::UInt16(Some(u16::$extreme)),
44            DataType::UInt32 => ScalarValue::UInt32(Some(u32::$extreme)),
45            DataType::UInt64 => ScalarValue::UInt64(Some(u64::$extreme)),
46            DataType::Int8 => ScalarValue::Int8(Some(i8::$extreme)),
47            DataType::Int16 => ScalarValue::Int16(Some(i16::$extreme)),
48            DataType::Int32 => ScalarValue::Int32(Some(i32::$extreme)),
49            DataType::Int64 => ScalarValue::Int64(Some(i64::$extreme)),
50            DataType::Float32 => ScalarValue::Float32(Some(f32::$extreme)),
51            DataType::Float64 => ScalarValue::Float64(Some(f64::$extreme)),
52            DataType::Duration(TimeUnit::Second) => {
53                ScalarValue::DurationSecond(Some(i64::$extreme))
54            }
55            DataType::Duration(TimeUnit::Millisecond) => {
56                ScalarValue::DurationMillisecond(Some(i64::$extreme))
57            }
58            DataType::Duration(TimeUnit::Microsecond) => {
59                ScalarValue::DurationMicrosecond(Some(i64::$extreme))
60            }
61            DataType::Duration(TimeUnit::Nanosecond) => {
62                ScalarValue::DurationNanosecond(Some(i64::$extreme))
63            }
64            DataType::Timestamp(TimeUnit::Second, _) => {
65                ScalarValue::TimestampSecond(Some(i64::$extreme), None)
66            }
67            DataType::Timestamp(TimeUnit::Millisecond, _) => {
68                ScalarValue::TimestampMillisecond(Some(i64::$extreme), None)
69            }
70            DataType::Timestamp(TimeUnit::Microsecond, _) => {
71                ScalarValue::TimestampMicrosecond(Some(i64::$extreme), None)
72            }
73            DataType::Timestamp(TimeUnit::Nanosecond, _) => {
74                ScalarValue::TimestampNanosecond(Some(i64::$extreme), None)
75            }
76            DataType::Interval(IntervalUnit::YearMonth) => {
77                ScalarValue::IntervalYearMonth(Some(i32::$extreme))
78            }
79            DataType::Interval(IntervalUnit::DayTime) => {
80                ScalarValue::IntervalDayTime(Some(IntervalDayTime::$extreme))
81            }
82            DataType::Interval(IntervalUnit::MonthDayNano) => {
83                ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano::$extreme))
84            }
85            DataType::Decimal128(precision, scale) => ScalarValue::Decimal128(
86                Some(
87                    paste::paste! {[<$extreme _DECIMAL128_FOR_EACH_PRECISION>]}
88                        [*precision as usize],
89                ),
90                *precision,
91                *scale,
92            ),
93            DataType::Decimal256(precision, scale) => ScalarValue::Decimal256(
94                Some(
95                    paste::paste! {[<$extreme _DECIMAL256_FOR_EACH_PRECISION>]}
96                        [*precision as usize],
97                ),
98                *precision,
99                *scale,
100            ),
101            _ => unreachable!(),
102        }
103    };
104}
105
106macro_rules! value_transition {
107    ($bound:ident, $direction:expr, $value:expr) => {
108        match $value {
109            UInt8(Some(value)) if value == u8::$bound => UInt8(None),
110            UInt16(Some(value)) if value == u16::$bound => UInt16(None),
111            UInt32(Some(value)) if value == u32::$bound => UInt32(None),
112            UInt64(Some(value)) if value == u64::$bound => UInt64(None),
113            Int8(Some(value)) if value == i8::$bound => Int8(None),
114            Int16(Some(value)) if value == i16::$bound => Int16(None),
115            Int32(Some(value)) if value == i32::$bound => Int32(None),
116            Int64(Some(value)) if value == i64::$bound => Int64(None),
117            Float32(Some(value)) if value == f32::$bound => Float32(None),
118            Float64(Some(value)) if value == f64::$bound => Float64(None),
119            DurationSecond(Some(value)) if value == i64::$bound => DurationSecond(None),
120            DurationMillisecond(Some(value)) if value == i64::$bound => {
121                DurationMillisecond(None)
122            }
123            DurationMicrosecond(Some(value)) if value == i64::$bound => {
124                DurationMicrosecond(None)
125            }
126            DurationNanosecond(Some(value)) if value == i64::$bound => {
127                DurationNanosecond(None)
128            }
129            TimestampSecond(Some(value), tz) if value == i64::$bound => {
130                TimestampSecond(None, tz)
131            }
132            TimestampMillisecond(Some(value), tz) if value == i64::$bound => {
133                TimestampMillisecond(None, tz)
134            }
135            TimestampMicrosecond(Some(value), tz) if value == i64::$bound => {
136                TimestampMicrosecond(None, tz)
137            }
138            TimestampNanosecond(Some(value), tz) if value == i64::$bound => {
139                TimestampNanosecond(None, tz)
140            }
141            IntervalYearMonth(Some(value)) if value == i32::$bound => {
142                IntervalYearMonth(None)
143            }
144            IntervalDayTime(Some(value))
145                if value == arrow::datatypes::IntervalDayTime::$bound =>
146            {
147                IntervalDayTime(None)
148            }
149            IntervalMonthDayNano(Some(value))
150                if value == arrow::datatypes::IntervalMonthDayNano::$bound =>
151            {
152                IntervalMonthDayNano(None)
153            }
154            _ => next_value_helper::<$direction>($value),
155        }
156    };
157}
158
159/// The `Interval` type represents a closed interval used for computing
160/// reliable bounds for mathematical expressions.
161///
162/// Conventions:
163///
164/// 1. **Closed bounds**: The interval always encompasses its endpoints. We
165///    accommodate operations resulting in open intervals by incrementing or
166///    decrementing the interval endpoint value to its successor/predecessor.
167///
168/// 2. **Unbounded endpoints**: If the `lower` or `upper` bounds are indeterminate,
169///    they are labeled as *unbounded*. This is represented using a `NULL`.
170///
171/// 3. **Overflow handling**: If the `lower` or `upper` endpoints exceed their
172///    limits after any operation, they either become unbounded or they are fixed
173///    to the maximum/minimum value of the datatype, depending on the direction
174///    of the overflowing endpoint, opting for the safer choice.
175///
176/// 4. **Floating-point special cases**:
177///    - `INF` values are converted to `NULL`s while constructing an interval to
178///      ensure consistency, with other data types.
179///    - `NaN` (Not a Number) results are conservatively result in unbounded
180///      endpoints.
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct Interval {
183    lower: ScalarValue,
184    upper: ScalarValue,
185}
186
187/// This macro handles the `NaN` and `INF` floating point values.
188///
189/// - `NaN` values are always converted to unbounded i.e. `NULL` values.
190/// - For lower bounds:
191///     - A `NEG_INF` value is converted to a `NULL`.
192///     - An `INF` value is conservatively converted to the maximum representable
193///       number for the floating-point type in question. In this case, converting
194///       to `NULL` doesn't make sense as it would be interpreted as a `NEG_INF`.
195/// - For upper bounds:
196///     - An `INF` value is converted to a `NULL`.
197///     - An `NEG_INF` value is conservatively converted to the minimum representable
198///       number for the floating-point type in question. In this case, converting
199///       to `NULL` doesn't make sense as it would be interpreted as an `INF`.
200macro_rules! handle_float_intervals {
201    ($scalar_type:ident, $primitive_type:ident, $lower:expr, $upper:expr) => {{
202        let lower = match $lower {
203            ScalarValue::$scalar_type(Some(l_val))
204                if l_val == $primitive_type::NEG_INFINITY || l_val.is_nan() =>
205            {
206                ScalarValue::$scalar_type(None)
207            }
208            ScalarValue::$scalar_type(Some(l_val))
209                if l_val == $primitive_type::INFINITY =>
210            {
211                ScalarValue::$scalar_type(Some($primitive_type::MAX))
212            }
213            value @ ScalarValue::$scalar_type(Some(_)) => value,
214            _ => ScalarValue::$scalar_type(None),
215        };
216
217        let upper = match $upper {
218            ScalarValue::$scalar_type(Some(r_val))
219                if r_val == $primitive_type::INFINITY || r_val.is_nan() =>
220            {
221                ScalarValue::$scalar_type(None)
222            }
223            ScalarValue::$scalar_type(Some(r_val))
224                if r_val == $primitive_type::NEG_INFINITY =>
225            {
226                ScalarValue::$scalar_type(Some($primitive_type::MIN))
227            }
228            value @ ScalarValue::$scalar_type(Some(_)) => value,
229            _ => ScalarValue::$scalar_type(None),
230        };
231
232        Interval { lower, upper }
233    }};
234}
235
236/// Ordering floating-point numbers according to their binary representations
237/// contradicts with their natural ordering. Floating-point number ordering
238/// after unsigned integer transmutation looks like:
239///
240/// ```text
241/// 0, 1, 2, 3, ..., MAX, -0, -1, -2, ..., -MAX
242/// ```
243///
244/// This macro applies a one-to-one map that fixes the ordering above.
245macro_rules! map_floating_point_order {
246    ($value:expr, $ty:ty) => {{
247        let num_bits = std::mem::size_of::<$ty>() * 8;
248        let sign_bit = 1 << (num_bits - 1);
249        if $value & sign_bit == sign_bit {
250            // Negative numbers:
251            !$value
252        } else {
253            // Positive numbers:
254            $value | sign_bit
255        }
256    }};
257}
258
259impl Interval {
260    /// Attempts to create a new `Interval` from the given lower and upper bounds.
261    ///
262    /// # Notes
263    ///
264    /// This constructor creates intervals in a "canonical" form where:
265    /// - **Boolean intervals**:
266    ///   - Unboundedness (`NULL`) for boolean endpoints is converted to `false`
267    ///     for lower and `true` for upper bounds.
268    /// - **Floating-point intervals**:
269    ///   - Floating-point endpoints with `NaN`, `INF`, or `NEG_INF` are converted
270    ///     to `NULL`s.
271    pub fn try_new(lower: ScalarValue, upper: ScalarValue) -> Result<Self> {
272        assert_eq_or_internal_err!(
273            lower.data_type(),
274            upper.data_type(),
275            "Endpoints of an Interval should have the same type"
276        );
277
278        let interval = Self::new(lower, upper);
279
280        assert_or_internal_err!(
281            interval.lower.is_null()
282                || interval.upper.is_null()
283                || interval.lower <= interval.upper,
284            "Interval's lower bound {} is greater than the upper bound {}",
285            interval.lower,
286            interval.upper
287        );
288        Ok(interval)
289    }
290
291    /// Only for internal usage. Responsible for standardizing booleans and
292    /// floating-point values, as well as fixing NaNs. It doesn't validate
293    /// the given bounds for ordering, or verify that they have the same data
294    /// type. For its user-facing counterpart and more details, see
295    /// [`Interval::try_new`].
296    fn new(lower: ScalarValue, upper: ScalarValue) -> Self {
297        if let ScalarValue::Boolean(lower_bool) = lower {
298            let ScalarValue::Boolean(upper_bool) = upper else {
299                // We are sure that upper and lower bounds have the same type.
300                unreachable!();
301            };
302            // Standardize boolean interval endpoints:
303            return Self {
304                lower: ScalarValue::Boolean(Some(lower_bool.unwrap_or(false))),
305                upper: ScalarValue::Boolean(Some(upper_bool.unwrap_or(true))),
306            };
307        }
308        match lower.data_type() {
309            // Standardize floating-point endpoints:
310            DataType::Float32 => handle_float_intervals!(Float32, f32, lower, upper),
311            DataType::Float64 => handle_float_intervals!(Float64, f64, lower, upper),
312            // Unsigned null values for lower bounds are set to zero:
313            DataType::UInt8 if lower.is_null() => Self {
314                lower: ScalarValue::UInt8(Some(0)),
315                upper,
316            },
317            DataType::UInt16 if lower.is_null() => Self {
318                lower: ScalarValue::UInt16(Some(0)),
319                upper,
320            },
321            DataType::UInt32 if lower.is_null() => Self {
322                lower: ScalarValue::UInt32(Some(0)),
323                upper,
324            },
325            DataType::UInt64 if lower.is_null() => Self {
326                lower: ScalarValue::UInt64(Some(0)),
327                upper,
328            },
329            // Other data types do not require standardization:
330            _ => Self { lower, upper },
331        }
332    }
333
334    /// Convenience function to create a new `Interval` from the given (optional)
335    /// bounds, for use in tests only. Absence of either endpoint indicates
336    /// unboundedness on that side. See [`Interval::try_new`] for more information.
337    pub fn make<T>(lower: Option<T>, upper: Option<T>) -> Result<Self>
338    where
339        ScalarValue: From<Option<T>>,
340    {
341        Self::try_new(ScalarValue::from(lower), ScalarValue::from(upper))
342    }
343
344    /// Creates a singleton zero interval if the datatype supported.
345    pub fn make_zero(data_type: &DataType) -> Result<Self> {
346        let zero_endpoint = ScalarValue::new_zero(data_type)?;
347        Ok(Self::new(zero_endpoint.clone(), zero_endpoint))
348    }
349
350    /// Creates an unbounded interval from both sides if the datatype supported.
351    pub fn make_unbounded(data_type: &DataType) -> Result<Self> {
352        let unbounded_endpoint = ScalarValue::try_from(data_type)?;
353        Ok(Self::new(unbounded_endpoint.clone(), unbounded_endpoint))
354    }
355
356    /// Creates an interval between -1 to 1.
357    pub fn make_symmetric_unit_interval(data_type: &DataType) -> Result<Self> {
358        Self::try_new(
359            ScalarValue::new_negative_one(data_type)?,
360            ScalarValue::new_one(data_type)?,
361        )
362    }
363
364    /// Create an interval from -π to π.
365    pub fn make_symmetric_pi_interval(data_type: &DataType) -> Result<Self> {
366        Self::try_new(
367            ScalarValue::new_negative_pi_lower(data_type)?,
368            ScalarValue::new_pi_upper(data_type)?,
369        )
370    }
371
372    /// Create an interval from -π/2 to π/2.
373    pub fn make_symmetric_half_pi_interval(data_type: &DataType) -> Result<Self> {
374        Self::try_new(
375            ScalarValue::new_neg_frac_pi_2_lower(data_type)?,
376            ScalarValue::new_frac_pi_2_upper(data_type)?,
377        )
378    }
379
380    /// Create an interval from 0 to infinity.
381    pub fn make_non_negative_infinity_interval(data_type: &DataType) -> Result<Self> {
382        Self::try_new(
383            ScalarValue::new_zero(data_type)?,
384            ScalarValue::try_from(data_type)?,
385        )
386    }
387
388    /// Returns a reference to the lower bound.
389    pub fn lower(&self) -> &ScalarValue {
390        &self.lower
391    }
392
393    /// Returns a reference to the upper bound.
394    pub fn upper(&self) -> &ScalarValue {
395        &self.upper
396    }
397
398    /// Converts this `Interval` into its boundary scalar values. It's useful
399    /// when you need to work with the individual bounds directly.
400    pub fn into_bounds(self) -> (ScalarValue, ScalarValue) {
401        (self.lower, self.upper)
402    }
403
404    /// This function returns the data type of this interval.
405    pub fn data_type(&self) -> DataType {
406        let lower_type = self.lower.data_type();
407        let upper_type = self.upper.data_type();
408
409        // There must be no way to create an interval whose endpoints have
410        // different types.
411        debug_assert!(
412            lower_type == upper_type,
413            "Interval bounds have different types: {lower_type} != {upper_type}"
414        );
415        lower_type
416    }
417
418    /// Checks if the interval is unbounded (on either side).
419    pub fn is_unbounded(&self) -> bool {
420        self.lower.is_null() || self.upper.is_null()
421    }
422
423    /// Casts this interval to `data_type` using `cast_options`.
424    pub fn cast_to(
425        &self,
426        data_type: &DataType,
427        cast_options: &CastOptions,
428    ) -> Result<Self> {
429        Self::try_new(
430            cast_scalar_value(&self.lower, data_type, cast_options)?,
431            cast_scalar_value(&self.upper, data_type, cast_options)?,
432        )
433    }
434
435    /// An interval containing only the 'false' truth value.
436    pub const FALSE: Self = Self {
437        lower: ScalarValue::Boolean(Some(false)),
438        upper: ScalarValue::Boolean(Some(false)),
439    };
440
441    #[deprecated(since = "52.0.0", note = "Use `FALSE` instead")]
442    pub const CERTAINLY_FALSE: Self = Self::FALSE;
443
444    /// An interval containing both the 'true', and 'false' truth values.
445    pub const TRUE_OR_FALSE: Self = Self {
446        lower: ScalarValue::Boolean(Some(false)),
447        upper: ScalarValue::Boolean(Some(true)),
448    };
449
450    #[deprecated(since = "52.0.0", note = "Use `TRUE_OR_FALSE` instead")]
451    pub const UNCERTAIN: Self = Self::TRUE_OR_FALSE;
452
453    /// An interval containing only the 'true' truth value.
454    pub const TRUE: Self = Self {
455        lower: ScalarValue::Boolean(Some(true)),
456        upper: ScalarValue::Boolean(Some(true)),
457    };
458
459    #[deprecated(since = "52.0.0", note = "Use `TRUE` instead")]
460    pub const CERTAINLY_TRUE: Self = Self::TRUE;
461
462    /// Decide if this interval is certainly greater than, possibly greater than,
463    /// or can't be greater than `other` by returning `[true, true]`,
464    /// `[false, true]` or `[false, false]` respectively.
465    ///
466    /// NOTE: This function only works with intervals of the same data type.
467    ///       Attempting to compare intervals of different data types will lead
468    ///       to an error.
469    pub fn gt<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
470        let rhs = other.borrow();
471        let lhs_type = self.data_type();
472        let rhs_type = rhs.data_type();
473        assert_eq_or_internal_err!(
474            lhs_type,
475            rhs_type,
476            "Only intervals with the same data type are comparable, lhs:{}, rhs:{}",
477            self.data_type(),
478            rhs.data_type()
479        );
480        if !(self.upper.is_null() || rhs.lower.is_null()) && self.upper <= rhs.lower {
481            // Values in this interval are certainly less than or equal to
482            // those in the given interval.
483            Ok(Self::FALSE)
484        } else if !(self.lower.is_null() || rhs.upper.is_null())
485            && (self.lower > rhs.upper)
486        {
487            // Values in this interval are certainly greater than those in the
488            // given interval.
489            Ok(Self::TRUE)
490        } else {
491            // All outcomes are possible.
492            Ok(Self::TRUE_OR_FALSE)
493        }
494    }
495
496    /// Decide if this interval is certainly greater than or equal to, possibly
497    /// greater than or equal to, or can't be greater than or equal to `other`
498    /// by returning `[true, true]`, `[false, true]` or `[false, false]` respectively.
499    ///
500    /// NOTE: This function only works with intervals of the same data type.
501    ///       Attempting to compare intervals of different data types will lead
502    ///       to an error.
503    pub fn gt_eq<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
504        let rhs = other.borrow();
505        let lhs_type = self.data_type();
506        let rhs_type = rhs.data_type();
507        assert_eq_or_internal_err!(
508            lhs_type,
509            rhs_type,
510            "Only intervals with the same data type are comparable, lhs:{}, rhs:{}",
511            self.data_type(),
512            rhs.data_type()
513        );
514        if !(self.lower.is_null() || rhs.upper.is_null()) && self.lower >= rhs.upper {
515            // Values in this interval are certainly greater than or equal to
516            // those in the given interval.
517            Ok(Self::TRUE)
518        } else if !(self.upper.is_null() || rhs.lower.is_null())
519            && (self.upper < rhs.lower)
520        {
521            // Values in this interval are certainly less than those in the
522            // given interval.
523            Ok(Self::FALSE)
524        } else {
525            // All outcomes are possible.
526            Ok(Self::TRUE_OR_FALSE)
527        }
528    }
529
530    /// Decide if this interval is certainly less than, possibly less than, or
531    /// can't be less than `other` by returning `[true, true]`, `[false, true]`
532    /// or `[false, false]` respectively.
533    ///
534    /// NOTE: This function only works with intervals of the same data type.
535    ///       Attempting to compare intervals of different data types will lead
536    ///       to an error.
537    pub fn lt<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
538        other.borrow().gt(self)
539    }
540
541    /// Decide if this interval is certainly less than or equal to, possibly
542    /// less than or equal to, or can't be less than or equal to `other` by
543    /// returning `[true, true]`, `[false, true]` or `[false, false]` respectively.
544    ///
545    /// NOTE: This function only works with intervals of the same data type.
546    ///       Attempting to compare intervals of different data types will lead
547    ///       to an error.
548    pub fn lt_eq<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
549        other.borrow().gt_eq(self)
550    }
551
552    /// Decide if this interval is certainly equal to, possibly equal to, or
553    /// can't be equal to `other` by returning `[true, true]`, `[false, true]`
554    /// or `[false, false]` respectively.
555    ///
556    /// NOTE: This function only works with intervals of the same data type.
557    ///       Attempting to compare intervals of different data types will lead
558    ///       to an error.
559    pub fn equal<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
560        let rhs = other.borrow();
561        let types_compatible =
562            BinaryTypeCoercer::new(&self.data_type(), &Operator::Eq, &rhs.data_type())
563                .get_result_type()
564                .is_ok();
565        assert_or_internal_err!(
566            types_compatible,
567            "Interval data types must be compatible for equality checks, lhs:{}, rhs:{}",
568            self.data_type(),
569            rhs.data_type()
570        );
571        if !self.lower.is_null()
572            && (self.lower == self.upper)
573            && (rhs.lower == rhs.upper)
574            && (self.lower == rhs.lower)
575        {
576            Ok(Self::TRUE)
577        } else if self.intersect(rhs)?.is_none() {
578            Ok(Self::FALSE)
579        } else {
580            Ok(Self::TRUE_OR_FALSE)
581        }
582    }
583
584    /// Compute the logical conjunction of this (boolean) interval with the
585    /// given boolean interval.
586    pub fn and<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
587        let rhs = other.borrow();
588        match (&self.lower, &self.upper, &rhs.lower, &rhs.upper) {
589            (
590                &ScalarValue::Boolean(Some(self_lower)),
591                &ScalarValue::Boolean(Some(self_upper)),
592                &ScalarValue::Boolean(Some(other_lower)),
593                &ScalarValue::Boolean(Some(other_upper)),
594            ) => {
595                let lower = self_lower && other_lower;
596                let upper = self_upper && other_upper;
597
598                Ok(Self {
599                    lower: ScalarValue::Boolean(Some(lower)),
600                    upper: ScalarValue::Boolean(Some(upper)),
601                })
602            }
603
604            // Return TRUE_OR_FALSE when intervals don't have concrete boolean bounds
605            _ => Ok(Self::TRUE_OR_FALSE),
606        }
607    }
608
609    /// Compute the logical disjunction of this boolean interval with the
610    /// given boolean interval.
611    pub fn or<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
612        let rhs = other.borrow();
613        match (&self.lower, &self.upper, &rhs.lower, &rhs.upper) {
614            (
615                &ScalarValue::Boolean(Some(self_lower)),
616                &ScalarValue::Boolean(Some(self_upper)),
617                &ScalarValue::Boolean(Some(other_lower)),
618                &ScalarValue::Boolean(Some(other_upper)),
619            ) => {
620                let lower = self_lower || other_lower;
621                let upper = self_upper || other_upper;
622
623                Ok(Self {
624                    lower: ScalarValue::Boolean(Some(lower)),
625                    upper: ScalarValue::Boolean(Some(upper)),
626                })
627            }
628
629            // Return TRUE_OR_FALSE when intervals don't have concrete boolean bounds
630            _ => Ok(Self::TRUE_OR_FALSE),
631        }
632    }
633
634    /// Compute the logical negation of this (boolean) interval.
635    pub fn not(&self) -> Result<Self> {
636        assert_eq_or_internal_err!(
637            self.data_type(),
638            DataType::Boolean,
639            "Cannot apply logical negation to a non-boolean interval"
640        );
641        if self == &Self::TRUE {
642            Ok(Self::FALSE)
643        } else if self == &Self::FALSE {
644            Ok(Self::TRUE)
645        } else {
646            Ok(Self::TRUE_OR_FALSE)
647        }
648    }
649
650    /// Compute the intersection of this interval with the given interval.
651    /// If the intersection is empty, return `None`.
652    ///
653    /// NOTE: This function only works with intervals of the same data type.
654    ///       Attempting to compare intervals of different data types will lead
655    ///       to an error.
656    pub fn intersect<T: Borrow<Self>>(&self, other: T) -> Result<Option<Self>> {
657        let rhs = other.borrow();
658        let lhs_type = self.data_type();
659        let rhs_type = rhs.data_type();
660        assert_eq_or_internal_err!(
661            lhs_type,
662            rhs_type,
663            "Only intervals with the same data type are intersectable, lhs:{}, rhs:{}",
664            self.data_type(),
665            rhs.data_type()
666        );
667
668        // If it is evident that the result is an empty interval, short-circuit
669        // and directly return `None`.
670        if (!(self.lower.is_null() || rhs.upper.is_null()) && self.lower > rhs.upper)
671            || (!(self.upper.is_null() || rhs.lower.is_null()) && self.upper < rhs.lower)
672        {
673            return Ok(None);
674        }
675
676        let lower = max_of_bounds(&self.lower, &rhs.lower);
677        let upper = min_of_bounds(&self.upper, &rhs.upper);
678
679        // New lower and upper bounds must always construct a valid interval.
680        debug_assert!(
681            (lower.is_null() || upper.is_null() || (lower <= upper)),
682            "The intersection of two intervals can not be an invalid interval"
683        );
684
685        Ok(Some(Self { lower, upper }))
686    }
687
688    /// Compute the union of this interval with the given interval.
689    ///
690    /// NOTE: This function only works with intervals of the same data type.
691    ///       Attempting to compare intervals of different data types will lead
692    ///       to an error.
693    pub fn union<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
694        let rhs = other.borrow();
695        let lhs_type = self.data_type();
696        let rhs_type = rhs.data_type();
697        assert_eq_or_internal_err!(
698            lhs_type,
699            rhs_type,
700            "Cannot calculate the union of intervals with different data types, lhs:{}, rhs:{}",
701            self.data_type(),
702            rhs.data_type()
703        );
704
705        let lower = if self.lower.is_null()
706            || (!rhs.lower.is_null() && self.lower <= rhs.lower)
707        {
708            self.lower.clone()
709        } else {
710            rhs.lower.clone()
711        };
712        let upper = if self.upper.is_null()
713            || (!rhs.upper.is_null() && self.upper >= rhs.upper)
714        {
715            self.upper.clone()
716        } else {
717            rhs.upper.clone()
718        };
719
720        // New lower and upper bounds must always construct a valid interval.
721        debug_assert!(
722            (lower.is_null() || upper.is_null() || (lower <= upper)),
723            "The union of two intervals can not be an invalid interval"
724        );
725
726        Ok(Self { lower, upper })
727    }
728
729    /// Decide if this interval contains a [`ScalarValue`] (`other`) by returning `true` or `false`.
730    pub fn contains_value<T: Borrow<ScalarValue>>(&self, other: T) -> Result<bool> {
731        let rhs = other.borrow();
732
733        let (lhs_lower, lhs_upper, rhs_value) = if self.data_type().eq(&rhs.data_type()) {
734            (self.lower.clone(), self.upper.clone(), rhs.clone())
735        } else {
736            let maybe_common_type =
737                comparison_coercion_numeric(&self.data_type(), &rhs.data_type());
738            assert_or_internal_err!(
739                maybe_common_type.is_some(),
740                "Data types must be compatible for containment checks, lhs:{}, rhs:{}",
741                self.data_type(),
742                rhs.data_type()
743            );
744            let common_type = maybe_common_type.expect("checked for Some");
745            (
746                self.lower.cast_to(&common_type)?,
747                self.upper.cast_to(&common_type)?,
748                rhs.cast_to(&common_type)?,
749            )
750        };
751
752        // We only check the upper bound for a `None` value because `None`
753        // values are less than `Some` values according to Rust.
754        Ok(lhs_lower <= rhs_value && (lhs_upper.is_null() || rhs_value <= lhs_upper))
755    }
756
757    /// Decide if this interval is a superset of, overlaps with, or
758    /// disjoint with `other` by returning `[true, true]`, `[false, true]` or
759    /// `[false, false]` respectively.
760    ///
761    /// NOTE: This function only works with intervals of the same data type.
762    ///       Attempting to compare intervals of different data types will lead
763    ///       to an error.
764    pub fn contains<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
765        let rhs = other.borrow();
766        let lhs_type = self.data_type();
767        let rhs_type = rhs.data_type();
768        assert_eq_or_internal_err!(
769            lhs_type,
770            rhs_type,
771            "Interval data types must match for containment checks, lhs:{}, rhs:{}",
772            self.data_type(),
773            rhs.data_type()
774        );
775
776        match self.intersect(rhs)? {
777            Some(intersection) => {
778                if &intersection == rhs {
779                    Ok(Self::TRUE)
780                } else {
781                    Ok(Self::TRUE_OR_FALSE)
782                }
783            }
784            None => Ok(Self::FALSE),
785        }
786    }
787
788    /// Decide if this interval is a superset of `other`. If argument `strict`
789    /// is `true`, only returns `true` if this interval is a strict superset.
790    ///
791    /// NOTE: This function only works with intervals of the same data type.
792    ///       Attempting to compare intervals of different data types will lead
793    ///       to an error.
794    pub fn is_superset(&self, other: &Interval, strict: bool) -> Result<bool> {
795        Ok(!(strict && self.eq(other)) && (self.contains(other)? == Interval::TRUE))
796    }
797
798    /// Add the given interval (`other`) to this interval. Say we have intervals
799    /// `[a1, b1]` and `[a2, b2]`, then their sum is `[a1 + a2, b1 + b2]`. Note
800    /// that this represents all possible values the sum can take if one can
801    /// choose single values arbitrarily from each of the operands.
802    pub fn add<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
803        let rhs = other.borrow();
804        let dt =
805            BinaryTypeCoercer::new(&self.data_type(), &Operator::Plus, &rhs.data_type())
806                .get_result_type()?;
807
808        Ok(Self::new(
809            add_bounds::<false>(&dt, &self.lower, &rhs.lower),
810            add_bounds::<true>(&dt, &self.upper, &rhs.upper),
811        ))
812    }
813
814    /// Subtract the given interval (`other`) from this interval. Say we have
815    /// intervals `[a1, b1]` and `[a2, b2]`, then their difference is
816    /// `[a1 - b2, b1 - a2]`. Note that this represents all possible values the
817    /// difference can take if one can choose single values arbitrarily from
818    /// each of the operands.
819    pub fn sub<T: Borrow<Interval>>(&self, other: T) -> Result<Self> {
820        let rhs = other.borrow();
821        let dt =
822            BinaryTypeCoercer::new(&self.data_type(), &Operator::Minus, &rhs.data_type())
823                .get_result_type()?;
824
825        Ok(Self::new(
826            sub_bounds::<false>(&dt, &self.lower, &rhs.upper),
827            sub_bounds::<true>(&dt, &self.upper, &rhs.lower),
828        ))
829    }
830
831    /// Multiply the given interval (`other`) with this interval. Say we have
832    /// intervals `[a1, b1]` and `[a2, b2]`, then their product is `[min(a1 * a2,
833    /// a1 * b2, b1 * a2, b1 * b2), max(a1 * a2, a1 * b2, b1 * a2, b1 * b2)]`.
834    /// Note that this represents all possible values the product can take if
835    /// one can choose single values arbitrarily from each of the operands.
836    ///
837    /// NOTE: This function only works with intervals of the same data type.
838    ///       Attempting to compare intervals of different data types will lead
839    ///       to an error.
840    pub fn mul<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
841        let rhs = other.borrow();
842        let dt = self.data_type();
843        let rhs_type = rhs.data_type();
844        assert_eq_or_internal_err!(
845            dt.clone(),
846            rhs_type.clone(),
847            "Intervals must have the same data type for multiplication, lhs:{}, rhs:{}",
848            dt.clone(),
849            rhs_type.clone()
850        );
851
852        let zero = ScalarValue::new_zero(&dt)?;
853
854        let result = match (
855            self.contains_value(&zero)?,
856            rhs.contains_value(&zero)?,
857            dt.is_unsigned_integer(),
858        ) {
859            (true, true, false) => mul_helper_multi_zero_inclusive(&dt, self, rhs),
860            (true, false, false) => {
861                mul_helper_single_zero_inclusive(&dt, self, rhs, &zero)
862            }
863            (false, true, false) => {
864                mul_helper_single_zero_inclusive(&dt, rhs, self, &zero)
865            }
866            _ => mul_helper_zero_exclusive(&dt, self, rhs, &zero),
867        };
868        Ok(result)
869    }
870
871    /// Divide this interval by the given interval (`other`). Say we have intervals
872    /// `[a1, b1]` and `[a2, b2]`, then their division is `[a1, b1] * [1 / b2, 1 / a2]`
873    /// if `0 ∉ [a2, b2]` and `[NEG_INF, INF]` otherwise. Note that this represents
874    /// all possible values the quotient can take if one can choose single values
875    /// arbitrarily from each of the operands.
876    ///
877    /// NOTE: This function only works with intervals of the same data type.
878    ///       Attempting to compare intervals of different data types will lead
879    ///       to an error.
880    ///
881    /// **TODO**: Once interval sets are supported, cases where the divisor contains
882    ///           zero should result in an interval set, not the universal set.
883    pub fn div<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
884        let rhs = other.borrow();
885        let dt = self.data_type();
886        let rhs_type = rhs.data_type();
887        assert_eq_or_internal_err!(
888            dt.clone(),
889            rhs_type.clone(),
890            "Intervals must have the same data type for division, lhs:{}, rhs:{}",
891            dt.clone(),
892            rhs_type.clone()
893        );
894
895        let zero = ScalarValue::new_zero(&dt)?;
896        // We want 0 to be approachable from both negative and positive sides.
897        let zero_point = match &dt {
898            DataType::Float32 | DataType::Float64 => Self::new(zero.clone(), zero),
899            _ => Self::new(prev_value(zero.clone()), next_value(zero)),
900        };
901
902        // Exit early with an unbounded interval if zero is strictly inside the
903        // right hand side:
904        if rhs.contains(&zero_point)? == Self::TRUE && !dt.is_unsigned_integer() {
905            Self::make_unbounded(&dt)
906        }
907        // At this point, we know that only one endpoint of the right hand side
908        // can be zero.
909        else if self.contains(&zero_point)? == Self::TRUE && !dt.is_unsigned_integer() {
910            Ok(div_helper_lhs_zero_inclusive(&dt, self, rhs, &zero_point))
911        } else {
912            Ok(div_helper_zero_exclusive(&dt, self, rhs, &zero_point))
913        }
914    }
915
916    /// Computes the width of this interval; i.e. the difference between its
917    /// bounds. For unbounded intervals, this function will return a `NULL`
918    /// `ScalarValue` If the underlying data type doesn't support subtraction,
919    /// this function will return an error.
920    pub fn width(&self) -> Result<ScalarValue> {
921        let dt = self.data_type();
922        let width_dt =
923            BinaryTypeCoercer::new(&dt, &Operator::Minus, &dt).get_result_type()?;
924        Ok(sub_bounds::<true>(&width_dt, &self.upper, &self.lower))
925    }
926
927    /// Returns the cardinality of this interval, which is the number of all
928    /// distinct points inside it. This function returns `None` if:
929    /// - The interval is unbounded from either side, or
930    /// - Cardinality calculations for the datatype in question is not
931    ///   implemented yet, or
932    /// - An overflow occurs during the calculation: This case can only arise
933    ///   when the calculated cardinality does not fit in an `u64`.
934    pub fn cardinality(&self) -> Option<u64> {
935        let data_type = self.data_type();
936        if data_type.is_integer() {
937            self.upper.distance(&self.lower).map(|diff| diff as u64)
938        } else if data_type.is_floating() {
939            // Negative numbers are sorted in the reverse order. To
940            // always have a positive difference after the subtraction,
941            // we perform following transformation:
942            match (&self.lower, &self.upper) {
943                // Exploit IEEE 754 ordering properties to calculate the correct
944                // cardinality in all cases (including subnormals).
945                (
946                    ScalarValue::Float32(Some(lower)),
947                    ScalarValue::Float32(Some(upper)),
948                ) => {
949                    let lower_bits = map_floating_point_order!(lower.to_bits(), u32);
950                    let upper_bits = map_floating_point_order!(upper.to_bits(), u32);
951                    Some((upper_bits - lower_bits) as u64)
952                }
953                (
954                    ScalarValue::Float64(Some(lower)),
955                    ScalarValue::Float64(Some(upper)),
956                ) => {
957                    let lower_bits = map_floating_point_order!(lower.to_bits(), u64);
958                    let upper_bits = map_floating_point_order!(upper.to_bits(), u64);
959                    let count = upper_bits - lower_bits;
960                    (count != u64::MAX).then_some(count)
961                }
962                _ => None,
963            }
964        } else {
965            // Cardinality calculations are not implemented for this data type yet:
966            None
967        }
968        .map(|result| result + 1)
969    }
970
971    /// Reflects an [`Interval`] around the point zero.
972    ///
973    /// This method computes the arithmetic negation of the interval, reflecting
974    /// it about the origin of the number line. This operation swaps and negates
975    /// the lower and upper bounds of the interval.
976    pub fn arithmetic_negate(&self) -> Result<Self> {
977        Ok(Self {
978            lower: self.upper.arithmetic_negate()?,
979            upper: self.lower.arithmetic_negate()?,
980        })
981    }
982}
983
984impl Display for Interval {
985    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
986        write!(f, "[{}, {}]", self.lower, self.upper)
987    }
988}
989
990impl From<ScalarValue> for Interval {
991    fn from(value: ScalarValue) -> Self {
992        Self::new(value.clone(), value)
993    }
994}
995
996impl From<&ScalarValue> for Interval {
997    fn from(value: &ScalarValue) -> Self {
998        Self::new(value.to_owned(), value.to_owned())
999    }
1000}
1001
1002/// Applies the given binary operator the `lhs` and `rhs` arguments.
1003pub fn apply_operator(op: &Operator, lhs: &Interval, rhs: &Interval) -> Result<Interval> {
1004    match *op {
1005        Operator::Eq => lhs.equal(rhs),
1006        Operator::NotEq => lhs.equal(rhs)?.not(),
1007        Operator::Gt => lhs.gt(rhs),
1008        Operator::GtEq => lhs.gt_eq(rhs),
1009        Operator::Lt => lhs.lt(rhs),
1010        Operator::LtEq => lhs.lt_eq(rhs),
1011        Operator::And => lhs.and(rhs),
1012        Operator::Or => lhs.or(rhs),
1013        Operator::Plus => lhs.add(rhs),
1014        Operator::Minus => lhs.sub(rhs),
1015        Operator::Multiply => lhs.mul(rhs),
1016        Operator::Divide => lhs.div(rhs),
1017        _ => internal_err!("Interval arithmetic does not support the operator {op}"),
1018    }
1019}
1020
1021/// Helper function used for adding the end-point values of intervals.
1022///
1023/// **Caution:** This function contains multiple calls to `unwrap()`, and may
1024/// return non-standardized interval bounds. Therefore, it should be used
1025/// with caution. Currently, it is used in contexts where the `DataType`
1026/// (`dt`) is validated prior to calling this function, and the following
1027/// interval creation is standardized with `Interval::new`.
1028fn add_bounds<const UPPER: bool>(
1029    dt: &DataType,
1030    lhs: &ScalarValue,
1031    rhs: &ScalarValue,
1032) -> ScalarValue {
1033    if lhs.is_null() || rhs.is_null() {
1034        return ScalarValue::try_from(dt).unwrap();
1035    }
1036
1037    match dt {
1038        DataType::Float64 | DataType::Float32 => {
1039            alter_fp_rounding_mode::<UPPER, _>(lhs, rhs, |lhs, rhs| lhs.add_checked(rhs))
1040        }
1041        _ => lhs.add_checked(rhs),
1042    }
1043    .unwrap_or_else(|_| handle_overflow::<UPPER>(dt, Operator::Plus, lhs, rhs))
1044}
1045
1046/// Helper function used for subtracting the end-point values of intervals.
1047///
1048/// **Caution:** This function contains multiple calls to `unwrap()`, and may
1049/// return non-standardized interval bounds. Therefore, it should be used
1050/// with caution. Currently, it is used in contexts where the `DataType`
1051/// (`dt`) is validated prior to calling this function, and the following
1052/// interval creation is standardized with `Interval::new`.
1053fn sub_bounds<const UPPER: bool>(
1054    dt: &DataType,
1055    lhs: &ScalarValue,
1056    rhs: &ScalarValue,
1057) -> ScalarValue {
1058    if lhs.is_null() || rhs.is_null() {
1059        return ScalarValue::try_from(dt).unwrap();
1060    }
1061
1062    match dt {
1063        DataType::Float64 | DataType::Float32 => {
1064            alter_fp_rounding_mode::<UPPER, _>(lhs, rhs, |lhs, rhs| lhs.sub_checked(rhs))
1065        }
1066        _ => lhs.sub_checked(rhs),
1067    }
1068    .unwrap_or_else(|_| handle_overflow::<UPPER>(dt, Operator::Minus, lhs, rhs))
1069}
1070
1071/// Helper function used for multiplying the end-point values of intervals.
1072///
1073/// **Caution:** This function contains multiple calls to `unwrap()`, and may
1074/// return non-standardized interval bounds. Therefore, it should be used
1075/// with caution. Currently, it is used in contexts where the `DataType`
1076/// (`dt`) is validated prior to calling this function, and the following
1077/// interval creation is standardized with `Interval::new`.
1078fn mul_bounds<const UPPER: bool>(
1079    dt: &DataType,
1080    lhs: &ScalarValue,
1081    rhs: &ScalarValue,
1082) -> ScalarValue {
1083    if lhs.is_null() || rhs.is_null() {
1084        return ScalarValue::try_from(dt).unwrap();
1085    }
1086
1087    match dt {
1088        DataType::Float64 | DataType::Float32 => {
1089            alter_fp_rounding_mode::<UPPER, _>(lhs, rhs, |lhs, rhs| lhs.mul_checked(rhs))
1090        }
1091        _ => lhs.mul_checked(rhs),
1092    }
1093    .unwrap_or_else(|_| handle_overflow::<UPPER>(dt, Operator::Multiply, lhs, rhs))
1094}
1095
1096/// Helper function used for dividing the end-point values of intervals.
1097///
1098/// **Caution:** This function contains multiple calls to `unwrap()`, and may
1099/// return non-standardized interval bounds. Therefore, it should be used
1100/// with caution. Currently, it is used in contexts where the `DataType`
1101/// (`dt`) is validated prior to calling this function, and the following
1102/// interval creation is standardized with `Interval::new`.
1103fn div_bounds<const UPPER: bool>(
1104    dt: &DataType,
1105    lhs: &ScalarValue,
1106    rhs: &ScalarValue,
1107) -> ScalarValue {
1108    let zero = ScalarValue::new_zero(dt).unwrap();
1109
1110    if (lhs.is_null() || rhs.eq(&zero)) || (dt.is_unsigned_integer() && rhs.is_null()) {
1111        return ScalarValue::try_from(dt).unwrap();
1112    } else if rhs.is_null() {
1113        return zero;
1114    }
1115
1116    match dt {
1117        DataType::Float64 | DataType::Float32 => {
1118            alter_fp_rounding_mode::<UPPER, _>(lhs, rhs, |lhs, rhs| lhs.div(rhs))
1119        }
1120        _ => lhs.div(rhs),
1121    }
1122    .unwrap_or_else(|_| handle_overflow::<UPPER>(dt, Operator::Divide, lhs, rhs))
1123}
1124
1125/// This function handles cases where an operation results in an overflow. Such
1126/// results are converted to an *unbounded endpoint* if:
1127///   - We are calculating an upper bound and we have a positive overflow.
1128///   - We are calculating a lower bound and we have a negative overflow.
1129///
1130/// Otherwise, the function sets the endpoint as:
1131///   - The minimum representable number with the given datatype (`dt`) if
1132///     we are calculating an upper bound and we have a negative overflow.
1133///   - The maximum representable number with the given datatype (`dt`) if
1134///     we are calculating a lower bound and we have a positive overflow.
1135///
1136/// **Caution:** This function contains multiple calls to `unwrap()`, and may
1137/// return non-standardized interval bounds. Therefore, it should be used
1138/// with caution. Currently, it is used in contexts where the `DataType`
1139/// (`dt`) is validated prior to calling this function,  `op` is supported by
1140/// interval library, and the following interval creation is standardized with
1141/// `Interval::new`.
1142fn handle_overflow<const UPPER: bool>(
1143    dt: &DataType,
1144    op: Operator,
1145    lhs: &ScalarValue,
1146    rhs: &ScalarValue,
1147) -> ScalarValue {
1148    let lhs_zero = ScalarValue::new_zero(&lhs.data_type()).unwrap();
1149    let rhs_zero = ScalarValue::new_zero(&rhs.data_type()).unwrap();
1150    let positive_sign = match op {
1151        Operator::Multiply | Operator::Divide => {
1152            lhs.lt(&lhs_zero) && rhs.lt(&rhs_zero)
1153                || lhs.gt(&lhs_zero) && rhs.gt(&rhs_zero)
1154        }
1155        Operator::Plus => lhs.ge(&lhs_zero),
1156        Operator::Minus => lhs.ge(rhs),
1157        _ => {
1158            unreachable!()
1159        }
1160    };
1161
1162    match (UPPER, positive_sign) {
1163        (true, true) | (false, false) => ScalarValue::try_from(dt).unwrap(),
1164        (true, false) => {
1165            get_extreme_value!(MIN, dt)
1166        }
1167        (false, true) => {
1168            get_extreme_value!(MAX, dt)
1169        }
1170    }
1171}
1172
1173// This function should remain private since it may corrupt the an interval if
1174// used without caution.
1175fn next_value(value: ScalarValue) -> ScalarValue {
1176    use ScalarValue::*;
1177    value_transition!(MAX, true, value)
1178}
1179
1180// This function should remain private since it may corrupt the an interval if
1181// used without caution.
1182fn prev_value(value: ScalarValue) -> ScalarValue {
1183    use ScalarValue::*;
1184    value_transition!(MIN, false, value)
1185}
1186
1187trait OneTrait: Sized + std::ops::Add + std::ops::Sub {
1188    fn one() -> Self;
1189}
1190macro_rules! impl_OneTrait{
1191    ($($m:ty),*) => {$( impl OneTrait for $m  { fn one() -> Self { 1 as $m } })*}
1192}
1193impl_OneTrait! {u8, u16, u32, u64, i8, i16, i32, i64, i128}
1194
1195impl OneTrait for IntervalDayTime {
1196    fn one() -> Self {
1197        IntervalDayTime {
1198            days: 0,
1199            milliseconds: 1,
1200        }
1201    }
1202}
1203
1204impl OneTrait for IntervalMonthDayNano {
1205    fn one() -> Self {
1206        IntervalMonthDayNano {
1207            months: 0,
1208            days: 0,
1209            nanoseconds: 1,
1210        }
1211    }
1212}
1213
1214/// This function either increments or decrements its argument, depending on
1215/// the `INC` value (where a `true` value corresponds to the increment).
1216fn increment_decrement<const INC: bool, T: OneTrait + SubAssign + AddAssign>(
1217    mut value: T,
1218) -> T {
1219    if INC {
1220        value.add_assign(T::one());
1221    } else {
1222        value.sub_assign(T::one());
1223    }
1224    value
1225}
1226
1227/// This function returns the next/previous value depending on the `INC` value.
1228/// If `true`, it returns the next value; otherwise it returns the previous value.
1229fn next_value_helper<const INC: bool>(value: ScalarValue) -> ScalarValue {
1230    use ScalarValue::*;
1231    match value {
1232        // f32/f64::NEG_INF/INF and f32/f64::NaN values should not emerge at this point.
1233        Float32(Some(val)) => {
1234            debug_assert!(val.is_finite(), "Non-standardized floating point usage");
1235            Float32(Some(if INC { next_up(val) } else { next_down(val) }))
1236        }
1237        Float64(Some(val)) => {
1238            debug_assert!(val.is_finite(), "Non-standardized floating point usage");
1239            Float64(Some(if INC { next_up(val) } else { next_down(val) }))
1240        }
1241        Int8(Some(val)) => Int8(Some(increment_decrement::<INC, i8>(val))),
1242        Int16(Some(val)) => Int16(Some(increment_decrement::<INC, i16>(val))),
1243        Int32(Some(val)) => Int32(Some(increment_decrement::<INC, i32>(val))),
1244        Int64(Some(val)) => Int64(Some(increment_decrement::<INC, i64>(val))),
1245        UInt8(Some(val)) => UInt8(Some(increment_decrement::<INC, u8>(val))),
1246        UInt16(Some(val)) => UInt16(Some(increment_decrement::<INC, u16>(val))),
1247        UInt32(Some(val)) => UInt32(Some(increment_decrement::<INC, u32>(val))),
1248        UInt64(Some(val)) => UInt64(Some(increment_decrement::<INC, u64>(val))),
1249        DurationSecond(Some(val)) => {
1250            DurationSecond(Some(increment_decrement::<INC, i64>(val)))
1251        }
1252        DurationMillisecond(Some(val)) => {
1253            DurationMillisecond(Some(increment_decrement::<INC, i64>(val)))
1254        }
1255        DurationMicrosecond(Some(val)) => {
1256            DurationMicrosecond(Some(increment_decrement::<INC, i64>(val)))
1257        }
1258        DurationNanosecond(Some(val)) => {
1259            DurationNanosecond(Some(increment_decrement::<INC, i64>(val)))
1260        }
1261        TimestampSecond(Some(val), tz) => {
1262            TimestampSecond(Some(increment_decrement::<INC, i64>(val)), tz)
1263        }
1264        TimestampMillisecond(Some(val), tz) => {
1265            TimestampMillisecond(Some(increment_decrement::<INC, i64>(val)), tz)
1266        }
1267        TimestampMicrosecond(Some(val), tz) => {
1268            TimestampMicrosecond(Some(increment_decrement::<INC, i64>(val)), tz)
1269        }
1270        TimestampNanosecond(Some(val), tz) => {
1271            TimestampNanosecond(Some(increment_decrement::<INC, i64>(val)), tz)
1272        }
1273        IntervalYearMonth(Some(val)) => {
1274            IntervalYearMonth(Some(increment_decrement::<INC, i32>(val)))
1275        }
1276        IntervalDayTime(Some(val)) => IntervalDayTime(Some(increment_decrement::<
1277            INC,
1278            arrow::datatypes::IntervalDayTime,
1279        >(val))),
1280        IntervalMonthDayNano(Some(val)) => {
1281            IntervalMonthDayNano(Some(increment_decrement::<
1282                INC,
1283                arrow::datatypes::IntervalMonthDayNano,
1284            >(val)))
1285        }
1286        _ => value, // Unbounded values return without change.
1287    }
1288}
1289
1290/// Returns the greater of the given interval bounds. Assumes that a `NULL`
1291/// value represents `NEG_INF`.
1292fn max_of_bounds(first: &ScalarValue, second: &ScalarValue) -> ScalarValue {
1293    if !first.is_null() && (second.is_null() || first >= second) {
1294        first.clone()
1295    } else {
1296        second.clone()
1297    }
1298}
1299
1300/// Returns the lesser of the given interval bounds. Assumes that a `NULL`
1301/// value represents `INF`.
1302fn min_of_bounds(first: &ScalarValue, second: &ScalarValue) -> ScalarValue {
1303    if !first.is_null() && (second.is_null() || first <= second) {
1304        first.clone()
1305    } else {
1306        second.clone()
1307    }
1308}
1309
1310/// This function updates the given intervals by enforcing (i.e. propagating)
1311/// the inequality `left > right` (or the `left >= right` inequality, if `strict`
1312/// is `true`).
1313///
1314/// Returns a `Result` wrapping an `Option` containing the tuple of resulting
1315/// intervals. If the comparison is infeasible, returns `None`.
1316///
1317/// Example usage:
1318/// ```
1319/// use datafusion_common::DataFusionError;
1320/// use datafusion_expr_common::interval_arithmetic::{satisfy_greater, Interval};
1321///
1322/// let left = Interval::make(Some(-1000.0_f32), Some(1000.0_f32))?;
1323/// let right = Interval::make(Some(500.0_f32), Some(2000.0_f32))?;
1324/// let strict = false;
1325/// assert_eq!(
1326///     satisfy_greater(&left, &right, strict)?,
1327///     Some((
1328///         Interval::make(Some(500.0_f32), Some(1000.0_f32))?,
1329///         Interval::make(Some(500.0_f32), Some(1000.0_f32))?
1330///     ))
1331/// );
1332/// Ok::<(), DataFusionError>(())
1333/// ```
1334///
1335/// NOTE: This function only works with intervals of the same data type.
1336///       Attempting to compare intervals of different data types will lead
1337///       to an error.
1338pub fn satisfy_greater(
1339    left: &Interval,
1340    right: &Interval,
1341    strict: bool,
1342) -> Result<Option<(Interval, Interval)>> {
1343    let lhs_type = left.data_type();
1344    let rhs_type = right.data_type();
1345    assert_eq_or_internal_err!(
1346        lhs_type.clone(),
1347        rhs_type.clone(),
1348        "Intervals must have the same data type, lhs:{}, rhs:{}",
1349        lhs_type,
1350        rhs_type
1351    );
1352
1353    if !left.upper.is_null() && left.upper <= right.lower {
1354        if !strict && left.upper == right.lower {
1355            // Singleton intervals:
1356            return Ok(Some((
1357                Interval::new(left.upper.clone(), left.upper.clone()),
1358                Interval::new(left.upper.clone(), left.upper.clone()),
1359            )));
1360        } else {
1361            // Left-hand side:  <--======----0------------>
1362            // Right-hand side: <------------0--======---->
1363            // No intersection, infeasible to propagate:
1364            return Ok(None);
1365        }
1366    }
1367
1368    // Only the lower bound of left-hand side and the upper bound of the right-hand
1369    // side can change after propagating the greater-than operation.
1370    let new_left_lower = if left.lower.is_null() || left.lower <= right.lower {
1371        if strict {
1372            next_value(right.lower.clone())
1373        } else {
1374            right.lower.clone()
1375        }
1376    } else {
1377        left.lower.clone()
1378    };
1379    // Below code is asymmetric relative to the above if statement, because
1380    // `None` compares less than `Some` in Rust.
1381    let new_right_upper = if right.upper.is_null()
1382        || (!left.upper.is_null() && left.upper <= right.upper)
1383    {
1384        if strict {
1385            prev_value(left.upper.clone())
1386        } else {
1387            left.upper.clone()
1388        }
1389    } else {
1390        right.upper.clone()
1391    };
1392    // No possibility to create an invalid interval:
1393    Ok(Some((
1394        Interval::new(new_left_lower, left.upper.clone()),
1395        Interval::new(right.lower.clone(), new_right_upper),
1396    )))
1397}
1398
1399/// Multiplies two intervals that both contain zero.
1400///
1401/// This function takes in two intervals (`lhs` and `rhs`) as arguments and
1402/// returns their product (whose data type is known to be `dt`). It is
1403/// specifically designed to handle intervals that contain zero within their
1404/// ranges. Returns an error if the multiplication of bounds fails.
1405///
1406/// ```text
1407/// Left-hand side:  <-------=====0=====------->
1408/// Right-hand side: <-------=====0=====------->
1409/// ```
1410///
1411/// **Caution:** This function contains multiple calls to `unwrap()`. Therefore,
1412/// it should be used with caution. Currently, it is used in contexts where the
1413/// `DataType` (`dt`) is validated prior to calling this function.
1414fn mul_helper_multi_zero_inclusive(
1415    dt: &DataType,
1416    lhs: &Interval,
1417    rhs: &Interval,
1418) -> Interval {
1419    if lhs.lower.is_null()
1420        || lhs.upper.is_null()
1421        || rhs.lower.is_null()
1422        || rhs.upper.is_null()
1423    {
1424        return Interval::make_unbounded(dt).unwrap();
1425    }
1426    // Since unbounded cases are handled above, we can safely
1427    // use the utility functions here to eliminate code duplication.
1428    let lower = min_of_bounds(
1429        &mul_bounds::<false>(dt, &lhs.lower, &rhs.upper),
1430        &mul_bounds::<false>(dt, &rhs.lower, &lhs.upper),
1431    );
1432    let upper = max_of_bounds(
1433        &mul_bounds::<true>(dt, &lhs.upper, &rhs.upper),
1434        &mul_bounds::<true>(dt, &lhs.lower, &rhs.lower),
1435    );
1436    // There is no possibility to create an invalid interval.
1437    Interval::new(lower, upper)
1438}
1439
1440/// Multiplies two intervals when only left-hand side interval contains zero.
1441///
1442/// This function takes in two intervals (`lhs` and `rhs`) as arguments and
1443/// returns their product (whose data type is known to be `dt`). This function
1444/// serves as a subroutine that handles the specific case when only `lhs` contains
1445/// zero within its range. The interval not containing zero, i.e. rhs, can lie
1446/// on either side of zero. Returns an error if the multiplication of bounds fails.
1447///
1448/// ``` text
1449/// Left-hand side:  <-------=====0=====------->
1450/// Right-hand side: <--======----0------------>
1451///
1452///                    or
1453///
1454/// Left-hand side:  <-------=====0=====------->
1455/// Right-hand side: <------------0--======---->
1456/// ```
1457///
1458/// **Caution:** This function contains multiple calls to `unwrap()`. Therefore,
1459/// it should be used with caution. Currently, it is used in contexts where the
1460/// `DataType` (`dt`) is validated prior to calling this function.
1461fn mul_helper_single_zero_inclusive(
1462    dt: &DataType,
1463    lhs: &Interval,
1464    rhs: &Interval,
1465    zero: &ScalarValue,
1466) -> Interval {
1467    // With the following interval bounds, there is no possibility to create an invalid interval.
1468    if rhs.upper <= *zero && !rhs.upper.is_null() {
1469        // <-------=====0=====------->
1470        // <--======----0------------>
1471        let lower = mul_bounds::<false>(dt, &lhs.upper, &rhs.lower);
1472        let upper = mul_bounds::<true>(dt, &lhs.lower, &rhs.lower);
1473        Interval::new(lower, upper)
1474    } else {
1475        // <-------=====0=====------->
1476        // <------------0--======---->
1477        let lower = mul_bounds::<false>(dt, &lhs.lower, &rhs.upper);
1478        let upper = mul_bounds::<true>(dt, &lhs.upper, &rhs.upper);
1479        Interval::new(lower, upper)
1480    }
1481}
1482
1483/// Multiplies two intervals when neither of them contains zero.
1484///
1485/// This function takes in two intervals (`lhs` and `rhs`) as arguments and
1486/// returns their product (whose data type is known to be `dt`). It is
1487/// specifically designed to handle intervals that do not contain zero within
1488/// their ranges. Returns an error if the multiplication of bounds fails.
1489///
1490/// ``` text
1491/// Left-hand side:  <--======----0------------>
1492/// Right-hand side: <--======----0------------>
1493///
1494///                    or
1495///
1496/// Left-hand side:  <--======----0------------>
1497/// Right-hand side: <------------0--======---->
1498///
1499///                    or
1500///
1501/// Left-hand side:  <------------0--======---->
1502/// Right-hand side: <--======----0------------>
1503///
1504///                    or
1505///
1506/// Left-hand side:  <------------0--======---->
1507/// Right-hand side: <------------0--======---->
1508/// ```
1509///
1510/// **Caution:** This function contains multiple calls to `unwrap()`. Therefore,
1511/// it should be used with caution. Currently, it is used in contexts where the
1512/// `DataType` (`dt`) is validated prior to calling this function.
1513fn mul_helper_zero_exclusive(
1514    dt: &DataType,
1515    lhs: &Interval,
1516    rhs: &Interval,
1517    zero: &ScalarValue,
1518) -> Interval {
1519    let (lower, upper) = match (
1520        lhs.upper <= *zero && !lhs.upper.is_null(),
1521        rhs.upper <= *zero && !rhs.upper.is_null(),
1522    ) {
1523        // With the following interval bounds, there is no possibility to create an invalid interval.
1524        (true, true) => (
1525            // <--======----0------------>
1526            // <--======----0------------>
1527            mul_bounds::<false>(dt, &lhs.upper, &rhs.upper),
1528            mul_bounds::<true>(dt, &lhs.lower, &rhs.lower),
1529        ),
1530        (true, false) => (
1531            // <--======----0------------>
1532            // <------------0--======---->
1533            mul_bounds::<false>(dt, &lhs.lower, &rhs.upper),
1534            mul_bounds::<true>(dt, &lhs.upper, &rhs.lower),
1535        ),
1536        (false, true) => (
1537            // <------------0--======---->
1538            // <--======----0------------>
1539            mul_bounds::<false>(dt, &rhs.lower, &lhs.upper),
1540            mul_bounds::<true>(dt, &rhs.upper, &lhs.lower),
1541        ),
1542        (false, false) => (
1543            // <------------0--======---->
1544            // <------------0--======---->
1545            mul_bounds::<false>(dt, &lhs.lower, &rhs.lower),
1546            mul_bounds::<true>(dt, &lhs.upper, &rhs.upper),
1547        ),
1548    };
1549    Interval::new(lower, upper)
1550}
1551
1552/// Divides the left-hand side interval by the right-hand side interval when
1553/// the former contains zero.
1554///
1555/// This function takes in two intervals (`lhs` and `rhs`) as arguments and
1556/// returns their quotient (whose data type is known to be `dt`). This function
1557/// serves as a subroutine that handles the specific case when only `lhs` contains
1558/// zero within its range. Returns an error if the division of bounds fails.
1559///
1560/// ``` text
1561/// Left-hand side:  <-------=====0=====------->
1562/// Right-hand side: <--======----0------------>
1563///
1564///                    or
1565///
1566/// Left-hand side:  <-------=====0=====------->
1567/// Right-hand side: <------------0--======---->
1568/// ```
1569///
1570/// **Caution:** This function contains multiple calls to `unwrap()`. Therefore,
1571/// it should be used with caution. Currently, it is used in contexts where the
1572/// `DataType` (`dt`) is validated prior to calling this function.
1573fn div_helper_lhs_zero_inclusive(
1574    dt: &DataType,
1575    lhs: &Interval,
1576    rhs: &Interval,
1577    zero_point: &Interval,
1578) -> Interval {
1579    // With the following interval bounds, there is no possibility to create an invalid interval.
1580    if rhs.upper <= zero_point.lower && !rhs.upper.is_null() {
1581        // <-------=====0=====------->
1582        // <--======----0------------>
1583        let lower = div_bounds::<false>(dt, &lhs.upper, &rhs.upper);
1584        let upper = div_bounds::<true>(dt, &lhs.lower, &rhs.upper);
1585        Interval::new(lower, upper)
1586    } else {
1587        // <-------=====0=====------->
1588        // <------------0--======---->
1589        let lower = div_bounds::<false>(dt, &lhs.lower, &rhs.lower);
1590        let upper = div_bounds::<true>(dt, &lhs.upper, &rhs.lower);
1591        Interval::new(lower, upper)
1592    }
1593}
1594
1595/// Divides the left-hand side interval by the right-hand side interval when
1596/// neither interval contains zero.
1597///
1598/// This function takes in two intervals (`lhs` and `rhs`) as arguments and
1599/// returns their quotient (whose data type is known to be `dt`). It is
1600/// specifically designed to handle intervals that do not contain zero within
1601/// their ranges. Returns an error if the division of bounds fails.
1602///
1603/// ``` text
1604/// Left-hand side:  <--======----0------------>
1605/// Right-hand side: <--======----0------------>
1606///
1607///                    or
1608///
1609/// Left-hand side:  <--======----0------------>
1610/// Right-hand side: <------------0--======---->
1611///
1612///                    or
1613///
1614/// Left-hand side:  <------------0--======---->
1615/// Right-hand side: <--======----0------------>
1616///
1617///                    or
1618///
1619/// Left-hand side:  <------------0--======---->
1620/// Right-hand side: <------------0--======---->
1621/// ```
1622///
1623/// **Caution:** This function contains multiple calls to `unwrap()`. Therefore,
1624/// it should be used with caution. Currently, it is used in contexts where the
1625/// `DataType` (`dt`) is validated prior to calling this function.
1626fn div_helper_zero_exclusive(
1627    dt: &DataType,
1628    lhs: &Interval,
1629    rhs: &Interval,
1630    zero_point: &Interval,
1631) -> Interval {
1632    let (lower, upper) = match (
1633        lhs.upper <= zero_point.lower && !lhs.upper.is_null(),
1634        rhs.upper <= zero_point.lower && !rhs.upper.is_null(),
1635    ) {
1636        // With the following interval bounds, there is no possibility to create an invalid interval.
1637        (true, true) => (
1638            // <--======----0------------>
1639            // <--======----0------------>
1640            div_bounds::<false>(dt, &lhs.upper, &rhs.lower),
1641            div_bounds::<true>(dt, &lhs.lower, &rhs.upper),
1642        ),
1643        (true, false) => (
1644            // <--======----0------------>
1645            // <------------0--======---->
1646            div_bounds::<false>(dt, &lhs.lower, &rhs.lower),
1647            div_bounds::<true>(dt, &lhs.upper, &rhs.upper),
1648        ),
1649        (false, true) => (
1650            // <------------0--======---->
1651            // <--======----0------------>
1652            div_bounds::<false>(dt, &lhs.upper, &rhs.upper),
1653            div_bounds::<true>(dt, &lhs.lower, &rhs.lower),
1654        ),
1655        (false, false) => (
1656            // <------------0--======---->
1657            // <------------0--======---->
1658            div_bounds::<false>(dt, &lhs.lower, &rhs.upper),
1659            div_bounds::<true>(dt, &lhs.upper, &rhs.lower),
1660        ),
1661    };
1662    Interval::new(lower, upper)
1663}
1664
1665/// This function computes the selectivity of an operation by computing the
1666/// cardinality ratio of the given input/output intervals. If this can not be
1667/// calculated for some reason, it returns `1.0` meaning fully selective (no
1668/// filtering).
1669pub fn cardinality_ratio(initial_interval: &Interval, final_interval: &Interval) -> f64 {
1670    match (final_interval.cardinality(), initial_interval.cardinality()) {
1671        (Some(final_interval), Some(initial_interval)) => {
1672            (final_interval as f64) / (initial_interval as f64)
1673        }
1674        _ => 1.0,
1675    }
1676}
1677
1678/// Cast scalar value to the given data type using an arrow kernel.
1679fn cast_scalar_value(
1680    value: &ScalarValue,
1681    data_type: &DataType,
1682    cast_options: &CastOptions,
1683) -> Result<ScalarValue> {
1684    let cast_array = cast_with_options(&value.to_array()?, data_type, cast_options)?;
1685    ScalarValue::try_from_array(&cast_array, 0)
1686}
1687
1688/// An [Interval] that also tracks null status using a boolean interval.
1689///
1690/// This represents values that may be in a particular range or be null.
1691///
1692/// # Examples
1693///
1694/// ```
1695/// use arrow::datatypes::DataType;
1696/// use datafusion_common::ScalarValue;
1697/// use datafusion_expr_common::interval_arithmetic::Interval;
1698/// use datafusion_expr_common::interval_arithmetic::NullableInterval;
1699///
1700/// // [1, 2) U {NULL}
1701/// let maybe_null = NullableInterval::MaybeNull {
1702///     values: Interval::try_new(
1703///         ScalarValue::Int32(Some(1)),
1704///         ScalarValue::Int32(Some(2)),
1705///     )
1706///     .unwrap(),
1707/// };
1708///
1709/// // (0, ∞)
1710/// let not_null = NullableInterval::NotNull {
1711///     values: Interval::try_new(ScalarValue::Int32(Some(0)), ScalarValue::Int32(None))
1712///         .unwrap(),
1713/// };
1714///
1715/// // {NULL}
1716/// let null_interval = NullableInterval::Null {
1717///     datatype: DataType::Int32,
1718/// };
1719///
1720/// // {4}
1721/// let single_value = NullableInterval::from(ScalarValue::Int32(Some(4)));
1722/// ```
1723#[derive(Debug, Clone, PartialEq, Eq)]
1724pub enum NullableInterval {
1725    /// The value is always null. This is typed so it can be used in physical
1726    /// expressions, which don't do type coercion.
1727    Null { datatype: DataType },
1728    /// The value may or may not be null. If it is non-null, its is within the
1729    /// specified range.
1730    MaybeNull { values: Interval },
1731    /// The value is definitely not null, and is within the specified range.
1732    NotNull { values: Interval },
1733}
1734
1735impl Display for NullableInterval {
1736    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1737        match self {
1738            Self::Null { .. } => write!(f, "NullableInterval: {{NULL}}"),
1739            Self::MaybeNull { values } => {
1740                write!(f, "NullableInterval: {values} U {{NULL}}")
1741            }
1742            Self::NotNull { values } => write!(f, "NullableInterval: {values}"),
1743        }
1744    }
1745}
1746
1747impl From<ScalarValue> for NullableInterval {
1748    /// Create an interval that represents a single value.
1749    fn from(value: ScalarValue) -> Self {
1750        if value.is_null() {
1751            Self::Null {
1752                datatype: value.data_type(),
1753            }
1754        } else {
1755            Self::NotNull {
1756                values: Interval {
1757                    lower: value.clone(),
1758                    upper: value,
1759                },
1760            }
1761        }
1762    }
1763}
1764
1765impl NullableInterval {
1766    /// An interval containing only the 'false' truth value.
1767    /// This interval is semantically equivalent to [Interval::FALSE].
1768    pub const FALSE: Self = NullableInterval::NotNull {
1769        values: Interval::FALSE,
1770    };
1771
1772    /// An interval containing only the 'true' truth value.
1773    /// This interval is semantically equivalent to [Interval::TRUE].
1774    pub const TRUE: Self = NullableInterval::NotNull {
1775        values: Interval::TRUE,
1776    };
1777
1778    /// An interval containing only the 'unknown' truth value.
1779    pub const UNKNOWN: Self = NullableInterval::Null {
1780        datatype: DataType::Boolean,
1781    };
1782
1783    /// An interval containing both the 'true', and 'false' truth values.
1784    /// This interval is semantically equivalent to [Interval::TRUE_OR_FALSE].
1785    pub const TRUE_OR_FALSE: Self = NullableInterval::NotNull {
1786        values: Interval::TRUE_OR_FALSE,
1787    };
1788
1789    /// An interval containing both the 'true' and 'unknown' truth values.
1790    pub const TRUE_OR_UNKNOWN: Self = NullableInterval::MaybeNull {
1791        values: Interval::TRUE,
1792    };
1793
1794    /// An interval containing both the 'false' and 'unknown' truth values.
1795    pub const FALSE_OR_UNKNOWN: Self = NullableInterval::MaybeNull {
1796        values: Interval::FALSE,
1797    };
1798
1799    /// An interval that contains all possible truth values: 'true', 'false' and 'unknown'.
1800    pub const ANY_TRUTH_VALUE: Self = NullableInterval::MaybeNull {
1801        values: Interval::TRUE_OR_FALSE,
1802    };
1803
1804    /// Get the values interval, or None if this interval is definitely null.
1805    pub fn values(&self) -> Option<&Interval> {
1806        match self {
1807            Self::Null { .. } => None,
1808            Self::MaybeNull { values } | Self::NotNull { values } => Some(values),
1809        }
1810    }
1811
1812    /// Get the data type
1813    pub fn data_type(&self) -> DataType {
1814        match self {
1815            Self::Null { datatype } => datatype.clone(),
1816            Self::MaybeNull { values } | Self::NotNull { values } => values.data_type(),
1817        }
1818    }
1819
1820    /// Return true if the value is definitely true (and not null).
1821    pub fn is_certainly_true(&self) -> bool {
1822        self == &Self::TRUE
1823    }
1824
1825    /// Returns the set of possible values after applying the `is true` test on all
1826    /// values in this set.
1827    /// The resulting set can only contain 'TRUE' and/or 'FALSE', never 'UNKNOWN'.
1828    pub fn is_true(&self) -> Result<Self> {
1829        let (t, f, u) = self.is_true_false_unknown()?;
1830
1831        match (t, f, u) {
1832            (true, false, false) => Ok(Self::TRUE),
1833            (true, _, _) => Ok(Self::TRUE_OR_FALSE),
1834            (false, _, _) => Ok(Self::FALSE),
1835        }
1836    }
1837
1838    /// Return true if the value is definitely false (and not null).
1839    pub fn is_certainly_false(&self) -> bool {
1840        self == &Self::FALSE
1841    }
1842
1843    /// Returns the set of possible values after applying the `is false` test on all
1844    /// values in this set.
1845    /// The resulting set can only contain 'TRUE' and/or 'FALSE', never 'UNKNOWN'.
1846    pub fn is_false(&self) -> Result<Self> {
1847        let (t, f, u) = self.is_true_false_unknown()?;
1848
1849        match (t, f, u) {
1850            (false, true, false) => Ok(Self::TRUE),
1851            (_, true, _) => Ok(Self::TRUE_OR_FALSE),
1852            (_, false, _) => Ok(Self::FALSE),
1853        }
1854    }
1855
1856    /// Return true if the value is definitely null (and not true or false).
1857    pub fn is_certainly_unknown(&self) -> bool {
1858        self == &Self::UNKNOWN
1859    }
1860
1861    /// Returns the set of possible values after applying the `is unknown` test on all
1862    /// values in this set.
1863    /// The resulting set can only contain 'TRUE' and/or 'FALSE', never 'UNKNOWN'.
1864    pub fn is_unknown(&self) -> Result<Self> {
1865        let (t, f, u) = self.is_true_false_unknown()?;
1866
1867        match (t, f, u) {
1868            (false, false, true) => Ok(Self::TRUE),
1869            (_, _, true) => Ok(Self::TRUE_OR_FALSE),
1870            (_, _, false) => Ok(Self::FALSE),
1871        }
1872    }
1873
1874    /// Returns a tuple of booleans indicating if this interval contains the
1875    /// true, false, and unknown truth values respectively.
1876    fn is_true_false_unknown(&self) -> Result<(bool, bool, bool), DataFusionError> {
1877        Ok(match self {
1878            NullableInterval::Null { .. } => (false, false, true),
1879            NullableInterval::MaybeNull { values } => (
1880                values.contains_value(ScalarValue::Boolean(Some(true)))?,
1881                values.contains_value(ScalarValue::Boolean(Some(false)))?,
1882                true,
1883            ),
1884            NullableInterval::NotNull { values } => (
1885                values.contains_value(ScalarValue::Boolean(Some(true)))?,
1886                values.contains_value(ScalarValue::Boolean(Some(false)))?,
1887                false,
1888            ),
1889        })
1890    }
1891
1892    /// Returns an interval representing the set of possible values after applying
1893    /// SQL three-valued logical NOT on possible value in this interval.
1894    ///
1895    /// This method uses the following truth table.
1896    ///
1897    /// ```text
1898    ///  A  | ¬A
1899    /// ----|----
1900    ///  F  |  T
1901    ///  U  |  U
1902    ///  T  |  F
1903    /// ```
1904    pub fn not(&self) -> Result<Self> {
1905        match self {
1906            Self::Null { datatype } => {
1907                assert_eq_or_internal_err!(
1908                    datatype,
1909                    &DataType::Boolean,
1910                    "Cannot apply logical negation to a non-boolean interval"
1911                );
1912                Ok(Self::UNKNOWN)
1913            }
1914            Self::MaybeNull { values } => Ok(Self::MaybeNull {
1915                values: values.not()?,
1916            }),
1917            Self::NotNull { values } => Ok(Self::NotNull {
1918                values: values.not()?,
1919            }),
1920        }
1921    }
1922
1923    /// Returns an interval representing the set of possible values after applying SQL
1924    /// three-valued logical AND on each combination of possible values from `self` and `other`.
1925    ///
1926    /// This method uses the following truth table.
1927    ///
1928    /// ```text
1929    ///       │   B
1930    /// A ∧ B ├──────
1931    ///       │ F U T
1932    /// ──┬───┼──────
1933    ///   │ F │ F F F
1934    /// A │ U │ F U U
1935    ///   │ T │ F U T
1936    /// ```
1937    pub fn and<T: Borrow<Self>>(&self, rhs: T) -> Result<Self> {
1938        if self == &Self::FALSE || rhs.borrow() == &Self::FALSE {
1939            return Ok(Self::FALSE);
1940        }
1941
1942        match (self.values(), rhs.borrow().values()) {
1943            (Some(l), Some(r)) => {
1944                let values = l.and(r)?;
1945                match (self, rhs.borrow()) {
1946                    (Self::NotNull { .. }, Self::NotNull { .. }) => {
1947                        Ok(Self::NotNull { values })
1948                    }
1949                    _ => Ok(Self::MaybeNull { values }),
1950                }
1951            }
1952            (Some(v), None) | (None, Some(v)) => {
1953                if v.contains_value(ScalarValue::Boolean(Some(false)))? {
1954                    Ok(Self::FALSE_OR_UNKNOWN)
1955                } else {
1956                    Ok(Self::UNKNOWN)
1957                }
1958            }
1959            _ => Ok(Self::UNKNOWN),
1960        }
1961    }
1962
1963    /// Returns an interval representing the set of possible values after applying SQL three-valued
1964    /// logical OR on each combination of possible values from `self` and `other`.
1965    ///
1966    /// This method uses the following truth table.
1967    ///
1968    /// ```text
1969    ///       │   B
1970    /// A ∨ B ├──────
1971    ///       │ F U T
1972    /// ──┬───┼──────
1973    ///   │ F │ F U T
1974    /// A │ U │ U U T
1975    ///   │ T │ T T T
1976    /// ```
1977    pub fn or<T: Borrow<Self>>(&self, rhs: T) -> Result<Self> {
1978        if self == &Self::TRUE || rhs.borrow() == &Self::TRUE {
1979            return Ok(Self::TRUE);
1980        }
1981
1982        match (self.values(), rhs.borrow().values()) {
1983            (Some(l), Some(r)) => {
1984                let values = l.or(r)?;
1985                match (self, rhs.borrow()) {
1986                    (Self::NotNull { .. }, Self::NotNull { .. }) => {
1987                        Ok(Self::NotNull { values })
1988                    }
1989                    _ => Ok(Self::MaybeNull { values }),
1990                }
1991            }
1992            (Some(v), None) | (None, Some(v)) => {
1993                if v.contains_value(ScalarValue::Boolean(Some(true)))? {
1994                    Ok(Self::TRUE_OR_UNKNOWN)
1995                } else {
1996                    Ok(Self::UNKNOWN)
1997                }
1998            }
1999            _ => Ok(Self::UNKNOWN),
2000        }
2001    }
2002
2003    /// Apply the given operator to this interval and the given interval.
2004    ///
2005    /// # Examples
2006    ///
2007    /// ```
2008    /// use datafusion_common::ScalarValue;
2009    /// use datafusion_expr_common::interval_arithmetic::Interval;
2010    /// use datafusion_expr_common::interval_arithmetic::NullableInterval;
2011    /// use datafusion_expr_common::operator::Operator;
2012    ///
2013    /// // 4 > 3 -> true
2014    /// let lhs = NullableInterval::from(ScalarValue::Int32(Some(4)));
2015    /// let rhs = NullableInterval::from(ScalarValue::Int32(Some(3)));
2016    /// let result = lhs.apply_operator(&Operator::Gt, &rhs).unwrap();
2017    /// assert_eq!(
2018    ///     result,
2019    ///     NullableInterval::from(ScalarValue::Boolean(Some(true)))
2020    /// );
2021    ///
2022    /// // [1, 3) > NULL -> NULL
2023    /// let lhs = NullableInterval::NotNull {
2024    ///     values: Interval::try_new(
2025    ///         ScalarValue::Int32(Some(1)),
2026    ///         ScalarValue::Int32(Some(3)),
2027    ///     )
2028    ///     .unwrap(),
2029    /// };
2030    /// let rhs = NullableInterval::from(ScalarValue::Int32(None));
2031    /// let result = lhs.apply_operator(&Operator::Gt, &rhs).unwrap();
2032    /// assert_eq!(result.single_value(), Some(ScalarValue::Boolean(None)));
2033    ///
2034    /// // [1, 3] > [2, 4] -> [false, true]
2035    /// let lhs = NullableInterval::NotNull {
2036    ///     values: Interval::try_new(
2037    ///         ScalarValue::Int32(Some(1)),
2038    ///         ScalarValue::Int32(Some(3)),
2039    ///     )
2040    ///     .unwrap(),
2041    /// };
2042    /// let rhs = NullableInterval::NotNull {
2043    ///     values: Interval::try_new(
2044    ///         ScalarValue::Int32(Some(2)),
2045    ///         ScalarValue::Int32(Some(4)),
2046    ///     )
2047    ///     .unwrap(),
2048    /// };
2049    /// let result = lhs.apply_operator(&Operator::Gt, &rhs).unwrap();
2050    /// // Both inputs are valid (non-null), so result must be non-null
2051    /// assert_eq!(
2052    ///     result,
2053    ///     NullableInterval::NotNull {
2054    ///         // Uncertain whether inequality is true or false
2055    ///         values: Interval::TRUE_OR_FALSE,
2056    ///     }
2057    /// );
2058    /// ```
2059    pub fn apply_operator(&self, op: &Operator, rhs: &Self) -> Result<Self> {
2060        match op {
2061            Operator::IsDistinctFrom => {
2062                let values = match (self, rhs) {
2063                    // NULL is distinct from NULL -> False
2064                    (Self::Null { .. }, Self::Null { .. }) => Interval::FALSE,
2065                    // x is distinct from y -> x != y,
2066                    // if at least one of them is never null.
2067                    (Self::NotNull { .. }, _) | (_, Self::NotNull { .. }) => {
2068                        let lhs_values = self.values();
2069                        let rhs_values = rhs.values();
2070                        match (lhs_values, rhs_values) {
2071                            (Some(lhs_values), Some(rhs_values)) => {
2072                                lhs_values.equal(rhs_values)?.not()?
2073                            }
2074                            (Some(_), None) | (None, Some(_)) => Interval::TRUE,
2075                            (None, None) => unreachable!("Null case handled above"),
2076                        }
2077                    }
2078                    _ => Interval::TRUE_OR_FALSE,
2079                };
2080                // IsDistinctFrom never returns null.
2081                Ok(Self::NotNull { values })
2082            }
2083            Operator::IsNotDistinctFrom => self
2084                .apply_operator(&Operator::IsDistinctFrom, rhs)
2085                .map(|i| i.not())?,
2086            Operator::And => self.and(rhs),
2087            Operator::Or => self.or(rhs),
2088            _ => {
2089                if let (Some(left_values), Some(right_values)) =
2090                    (self.values(), rhs.values())
2091                {
2092                    let values = apply_operator(op, left_values, right_values)?;
2093                    match (self, rhs) {
2094                        (Self::NotNull { .. }, Self::NotNull { .. }) => {
2095                            Ok(Self::NotNull { values })
2096                        }
2097                        _ => Ok(Self::MaybeNull { values }),
2098                    }
2099                } else if op.supports_propagation() {
2100                    Ok(Self::Null {
2101                        datatype: DataType::Boolean,
2102                    })
2103                } else {
2104                    Ok(Self::Null {
2105                        datatype: self.data_type(),
2106                    })
2107                }
2108            }
2109        }
2110    }
2111
2112    /// Decide if this interval is a superset of, overlaps with, or
2113    /// disjoint with `other` by returning `[true, true]`, `[false, true]` or
2114    /// `[false, false]` respectively.
2115    ///
2116    /// NOTE: This function only works with intervals of the same data type.
2117    ///       Attempting to compare intervals of different data types will lead
2118    ///       to an error.
2119    pub fn contains<T: Borrow<Self>>(&self, other: T) -> Result<Self> {
2120        let rhs = other.borrow();
2121        if let (Some(left_values), Some(right_values)) = (self.values(), rhs.values()) {
2122            left_values
2123                .contains(right_values)
2124                .map(|values| match (self, rhs) {
2125                    (Self::NotNull { .. }, Self::NotNull { .. }) => {
2126                        Self::NotNull { values }
2127                    }
2128                    _ => Self::MaybeNull { values },
2129                })
2130        } else {
2131            Ok(Self::Null {
2132                datatype: DataType::Boolean,
2133            })
2134        }
2135    }
2136
2137    /// Determines if this interval contains a [`ScalarValue`] or not.
2138    pub fn contains_value<T: Borrow<ScalarValue>>(&self, value: T) -> Result<bool> {
2139        match value.borrow() {
2140            ScalarValue::Null => match self {
2141                NullableInterval::Null { .. } | NullableInterval::MaybeNull { .. } => {
2142                    Ok(true)
2143                }
2144                NullableInterval::NotNull { .. } => Ok(false),
2145            },
2146            s if s.is_null() => match self {
2147                NullableInterval::Null { datatype } => Ok(datatype.eq(&s.data_type())),
2148                NullableInterval::MaybeNull { values } => {
2149                    Ok(values.data_type().eq(&s.data_type()))
2150                }
2151                NullableInterval::NotNull { .. } => Ok(false),
2152            },
2153            s => match self {
2154                NullableInterval::Null { .. } => Ok(false),
2155                NullableInterval::MaybeNull { values }
2156                | NullableInterval::NotNull { values } => values.contains_value(s),
2157            },
2158        }
2159    }
2160
2161    /// If the interval has collapsed to a single value, return that value.
2162    /// Otherwise, returns `None`.
2163    ///
2164    /// # Examples
2165    ///
2166    /// ```
2167    /// use datafusion_common::ScalarValue;
2168    /// use datafusion_expr_common::interval_arithmetic::Interval;
2169    /// use datafusion_expr_common::interval_arithmetic::NullableInterval;
2170    ///
2171    /// let interval = NullableInterval::from(ScalarValue::Int32(Some(4)));
2172    /// assert_eq!(interval.single_value(), Some(ScalarValue::Int32(Some(4))));
2173    ///
2174    /// let interval = NullableInterval::from(ScalarValue::Int32(None));
2175    /// assert_eq!(interval.single_value(), Some(ScalarValue::Int32(None)));
2176    ///
2177    /// let interval = NullableInterval::MaybeNull {
2178    ///     values: Interval::try_new(
2179    ///         ScalarValue::Int32(Some(1)),
2180    ///         ScalarValue::Int32(Some(4)),
2181    ///     )
2182    ///     .unwrap(),
2183    /// };
2184    /// assert_eq!(interval.single_value(), None);
2185    /// ```
2186    pub fn single_value(&self) -> Option<ScalarValue> {
2187        match self {
2188            Self::Null { datatype } => {
2189                Some(ScalarValue::try_from(datatype).unwrap_or(ScalarValue::Null))
2190            }
2191            Self::MaybeNull { values } | Self::NotNull { values }
2192                if values.lower == values.upper && !values.lower.is_null() =>
2193            {
2194                Some(values.lower.clone())
2195            }
2196            _ => None,
2197        }
2198    }
2199}
2200
2201#[cfg(test)]
2202mod tests {
2203    use crate::{
2204        interval_arithmetic::{
2205            Interval, handle_overflow, next_value, prev_value, satisfy_greater,
2206        },
2207        operator::Operator,
2208    };
2209
2210    use crate::interval_arithmetic::NullableInterval;
2211    use arrow::datatypes::DataType;
2212    use datafusion_common::rounding::{next_down, next_up};
2213    use datafusion_common::{Result, ScalarValue};
2214
2215    #[test]
2216    fn test_next_prev_value() -> Result<()> {
2217        let zeros = vec![
2218            ScalarValue::new_zero(&DataType::UInt8)?,
2219            ScalarValue::new_zero(&DataType::UInt16)?,
2220            ScalarValue::new_zero(&DataType::UInt32)?,
2221            ScalarValue::new_zero(&DataType::UInt64)?,
2222            ScalarValue::new_zero(&DataType::Int8)?,
2223            ScalarValue::new_zero(&DataType::Int16)?,
2224            ScalarValue::new_zero(&DataType::Int32)?,
2225            ScalarValue::new_zero(&DataType::Int64)?,
2226        ];
2227        let ones = vec![
2228            ScalarValue::new_one(&DataType::UInt8)?,
2229            ScalarValue::new_one(&DataType::UInt16)?,
2230            ScalarValue::new_one(&DataType::UInt32)?,
2231            ScalarValue::new_one(&DataType::UInt64)?,
2232            ScalarValue::new_one(&DataType::Int8)?,
2233            ScalarValue::new_one(&DataType::Int16)?,
2234            ScalarValue::new_one(&DataType::Int32)?,
2235            ScalarValue::new_one(&DataType::Int64)?,
2236        ];
2237        zeros.into_iter().zip(ones).for_each(|(z, o)| {
2238            assert_eq!(next_value(z.clone()), o);
2239            assert_eq!(prev_value(o), z);
2240        });
2241
2242        let values = vec![
2243            ScalarValue::new_zero(&DataType::Float32)?,
2244            ScalarValue::new_zero(&DataType::Float64)?,
2245        ];
2246        let eps = vec![
2247            ScalarValue::Float32(Some(1e-6)),
2248            ScalarValue::Float64(Some(1e-6)),
2249        ];
2250        values.into_iter().zip(eps).for_each(|(value, eps)| {
2251            assert!(
2252                next_value(value.clone())
2253                    .sub(value.clone())
2254                    .unwrap()
2255                    .lt(&eps)
2256            );
2257            assert!(value.sub(prev_value(value.clone())).unwrap().lt(&eps));
2258            assert_ne!(next_value(value.clone()), value);
2259            assert_ne!(prev_value(value.clone()), value);
2260        });
2261
2262        let min_max = vec![
2263            (
2264                ScalarValue::UInt64(Some(u64::MIN)),
2265                ScalarValue::UInt64(Some(u64::MAX)),
2266            ),
2267            (
2268                ScalarValue::Int8(Some(i8::MIN)),
2269                ScalarValue::Int8(Some(i8::MAX)),
2270            ),
2271            (
2272                ScalarValue::Float32(Some(f32::MIN)),
2273                ScalarValue::Float32(Some(f32::MAX)),
2274            ),
2275            (
2276                ScalarValue::Float64(Some(f64::MIN)),
2277                ScalarValue::Float64(Some(f64::MAX)),
2278            ),
2279        ];
2280        let inf = vec![
2281            ScalarValue::UInt64(None),
2282            ScalarValue::Int8(None),
2283            ScalarValue::Float32(None),
2284            ScalarValue::Float64(None),
2285        ];
2286        min_max.into_iter().zip(inf).for_each(|((min, max), inf)| {
2287            assert_eq!(next_value(max.clone()), inf);
2288            assert_ne!(prev_value(max.clone()), max);
2289            assert_ne!(prev_value(max), inf);
2290
2291            assert_eq!(prev_value(min.clone()), inf);
2292            assert_ne!(next_value(min.clone()), min);
2293            assert_ne!(next_value(min), inf);
2294
2295            assert_eq!(next_value(inf.clone()), inf);
2296            assert_eq!(prev_value(inf.clone()), inf);
2297        });
2298
2299        Ok(())
2300    }
2301
2302    #[test]
2303    fn test_new_interval() -> Result<()> {
2304        use ScalarValue::*;
2305
2306        let cases = vec![
2307            (
2308                (Boolean(None), Boolean(Some(false))),
2309                Boolean(Some(false)),
2310                Boolean(Some(false)),
2311            ),
2312            (
2313                (Boolean(Some(false)), Boolean(None)),
2314                Boolean(Some(false)),
2315                Boolean(Some(true)),
2316            ),
2317            (
2318                (Boolean(Some(false)), Boolean(Some(true))),
2319                Boolean(Some(false)),
2320                Boolean(Some(true)),
2321            ),
2322            (
2323                (UInt16(Some(u16::MAX)), UInt16(None)),
2324                UInt16(Some(u16::MAX)),
2325                UInt16(None),
2326            ),
2327            (
2328                (Int16(None), Int16(Some(-1000))),
2329                Int16(None),
2330                Int16(Some(-1000)),
2331            ),
2332            (
2333                (Float32(Some(f32::MAX)), Float32(Some(f32::MAX))),
2334                Float32(Some(f32::MAX)),
2335                Float32(Some(f32::MAX)),
2336            ),
2337            (
2338                (Float32(Some(f32::NAN)), Float32(Some(f32::MIN))),
2339                Float32(None),
2340                Float32(Some(f32::MIN)),
2341            ),
2342            (
2343                (
2344                    Float64(Some(f64::NEG_INFINITY)),
2345                    Float64(Some(f64::INFINITY)),
2346                ),
2347                Float64(None),
2348                Float64(None),
2349            ),
2350        ];
2351        for (inputs, lower, upper) in cases {
2352            let result = Interval::try_new(inputs.0, inputs.1)?;
2353            assert_eq!(result.clone().lower(), &lower);
2354            assert_eq!(result.upper(), &upper);
2355        }
2356
2357        let invalid_intervals = vec![
2358            (Float32(Some(f32::INFINITY)), Float32(Some(100_f32))),
2359            (Float64(Some(0_f64)), Float64(Some(f64::NEG_INFINITY))),
2360            (Boolean(Some(true)), Boolean(Some(false))),
2361            (Int32(Some(1000)), Int32(Some(-2000))),
2362            (UInt64(Some(1)), UInt64(Some(0))),
2363        ];
2364        for (lower, upper) in invalid_intervals {
2365            Interval::try_new(lower, upper).expect_err(
2366                "Given parameters should have given an invalid interval error",
2367            );
2368        }
2369
2370        Ok(())
2371    }
2372
2373    #[test]
2374    fn test_make_unbounded() -> Result<()> {
2375        use ScalarValue::*;
2376
2377        let unbounded_cases = vec![
2378            (DataType::Boolean, Boolean(Some(false)), Boolean(Some(true))),
2379            (DataType::UInt8, UInt8(Some(0)), UInt8(None)),
2380            (DataType::UInt16, UInt16(Some(0)), UInt16(None)),
2381            (DataType::UInt32, UInt32(Some(0)), UInt32(None)),
2382            (DataType::UInt64, UInt64(Some(0)), UInt64(None)),
2383            (DataType::Int8, Int8(None), Int8(None)),
2384            (DataType::Int16, Int16(None), Int16(None)),
2385            (DataType::Int32, Int32(None), Int32(None)),
2386            (DataType::Int64, Int64(None), Int64(None)),
2387            (DataType::Float32, Float32(None), Float32(None)),
2388            (DataType::Float64, Float64(None), Float64(None)),
2389        ];
2390        for (dt, lower, upper) in unbounded_cases {
2391            let inf = Interval::make_unbounded(&dt)?;
2392            assert_eq!(inf.clone().lower(), &lower);
2393            assert_eq!(inf.upper(), &upper);
2394        }
2395
2396        Ok(())
2397    }
2398
2399    #[test]
2400    fn gt_lt_test() -> Result<()> {
2401        let exactly_gt_cases = vec![
2402            (
2403                Interval::make(Some(1000_i64), None)?,
2404                Interval::make(None, Some(999_i64))?,
2405            ),
2406            (
2407                Interval::make(Some(1000_i64), Some(1000_i64))?,
2408                Interval::make(None, Some(999_i64))?,
2409            ),
2410            (
2411                Interval::make(Some(501_i64), Some(1000_i64))?,
2412                Interval::make(Some(500_i64), Some(500_i64))?,
2413            ),
2414            (
2415                Interval::make(Some(-1000_i64), Some(1000_i64))?,
2416                Interval::make(None, Some(-1500_i64))?,
2417            ),
2418            (
2419                Interval::try_new(
2420                    next_value(ScalarValue::Float32(Some(0.0))),
2421                    next_value(ScalarValue::Float32(Some(0.0))),
2422                )?,
2423                Interval::make(Some(0.0_f32), Some(0.0_f32))?,
2424            ),
2425            (
2426                Interval::make(Some(-1.0_f32), Some(-1.0_f32))?,
2427                Interval::try_new(
2428                    prev_value(ScalarValue::Float32(Some(-1.0))),
2429                    prev_value(ScalarValue::Float32(Some(-1.0))),
2430                )?,
2431            ),
2432        ];
2433        for (first, second) in exactly_gt_cases {
2434            assert_eq!(first.gt(second.clone())?, Interval::TRUE);
2435            assert_eq!(second.lt(first)?, Interval::TRUE);
2436        }
2437
2438        let possibly_gt_cases = vec![
2439            (
2440                Interval::make(Some(1000_i64), Some(2000_i64))?,
2441                Interval::make(Some(1000_i64), Some(1000_i64))?,
2442            ),
2443            (
2444                Interval::make(Some(500_i64), Some(1000_i64))?,
2445                Interval::make(Some(500_i64), Some(1000_i64))?,
2446            ),
2447            (
2448                Interval::make(Some(1000_i64), None)?,
2449                Interval::make(Some(1000_i64), None)?,
2450            ),
2451            (
2452                Interval::make::<i64>(None, None)?,
2453                Interval::make::<i64>(None, None)?,
2454            ),
2455            (
2456                Interval::try_new(
2457                    ScalarValue::Float32(Some(0.0_f32)),
2458                    next_value(ScalarValue::Float32(Some(0.0_f32))),
2459                )?,
2460                Interval::make(Some(0.0_f32), Some(0.0_f32))?,
2461            ),
2462            (
2463                Interval::make(Some(-1.0_f32), Some(-1.0_f32))?,
2464                Interval::try_new(
2465                    prev_value(ScalarValue::Float32(Some(-1.0_f32))),
2466                    ScalarValue::Float32(Some(-1.0_f32)),
2467                )?,
2468            ),
2469        ];
2470        for (first, second) in possibly_gt_cases {
2471            assert_eq!(first.gt(second.clone())?, Interval::TRUE_OR_FALSE);
2472            assert_eq!(second.lt(first)?, Interval::TRUE_OR_FALSE);
2473        }
2474
2475        let not_gt_cases = vec![
2476            (
2477                Interval::make(Some(1000_i64), Some(1000_i64))?,
2478                Interval::make(Some(1000_i64), Some(1000_i64))?,
2479            ),
2480            (
2481                Interval::make(Some(500_i64), Some(1000_i64))?,
2482                Interval::make(Some(1000_i64), None)?,
2483            ),
2484            (
2485                Interval::make(None, Some(1000_i64))?,
2486                Interval::make(Some(1000_i64), Some(1500_i64))?,
2487            ),
2488            (
2489                Interval::make(Some(0_u8), Some(0_u8))?,
2490                Interval::make::<u8>(None, None)?,
2491            ),
2492            (
2493                Interval::try_new(
2494                    prev_value(ScalarValue::Float32(Some(0.0_f32))),
2495                    ScalarValue::Float32(Some(0.0_f32)),
2496                )?,
2497                Interval::make(Some(0.0_f32), Some(0.0_f32))?,
2498            ),
2499            (
2500                Interval::make(Some(-1.0_f32), Some(-1.0_f32))?,
2501                Interval::try_new(
2502                    ScalarValue::Float32(Some(-1.0_f32)),
2503                    next_value(ScalarValue::Float32(Some(-1.0_f32))),
2504                )?,
2505            ),
2506        ];
2507        for (first, second) in not_gt_cases {
2508            assert_eq!(first.gt(second.clone())?, Interval::FALSE);
2509            assert_eq!(second.lt(first)?, Interval::FALSE);
2510        }
2511
2512        Ok(())
2513    }
2514
2515    #[test]
2516    fn gteq_lteq_test() -> Result<()> {
2517        let exactly_gteq_cases = vec![
2518            (
2519                Interval::make(Some(1000_i64), None)?,
2520                Interval::make(None, Some(1000_i64))?,
2521            ),
2522            (
2523                Interval::make(Some(1000_i64), Some(1000_i64))?,
2524                Interval::make(None, Some(1000_i64))?,
2525            ),
2526            (
2527                Interval::make(Some(500_i64), Some(1000_i64))?,
2528                Interval::make(Some(500_i64), Some(500_i64))?,
2529            ),
2530            (
2531                Interval::make(Some(-1000_i64), Some(1000_i64))?,
2532                Interval::make(None, Some(-1500_i64))?,
2533            ),
2534            (
2535                Interval::make::<u64>(None, None)?,
2536                Interval::make(Some(0_u64), Some(0_u64))?,
2537            ),
2538            (
2539                Interval::make(Some(0.0_f32), Some(0.0_f32))?,
2540                Interval::make(Some(0.0_f32), Some(0.0_f32))?,
2541            ),
2542            (
2543                Interval::try_new(
2544                    ScalarValue::Float32(Some(-1.0)),
2545                    next_value(ScalarValue::Float32(Some(-1.0))),
2546                )?,
2547                Interval::try_new(
2548                    prev_value(ScalarValue::Float32(Some(-1.0))),
2549                    ScalarValue::Float32(Some(-1.0)),
2550                )?,
2551            ),
2552        ];
2553        for (first, second) in exactly_gteq_cases {
2554            assert_eq!(first.gt_eq(second.clone())?, Interval::TRUE);
2555            assert_eq!(second.lt_eq(first)?, Interval::TRUE);
2556        }
2557
2558        let possibly_gteq_cases = vec![
2559            (
2560                Interval::make(Some(999_i64), Some(2000_i64))?,
2561                Interval::make(Some(1000_i64), Some(1000_i64))?,
2562            ),
2563            (
2564                Interval::make(Some(500_i64), Some(1000_i64))?,
2565                Interval::make(Some(500_i64), Some(1001_i64))?,
2566            ),
2567            (
2568                Interval::make(Some(0_i64), None)?,
2569                Interval::make(Some(1000_i64), None)?,
2570            ),
2571            (
2572                Interval::make::<i64>(None, None)?,
2573                Interval::make::<i64>(None, None)?,
2574            ),
2575            (
2576                Interval::try_new(
2577                    prev_value(ScalarValue::Float32(Some(0.0))),
2578                    ScalarValue::Float32(Some(0.0)),
2579                )?,
2580                Interval::make(Some(0.0_f32), Some(0.0_f32))?,
2581            ),
2582            (
2583                Interval::make(Some(-1.0_f32), Some(-1.0_f32))?,
2584                Interval::try_new(
2585                    prev_value(ScalarValue::Float32(Some(-1.0_f32))),
2586                    next_value(ScalarValue::Float32(Some(-1.0_f32))),
2587                )?,
2588            ),
2589        ];
2590        for (first, second) in possibly_gteq_cases {
2591            assert_eq!(first.gt_eq(second.clone())?, Interval::TRUE_OR_FALSE);
2592            assert_eq!(second.lt_eq(first)?, Interval::TRUE_OR_FALSE);
2593        }
2594
2595        let not_gteq_cases = vec![
2596            (
2597                Interval::make(Some(1000_i64), Some(1000_i64))?,
2598                Interval::make(Some(2000_i64), Some(2000_i64))?,
2599            ),
2600            (
2601                Interval::make(Some(500_i64), Some(999_i64))?,
2602                Interval::make(Some(1000_i64), None)?,
2603            ),
2604            (
2605                Interval::make(None, Some(1000_i64))?,
2606                Interval::make(Some(1001_i64), Some(1500_i64))?,
2607            ),
2608            (
2609                Interval::try_new(
2610                    prev_value(ScalarValue::Float32(Some(0.0_f32))),
2611                    prev_value(ScalarValue::Float32(Some(0.0_f32))),
2612                )?,
2613                Interval::make(Some(0.0_f32), Some(0.0_f32))?,
2614            ),
2615            (
2616                Interval::make(Some(-1.0_f32), Some(-1.0_f32))?,
2617                Interval::try_new(
2618                    next_value(ScalarValue::Float32(Some(-1.0))),
2619                    next_value(ScalarValue::Float32(Some(-1.0))),
2620                )?,
2621            ),
2622        ];
2623        for (first, second) in not_gteq_cases {
2624            assert_eq!(first.gt_eq(second.clone())?, Interval::FALSE);
2625            assert_eq!(second.lt_eq(first)?, Interval::FALSE);
2626        }
2627
2628        Ok(())
2629    }
2630
2631    #[test]
2632    fn equal_test() -> Result<()> {
2633        let exactly_eq_cases = vec![
2634            (
2635                Interval::make(Some(1000_i64), Some(1000_i64))?,
2636                Interval::make(Some(1000_i64), Some(1000_i64))?,
2637            ),
2638            (
2639                Interval::make(Some(0_u64), Some(0_u64))?,
2640                Interval::make(Some(0_u64), Some(0_u64))?,
2641            ),
2642            (
2643                Interval::make(Some(f32::MAX), Some(f32::MAX))?,
2644                Interval::make(Some(f32::MAX), Some(f32::MAX))?,
2645            ),
2646            (
2647                Interval::make(Some(f64::MIN), Some(f64::MIN))?,
2648                Interval::make(Some(f64::MIN), Some(f64::MIN))?,
2649            ),
2650        ];
2651        for (first, second) in exactly_eq_cases {
2652            assert_eq!(first.equal(second.clone())?, Interval::TRUE);
2653            assert_eq!(second.equal(first)?, Interval::TRUE);
2654        }
2655
2656        let possibly_eq_cases = vec![
2657            (
2658                Interval::make::<i64>(None, None)?,
2659                Interval::make::<i64>(None, None)?,
2660            ),
2661            (
2662                Interval::make(Some(0_i64), Some(0_i64))?,
2663                Interval::make(Some(0_i64), Some(1000_i64))?,
2664            ),
2665            (
2666                Interval::make(Some(0_i64), Some(0_i64))?,
2667                Interval::make(Some(0_i64), Some(1000_i64))?,
2668            ),
2669            (
2670                Interval::make(Some(100.0_f32), Some(200.0_f32))?,
2671                Interval::make(Some(0.0_f32), Some(1000.0_f32))?,
2672            ),
2673            (
2674                Interval::try_new(
2675                    prev_value(ScalarValue::Float32(Some(0.0))),
2676                    ScalarValue::Float32(Some(0.0)),
2677                )?,
2678                Interval::make(Some(0.0_f32), Some(0.0_f32))?,
2679            ),
2680            (
2681                Interval::make(Some(-1.0_f32), Some(-1.0_f32))?,
2682                Interval::try_new(
2683                    prev_value(ScalarValue::Float32(Some(-1.0))),
2684                    next_value(ScalarValue::Float32(Some(-1.0))),
2685                )?,
2686            ),
2687        ];
2688        for (first, second) in possibly_eq_cases {
2689            assert_eq!(first.equal(second.clone())?, Interval::TRUE_OR_FALSE);
2690            assert_eq!(second.equal(first)?, Interval::TRUE_OR_FALSE);
2691        }
2692
2693        let not_eq_cases = vec![
2694            (
2695                Interval::make(Some(1000_i64), Some(1000_i64))?,
2696                Interval::make(Some(2000_i64), Some(2000_i64))?,
2697            ),
2698            (
2699                Interval::make(Some(500_i64), Some(999_i64))?,
2700                Interval::make(Some(1000_i64), None)?,
2701            ),
2702            (
2703                Interval::make(None, Some(1000_i64))?,
2704                Interval::make(Some(1001_i64), Some(1500_i64))?,
2705            ),
2706            (
2707                Interval::try_new(
2708                    prev_value(ScalarValue::Float32(Some(0.0))),
2709                    prev_value(ScalarValue::Float32(Some(0.0))),
2710                )?,
2711                Interval::make(Some(0.0_f32), Some(0.0_f32))?,
2712            ),
2713            (
2714                Interval::make(Some(-1.0_f32), Some(-1.0_f32))?,
2715                Interval::try_new(
2716                    next_value(ScalarValue::Float32(Some(-1.0))),
2717                    next_value(ScalarValue::Float32(Some(-1.0))),
2718                )?,
2719            ),
2720        ];
2721        for (first, second) in not_eq_cases {
2722            assert_eq!(first.equal(second.clone())?, Interval::FALSE);
2723            assert_eq!(second.equal(first)?, Interval::FALSE);
2724        }
2725
2726        Ok(())
2727    }
2728
2729    #[test]
2730    fn and_test() -> Result<()> {
2731        let cases = vec![
2732            (Interval::TRUE_OR_FALSE, Interval::FALSE, Interval::FALSE),
2733            (
2734                Interval::TRUE_OR_FALSE,
2735                Interval::TRUE_OR_FALSE,
2736                Interval::TRUE_OR_FALSE,
2737            ),
2738            (
2739                Interval::TRUE_OR_FALSE,
2740                Interval::TRUE,
2741                Interval::TRUE_OR_FALSE,
2742            ),
2743            (Interval::FALSE, Interval::FALSE, Interval::FALSE),
2744            (Interval::FALSE, Interval::TRUE_OR_FALSE, Interval::FALSE),
2745            (Interval::FALSE, Interval::TRUE, Interval::FALSE),
2746            (Interval::TRUE, Interval::FALSE, Interval::FALSE),
2747            (
2748                Interval::TRUE,
2749                Interval::TRUE_OR_FALSE,
2750                Interval::TRUE_OR_FALSE,
2751            ),
2752            (Interval::TRUE, Interval::TRUE, Interval::TRUE),
2753        ];
2754
2755        for case in cases {
2756            assert_eq!(
2757                case.0.and(&case.1)?,
2758                case.2,
2759                "Failed for {} AND {}",
2760                case.0,
2761                case.1
2762            );
2763        }
2764        Ok(())
2765    }
2766
2767    #[test]
2768    fn or_test() -> Result<()> {
2769        let cases = vec![
2770            (
2771                Interval::TRUE_OR_FALSE,
2772                Interval::FALSE,
2773                Interval::TRUE_OR_FALSE,
2774            ),
2775            (
2776                Interval::TRUE_OR_FALSE,
2777                Interval::TRUE_OR_FALSE,
2778                Interval::TRUE_OR_FALSE,
2779            ),
2780            (Interval::TRUE_OR_FALSE, Interval::TRUE, Interval::TRUE),
2781            (Interval::FALSE, Interval::FALSE, Interval::FALSE),
2782            (
2783                Interval::FALSE,
2784                Interval::TRUE_OR_FALSE,
2785                Interval::TRUE_OR_FALSE,
2786            ),
2787            (Interval::FALSE, Interval::TRUE, Interval::TRUE),
2788            (Interval::TRUE, Interval::FALSE, Interval::TRUE),
2789            (Interval::TRUE, Interval::TRUE_OR_FALSE, Interval::TRUE),
2790            (Interval::TRUE, Interval::TRUE, Interval::TRUE),
2791        ];
2792
2793        for case in cases {
2794            assert_eq!(
2795                case.0.or(&case.1)?,
2796                case.2,
2797                "Failed for {} OR {}",
2798                case.0,
2799                case.1
2800            );
2801        }
2802        Ok(())
2803    }
2804
2805    #[test]
2806    fn not_test() -> Result<()> {
2807        let cases = vec![
2808            (Interval::TRUE_OR_FALSE, Interval::TRUE_OR_FALSE),
2809            (Interval::FALSE, Interval::TRUE),
2810            (Interval::TRUE, Interval::FALSE),
2811        ];
2812
2813        for case in cases {
2814            assert_eq!(case.0.not()?, case.1, "Failed for NOT {}", case.0);
2815        }
2816        Ok(())
2817    }
2818
2819    #[test]
2820    fn test_and_or_with_normalized_boolean_intervals() -> Result<()> {
2821        // Verify that NULL boolean bounds are normalized and don't cause errors
2822        let from_nulls =
2823            Interval::try_new(ScalarValue::Boolean(None), ScalarValue::Boolean(None))?;
2824
2825        assert!(from_nulls.or(&Interval::TRUE).is_ok());
2826        assert!(from_nulls.and(&Interval::FALSE).is_ok());
2827
2828        Ok(())
2829    }
2830
2831    // Tests that there's no such thing as a 'null' boolean interval.
2832    // An interval with two `Boolean(None)` boundaries is normalised to `Interval::TRUE_OR_FALSE`.
2833    #[test]
2834    fn test_null_boolean_interval() {
2835        let null_interval =
2836            Interval::try_new(ScalarValue::Boolean(None), ScalarValue::Boolean(None))
2837                .unwrap();
2838
2839        assert_eq!(null_interval, Interval::TRUE_OR_FALSE);
2840    }
2841
2842    // Asserts that `Interval::TRUE_OR_FALSE` represents a set that contains `true`, `false`, and does
2843    // not contain `null`.
2844    #[test]
2845    fn test_uncertain_boolean_interval() {
2846        assert!(
2847            Interval::TRUE_OR_FALSE
2848                .contains_value(ScalarValue::Boolean(Some(true)))
2849                .unwrap()
2850        );
2851        assert!(
2852            Interval::TRUE_OR_FALSE
2853                .contains_value(ScalarValue::Boolean(Some(false)))
2854                .unwrap()
2855        );
2856        assert!(
2857            !Interval::TRUE_OR_FALSE
2858                .contains_value(ScalarValue::Boolean(None))
2859                .unwrap()
2860        );
2861        assert!(
2862            !Interval::TRUE_OR_FALSE
2863                .contains_value(ScalarValue::Null)
2864                .unwrap()
2865        );
2866    }
2867
2868    #[test]
2869    fn test_and_uncertain_boolean_intervals() -> Result<()> {
2870        let and_result = Interval::TRUE_OR_FALSE.and(&Interval::FALSE)?;
2871        assert_eq!(and_result, Interval::FALSE);
2872
2873        let and_result = Interval::FALSE.and(&Interval::TRUE_OR_FALSE)?;
2874        assert_eq!(and_result, Interval::FALSE);
2875
2876        let and_result = Interval::TRUE_OR_FALSE.and(&Interval::TRUE)?;
2877        assert_eq!(and_result, Interval::TRUE_OR_FALSE);
2878
2879        let and_result = Interval::TRUE.and(&Interval::TRUE_OR_FALSE)?;
2880        assert_eq!(and_result, Interval::TRUE_OR_FALSE);
2881
2882        let and_result = Interval::TRUE_OR_FALSE.and(&Interval::TRUE_OR_FALSE)?;
2883        assert_eq!(and_result, Interval::TRUE_OR_FALSE);
2884
2885        Ok(())
2886    }
2887
2888    #[test]
2889    fn test_or_uncertain_boolean_intervals() -> Result<()> {
2890        let or_result = Interval::TRUE_OR_FALSE.or(&Interval::FALSE)?;
2891        assert_eq!(or_result, Interval::TRUE_OR_FALSE);
2892
2893        let or_result = Interval::FALSE.or(&Interval::TRUE_OR_FALSE)?;
2894        assert_eq!(or_result, Interval::TRUE_OR_FALSE);
2895
2896        let or_result = Interval::TRUE_OR_FALSE.or(&Interval::TRUE)?;
2897        assert_eq!(or_result, Interval::TRUE);
2898
2899        let or_result = Interval::TRUE.or(&Interval::TRUE_OR_FALSE)?;
2900        assert_eq!(or_result, Interval::TRUE);
2901
2902        let or_result = Interval::TRUE_OR_FALSE.or(&Interval::TRUE_OR_FALSE)?;
2903        assert_eq!(or_result, Interval::TRUE_OR_FALSE);
2904
2905        Ok(())
2906    }
2907
2908    #[test]
2909    fn intersect_test() -> Result<()> {
2910        let possible_cases = vec![
2911            (
2912                Interval::make(Some(1000_i64), None)?,
2913                Interval::make::<i64>(None, None)?,
2914                Interval::make(Some(1000_i64), None)?,
2915            ),
2916            (
2917                Interval::make(Some(1000_i64), None)?,
2918                Interval::make(None, Some(1000_i64))?,
2919                Interval::make(Some(1000_i64), Some(1000_i64))?,
2920            ),
2921            (
2922                Interval::make(Some(1000_i64), None)?,
2923                Interval::make(None, Some(2000_i64))?,
2924                Interval::make(Some(1000_i64), Some(2000_i64))?,
2925            ),
2926            (
2927                Interval::make(Some(1000_i64), Some(2000_i64))?,
2928                Interval::make(Some(1000_i64), None)?,
2929                Interval::make(Some(1000_i64), Some(2000_i64))?,
2930            ),
2931            (
2932                Interval::make(Some(1000_i64), Some(2000_i64))?,
2933                Interval::make(Some(1000_i64), Some(1500_i64))?,
2934                Interval::make(Some(1000_i64), Some(1500_i64))?,
2935            ),
2936            (
2937                Interval::make(Some(1000_i64), Some(2000_i64))?,
2938                Interval::make(Some(500_i64), Some(1500_i64))?,
2939                Interval::make(Some(1000_i64), Some(1500_i64))?,
2940            ),
2941            (
2942                Interval::make::<i64>(None, None)?,
2943                Interval::make::<i64>(None, None)?,
2944                Interval::make::<i64>(None, None)?,
2945            ),
2946            (
2947                Interval::make(None, Some(2000_u64))?,
2948                Interval::make(Some(500_u64), None)?,
2949                Interval::make(Some(500_u64), Some(2000_u64))?,
2950            ),
2951            (
2952                Interval::make(Some(0_u64), Some(0_u64))?,
2953                Interval::make(Some(0_u64), None)?,
2954                Interval::make(Some(0_u64), Some(0_u64))?,
2955            ),
2956            (
2957                Interval::make(Some(1000.0_f32), None)?,
2958                Interval::make(None, Some(1000.0_f32))?,
2959                Interval::make(Some(1000.0_f32), Some(1000.0_f32))?,
2960            ),
2961            (
2962                Interval::make(Some(1000.0_f32), Some(1500.0_f32))?,
2963                Interval::make(Some(0.0_f32), Some(1500.0_f32))?,
2964                Interval::make(Some(1000.0_f32), Some(1500.0_f32))?,
2965            ),
2966            (
2967                Interval::make(Some(-1000.0_f64), Some(1500.0_f64))?,
2968                Interval::make(Some(-1500.0_f64), Some(2000.0_f64))?,
2969                Interval::make(Some(-1000.0_f64), Some(1500.0_f64))?,
2970            ),
2971            (
2972                Interval::make(Some(16.0_f64), Some(32.0_f64))?,
2973                Interval::make(Some(32.0_f64), Some(64.0_f64))?,
2974                Interval::make(Some(32.0_f64), Some(32.0_f64))?,
2975            ),
2976        ];
2977        for (first, second, expected) in possible_cases {
2978            assert_eq!(first.intersect(second)?.unwrap(), expected)
2979        }
2980
2981        let empty_cases = vec![
2982            (
2983                Interval::make(Some(1000_i64), None)?,
2984                Interval::make(None, Some(0_i64))?,
2985            ),
2986            (
2987                Interval::make(Some(1000_i64), None)?,
2988                Interval::make(None, Some(999_i64))?,
2989            ),
2990            (
2991                Interval::make(Some(1500_i64), Some(2000_i64))?,
2992                Interval::make(Some(1000_i64), Some(1499_i64))?,
2993            ),
2994            (
2995                Interval::make(Some(0_i64), Some(1000_i64))?,
2996                Interval::make(Some(2000_i64), Some(3000_i64))?,
2997            ),
2998            (
2999                Interval::try_new(
3000                    prev_value(ScalarValue::Float32(Some(1.0))),
3001                    prev_value(ScalarValue::Float32(Some(1.0))),
3002                )?,
3003                Interval::make(Some(1.0_f32), Some(1.0_f32))?,
3004            ),
3005            (
3006                Interval::try_new(
3007                    next_value(ScalarValue::Float32(Some(1.0))),
3008                    next_value(ScalarValue::Float32(Some(1.0))),
3009                )?,
3010                Interval::make(Some(1.0_f32), Some(1.0_f32))?,
3011            ),
3012        ];
3013        for (first, second) in empty_cases {
3014            assert_eq!(first.intersect(second)?, None)
3015        }
3016
3017        Ok(())
3018    }
3019
3020    #[test]
3021    fn union_test() -> Result<()> {
3022        let possible_cases = vec![
3023            (
3024                Interval::make(Some(1000_i64), None)?,
3025                Interval::make::<i64>(None, None)?,
3026                Interval::make_unbounded(&DataType::Int64)?,
3027            ),
3028            (
3029                Interval::make(Some(1000_i64), None)?,
3030                Interval::make(None, Some(1000_i64))?,
3031                Interval::make_unbounded(&DataType::Int64)?,
3032            ),
3033            (
3034                Interval::make(Some(1000_i64), None)?,
3035                Interval::make(None, Some(2000_i64))?,
3036                Interval::make_unbounded(&DataType::Int64)?,
3037            ),
3038            (
3039                Interval::make(Some(1000_i64), Some(2000_i64))?,
3040                Interval::make(Some(1000_i64), None)?,
3041                Interval::make(Some(1000_i64), None)?,
3042            ),
3043            (
3044                Interval::make(Some(1000_i64), Some(2000_i64))?,
3045                Interval::make(Some(1000_i64), Some(1500_i64))?,
3046                Interval::make(Some(1000_i64), Some(2000_i64))?,
3047            ),
3048            (
3049                Interval::make(Some(1000_i64), Some(2000_i64))?,
3050                Interval::make(Some(500_i64), Some(1500_i64))?,
3051                Interval::make(Some(500_i64), Some(2000_i64))?,
3052            ),
3053            (
3054                Interval::make::<i64>(None, None)?,
3055                Interval::make::<i64>(None, None)?,
3056                Interval::make::<i64>(None, None)?,
3057            ),
3058            (
3059                Interval::make(Some(1000_i64), None)?,
3060                Interval::make(None, Some(0_i64))?,
3061                Interval::make_unbounded(&DataType::Int64)?,
3062            ),
3063            (
3064                Interval::make(Some(1000_i64), None)?,
3065                Interval::make(None, Some(999_i64))?,
3066                Interval::make_unbounded(&DataType::Int64)?,
3067            ),
3068            (
3069                Interval::make(Some(1500_i64), Some(2000_i64))?,
3070                Interval::make(Some(1000_i64), Some(1499_i64))?,
3071                Interval::make(Some(1000_i64), Some(2000_i64))?,
3072            ),
3073            (
3074                Interval::make(Some(0_i64), Some(1000_i64))?,
3075                Interval::make(Some(2000_i64), Some(3000_i64))?,
3076                Interval::make(Some(0_i64), Some(3000_i64))?,
3077            ),
3078            (
3079                Interval::make(None, Some(2000_u64))?,
3080                Interval::make(Some(500_u64), None)?,
3081                Interval::make(Some(0_u64), None)?,
3082            ),
3083            (
3084                Interval::make(Some(0_u64), Some(0_u64))?,
3085                Interval::make(Some(0_u64), None)?,
3086                Interval::make(Some(0_u64), None)?,
3087            ),
3088            (
3089                Interval::make(Some(1000.0_f32), None)?,
3090                Interval::make(None, Some(1000.0_f32))?,
3091                Interval::make_unbounded(&DataType::Float32)?,
3092            ),
3093            (
3094                Interval::make(Some(1000.0_f32), Some(1500.0_f32))?,
3095                Interval::make(Some(0.0_f32), Some(1500.0_f32))?,
3096                Interval::make(Some(0.0_f32), Some(1500.0_f32))?,
3097            ),
3098            (
3099                Interval::try_new(
3100                    prev_value(ScalarValue::Float32(Some(1.0))),
3101                    prev_value(ScalarValue::Float32(Some(1.0))),
3102                )?,
3103                Interval::make(Some(1.0_f32), Some(1.0_f32))?,
3104                Interval::try_new(
3105                    prev_value(ScalarValue::Float32(Some(1.0))),
3106                    ScalarValue::Float32(Some(1.0)),
3107                )?,
3108            ),
3109            (
3110                Interval::try_new(
3111                    next_value(ScalarValue::Float32(Some(1.0))),
3112                    next_value(ScalarValue::Float32(Some(1.0))),
3113                )?,
3114                Interval::make(Some(1.0_f32), Some(1.0_f32))?,
3115                Interval::try_new(
3116                    ScalarValue::Float32(Some(1.0)),
3117                    next_value(ScalarValue::Float32(Some(1.0))),
3118                )?,
3119            ),
3120            (
3121                Interval::make(Some(-1000.0_f64), Some(1500.0_f64))?,
3122                Interval::make(Some(-1500.0_f64), Some(2000.0_f64))?,
3123                Interval::make(Some(-1500.0_f64), Some(2000.0_f64))?,
3124            ),
3125            (
3126                Interval::make(Some(16.0_f64), Some(32.0_f64))?,
3127                Interval::make(Some(32.0_f64), Some(64.0_f64))?,
3128                Interval::make(Some(16.0_f64), Some(64.0_f64))?,
3129            ),
3130        ];
3131        for (first, second, expected) in possible_cases {
3132            println!("{first}");
3133            println!("{second}");
3134            assert_eq!(first.union(second)?, expected)
3135        }
3136
3137        Ok(())
3138    }
3139
3140    #[test]
3141    fn test_contains() -> Result<()> {
3142        let possible_cases = vec![
3143            (
3144                Interval::make::<i64>(None, None)?,
3145                Interval::make::<i64>(None, None)?,
3146                Interval::TRUE,
3147            ),
3148            (
3149                Interval::make(Some(1500_i64), Some(2000_i64))?,
3150                Interval::make(Some(1501_i64), Some(1999_i64))?,
3151                Interval::TRUE,
3152            ),
3153            (
3154                Interval::make(Some(1000_i64), None)?,
3155                Interval::make::<i64>(None, None)?,
3156                Interval::TRUE_OR_FALSE,
3157            ),
3158            (
3159                Interval::make(Some(1000_i64), Some(2000_i64))?,
3160                Interval::make(Some(500), Some(1500_i64))?,
3161                Interval::TRUE_OR_FALSE,
3162            ),
3163            (
3164                Interval::make(Some(16.0), Some(32.0))?,
3165                Interval::make(Some(32.0), Some(64.0))?,
3166                Interval::TRUE_OR_FALSE,
3167            ),
3168            (
3169                Interval::make(Some(1000_i64), None)?,
3170                Interval::make(None, Some(0_i64))?,
3171                Interval::FALSE,
3172            ),
3173            (
3174                Interval::make(Some(1500_i64), Some(2000_i64))?,
3175                Interval::make(Some(1000_i64), Some(1499_i64))?,
3176                Interval::FALSE,
3177            ),
3178            (
3179                Interval::try_new(
3180                    prev_value(ScalarValue::Float32(Some(1.0))),
3181                    prev_value(ScalarValue::Float32(Some(1.0))),
3182                )?,
3183                Interval::make(Some(1.0_f32), Some(1.0_f32))?,
3184                Interval::FALSE,
3185            ),
3186            (
3187                Interval::try_new(
3188                    next_value(ScalarValue::Float32(Some(1.0))),
3189                    next_value(ScalarValue::Float32(Some(1.0))),
3190                )?,
3191                Interval::make(Some(1.0_f32), Some(1.0_f32))?,
3192                Interval::FALSE,
3193            ),
3194        ];
3195        for (first, second, expected) in possible_cases {
3196            assert_eq!(first.contains(second)?, expected)
3197        }
3198
3199        Ok(())
3200    }
3201
3202    #[test]
3203    fn test_contains_value() -> Result<()> {
3204        let possible_cases = vec![
3205            (
3206                Interval::make(Some(0), Some(100))?,
3207                ScalarValue::Int32(Some(50)),
3208                true,
3209            ),
3210            (
3211                Interval::make(Some(0), Some(100))?,
3212                ScalarValue::Int32(Some(150)),
3213                false,
3214            ),
3215            (
3216                Interval::make(Some(0), Some(100))?,
3217                ScalarValue::Float64(Some(50.)),
3218                true,
3219            ),
3220            (
3221                Interval::make(Some(0), Some(100))?,
3222                ScalarValue::Float64(Some(next_down(100.))),
3223                true,
3224            ),
3225            (
3226                Interval::make(Some(0), Some(100))?,
3227                ScalarValue::Float64(Some(next_up(100.))),
3228                false,
3229            ),
3230        ];
3231
3232        for (interval, value, expected) in possible_cases {
3233            assert_eq!(interval.contains_value(value)?, expected)
3234        }
3235
3236        Ok(())
3237    }
3238
3239    #[test]
3240    fn test_add() -> Result<()> {
3241        let cases = vec![
3242            (
3243                Interval::make(Some(100_i64), Some(200_i64))?,
3244                Interval::make(None, Some(200_i64))?,
3245                Interval::make(None, Some(400_i64))?,
3246            ),
3247            (
3248                Interval::make(Some(100_i64), Some(200_i64))?,
3249                Interval::make(Some(200_i64), None)?,
3250                Interval::make(Some(300_i64), None)?,
3251            ),
3252            (
3253                Interval::make(None, Some(200_i64))?,
3254                Interval::make(Some(100_i64), Some(200_i64))?,
3255                Interval::make(None, Some(400_i64))?,
3256            ),
3257            (
3258                Interval::make(Some(200_i64), None)?,
3259                Interval::make(Some(100_i64), Some(200_i64))?,
3260                Interval::make(Some(300_i64), None)?,
3261            ),
3262            (
3263                Interval::make(Some(100_i64), Some(200_i64))?,
3264                Interval::make(Some(-300_i64), Some(150_i64))?,
3265                Interval::make(Some(-200_i64), Some(350_i64))?,
3266            ),
3267            (
3268                Interval::make(Some(f32::MAX), Some(f32::MAX))?,
3269                Interval::make(Some(11_f32), Some(11_f32))?,
3270                Interval::make(Some(f32::MAX), None)?,
3271            ),
3272            (
3273                Interval::make(Some(f32::MIN), Some(f32::MIN))?,
3274                Interval::make(Some(-10_f32), Some(10_f32))?,
3275                // Since rounding mode is up, the result would be much greater than f32::MIN
3276                // (f32::MIN = -3.4_028_235e38, the result is -3.4_028_233e38)
3277                Interval::make(
3278                    None,
3279                    Some(-340282330000000000000000000000000000000.0_f32),
3280                )?,
3281            ),
3282            (
3283                Interval::make(Some(f32::MIN), Some(f32::MIN))?,
3284                Interval::make(Some(-10_f32), Some(-10_f32))?,
3285                Interval::make(None, Some(f32::MIN))?,
3286            ),
3287            (
3288                Interval::make(Some(1.0), Some(f32::MAX))?,
3289                Interval::make(Some(f32::MAX), Some(f32::MAX))?,
3290                Interval::make(Some(f32::MAX), None)?,
3291            ),
3292            (
3293                Interval::make(Some(f32::MIN), Some(f32::MIN))?,
3294                Interval::make(Some(f32::MAX), Some(f32::MAX))?,
3295                Interval::make(Some(-0.0_f32), Some(0.0_f32))?,
3296            ),
3297            (
3298                Interval::make(Some(100_f64), None)?,
3299                Interval::make(None, Some(200_f64))?,
3300                Interval::make::<i64>(None, None)?,
3301            ),
3302            (
3303                Interval::make(None, Some(100_f64))?,
3304                Interval::make(None, Some(200_f64))?,
3305                Interval::make(None, Some(300_f64))?,
3306            ),
3307        ];
3308        for case in cases {
3309            let result = case.0.add(case.1)?;
3310            if case.0.data_type().is_floating() {
3311                assert!(
3312                    result.lower().is_null() && case.2.lower().is_null()
3313                        || result.lower().le(case.2.lower())
3314                );
3315                assert!(
3316                    result.upper().is_null() && case.2.upper().is_null()
3317                        || result.upper().ge(case.2.upper())
3318                );
3319            } else {
3320                assert_eq!(result, case.2);
3321            }
3322        }
3323
3324        Ok(())
3325    }
3326
3327    #[test]
3328    fn test_sub() -> Result<()> {
3329        let cases = vec![
3330            (
3331                Interval::make(Some(i32::MAX), Some(i32::MAX))?,
3332                Interval::make(Some(11_i32), Some(11_i32))?,
3333                Interval::make(Some(i32::MAX - 11), Some(i32::MAX - 11))?,
3334            ),
3335            (
3336                Interval::make(Some(100_i64), Some(200_i64))?,
3337                Interval::make(None, Some(200_i64))?,
3338                Interval::make(Some(-100_i64), None)?,
3339            ),
3340            (
3341                Interval::make(Some(100_i64), Some(200_i64))?,
3342                Interval::make(Some(200_i64), None)?,
3343                Interval::make(None, Some(0_i64))?,
3344            ),
3345            (
3346                Interval::make(None, Some(200_i64))?,
3347                Interval::make(Some(100_i64), Some(200_i64))?,
3348                Interval::make(None, Some(100_i64))?,
3349            ),
3350            (
3351                Interval::make(Some(200_i64), None)?,
3352                Interval::make(Some(100_i64), Some(200_i64))?,
3353                Interval::make(Some(0_i64), None)?,
3354            ),
3355            (
3356                Interval::make(Some(100_i64), Some(200_i64))?,
3357                Interval::make(Some(-300_i64), Some(150_i64))?,
3358                Interval::make(Some(-50_i64), Some(500_i64))?,
3359            ),
3360            (
3361                Interval::make(Some(i64::MIN), Some(i64::MIN))?,
3362                Interval::make(Some(-10_i64), Some(-10_i64))?,
3363                Interval::make(Some(i64::MIN + 10), Some(i64::MIN + 10))?,
3364            ),
3365            (
3366                Interval::make(Some(1), Some(i64::MAX))?,
3367                Interval::make(Some(i64::MAX), Some(i64::MAX))?,
3368                Interval::make(Some(1 - i64::MAX), Some(0))?,
3369            ),
3370            (
3371                Interval::make(Some(i64::MIN), Some(i64::MIN))?,
3372                Interval::make(Some(i64::MAX), Some(i64::MAX))?,
3373                Interval::make(None, Some(i64::MIN))?,
3374            ),
3375            (
3376                Interval::make(Some(2_u32), Some(10_u32))?,
3377                Interval::make(Some(4_u32), Some(6_u32))?,
3378                Interval::make(None, Some(6_u32))?,
3379            ),
3380            (
3381                Interval::make(Some(2_u32), Some(10_u32))?,
3382                Interval::make(Some(20_u32), Some(30_u32))?,
3383                Interval::make(None, Some(0_u32))?,
3384            ),
3385            (
3386                Interval::make(Some(f32::MIN), Some(f32::MIN))?,
3387                Interval::make(Some(-10_f32), Some(10_f32))?,
3388                // Since rounding mode is up, the result would be much larger than f32::MIN
3389                // (f32::MIN = -3.4_028_235e38, the result is -3.4_028_233e38)
3390                Interval::make(
3391                    None,
3392                    Some(-340282330000000000000000000000000000000.0_f32),
3393                )?,
3394            ),
3395            (
3396                Interval::make(Some(100_f64), None)?,
3397                Interval::make(None, Some(200_f64))?,
3398                Interval::make(Some(-100_f64), None)?,
3399            ),
3400            (
3401                Interval::make(None, Some(100_f64))?,
3402                Interval::make(None, Some(200_f64))?,
3403                Interval::make::<i64>(None, None)?,
3404            ),
3405        ];
3406        for case in cases {
3407            let result = case.0.sub(case.1)?;
3408            if case.0.data_type().is_floating() {
3409                assert!(
3410                    result.lower().is_null() && case.2.lower().is_null()
3411                        || result.lower().le(case.2.lower())
3412                );
3413                assert!(
3414                    result.upper().is_null() && case.2.upper().is_null()
3415                        || result.upper().ge(case.2.upper(),)
3416                );
3417            } else {
3418                assert_eq!(result, case.2);
3419            }
3420        }
3421
3422        Ok(())
3423    }
3424
3425    #[test]
3426    fn test_mul() -> Result<()> {
3427        let cases = vec![
3428            (
3429                Interval::make(Some(1_i64), Some(2_i64))?,
3430                Interval::make(None, Some(2_i64))?,
3431                Interval::make(None, Some(4_i64))?,
3432            ),
3433            (
3434                Interval::make(Some(1_i64), Some(2_i64))?,
3435                Interval::make(Some(2_i64), None)?,
3436                Interval::make(Some(2_i64), None)?,
3437            ),
3438            (
3439                Interval::make(None, Some(2_i64))?,
3440                Interval::make(Some(1_i64), Some(2_i64))?,
3441                Interval::make(None, Some(4_i64))?,
3442            ),
3443            (
3444                Interval::make(Some(2_i64), None)?,
3445                Interval::make(Some(1_i64), Some(2_i64))?,
3446                Interval::make(Some(2_i64), None)?,
3447            ),
3448            (
3449                Interval::make(Some(1_i64), Some(2_i64))?,
3450                Interval::make(Some(-3_i64), Some(15_i64))?,
3451                Interval::make(Some(-6_i64), Some(30_i64))?,
3452            ),
3453            (
3454                Interval::make(Some(-0.0), Some(0.0))?,
3455                Interval::make(None, Some(0.0))?,
3456                Interval::make::<i64>(None, None)?,
3457            ),
3458            (
3459                Interval::make(Some(f32::MIN), Some(f32::MIN))?,
3460                Interval::make(Some(-10_f32), Some(10_f32))?,
3461                Interval::make::<i64>(None, None)?,
3462            ),
3463            (
3464                Interval::make(Some(1_u32), Some(2_u32))?,
3465                Interval::make(Some(0_u32), Some(1_u32))?,
3466                Interval::make(Some(0_u32), Some(2_u32))?,
3467            ),
3468            (
3469                Interval::make(None, Some(2_u32))?,
3470                Interval::make(Some(0_u32), Some(1_u32))?,
3471                Interval::make(None, Some(2_u32))?,
3472            ),
3473            (
3474                Interval::make(None, Some(2_u32))?,
3475                Interval::make(Some(1_u32), Some(2_u32))?,
3476                Interval::make(None, Some(4_u32))?,
3477            ),
3478            (
3479                Interval::make(None, Some(2_u32))?,
3480                Interval::make(Some(1_u32), None)?,
3481                Interval::make::<u32>(None, None)?,
3482            ),
3483            (
3484                Interval::make::<u32>(None, None)?,
3485                Interval::make(Some(0_u32), None)?,
3486                Interval::make::<u32>(None, None)?,
3487            ),
3488            (
3489                Interval::make(Some(f32::MAX), Some(f32::MAX))?,
3490                Interval::make(Some(11_f32), Some(11_f32))?,
3491                Interval::make(Some(f32::MAX), None)?,
3492            ),
3493            (
3494                Interval::make(Some(f32::MIN), Some(f32::MIN))?,
3495                Interval::make(Some(-10_f32), Some(-10_f32))?,
3496                Interval::make(Some(f32::MAX), None)?,
3497            ),
3498            (
3499                Interval::make(Some(1.0), Some(f32::MAX))?,
3500                Interval::make(Some(f32::MAX), Some(f32::MAX))?,
3501                Interval::make(Some(f32::MAX), None)?,
3502            ),
3503            (
3504                Interval::make(Some(f32::MIN), Some(f32::MIN))?,
3505                Interval::make(Some(f32::MAX), Some(f32::MAX))?,
3506                Interval::make(None, Some(f32::MIN))?,
3507            ),
3508            (
3509                Interval::make(Some(-0.0_f32), Some(0.0_f32))?,
3510                Interval::make(Some(f32::MAX), None)?,
3511                Interval::make::<f32>(None, None)?,
3512            ),
3513            (
3514                Interval::make(Some(0.0_f32), Some(0.0_f32))?,
3515                Interval::make(Some(f32::MAX), None)?,
3516                Interval::make(Some(0.0_f32), None)?,
3517            ),
3518            (
3519                Interval::make(Some(1_f64), None)?,
3520                Interval::make(None, Some(2_f64))?,
3521                Interval::make::<f64>(None, None)?,
3522            ),
3523            (
3524                Interval::make(None, Some(1_f64))?,
3525                Interval::make(None, Some(2_f64))?,
3526                Interval::make::<f64>(None, None)?,
3527            ),
3528            (
3529                Interval::make(Some(-0.0_f64), Some(-0.0_f64))?,
3530                Interval::make(Some(1_f64), Some(2_f64))?,
3531                Interval::make(Some(-0.0_f64), Some(-0.0_f64))?,
3532            ),
3533            (
3534                Interval::make(Some(0.0_f64), Some(0.0_f64))?,
3535                Interval::make(Some(1_f64), Some(2_f64))?,
3536                Interval::make(Some(0.0_f64), Some(0.0_f64))?,
3537            ),
3538            (
3539                Interval::make(Some(-0.0_f64), Some(0.0_f64))?,
3540                Interval::make(Some(1_f64), Some(2_f64))?,
3541                Interval::make(Some(-0.0_f64), Some(0.0_f64))?,
3542            ),
3543            (
3544                Interval::make(Some(-0.0_f64), Some(1.0_f64))?,
3545                Interval::make(Some(1_f64), Some(2_f64))?,
3546                Interval::make(Some(-0.0_f64), Some(2.0_f64))?,
3547            ),
3548            (
3549                Interval::make(Some(0.0_f64), Some(1.0_f64))?,
3550                Interval::make(Some(1_f64), Some(2_f64))?,
3551                Interval::make(Some(0.0_f64), Some(2.0_f64))?,
3552            ),
3553            (
3554                Interval::make(Some(-0.0_f64), Some(1.0_f64))?,
3555                Interval::make(Some(-1_f64), Some(2_f64))?,
3556                Interval::make(Some(-1.0_f64), Some(2.0_f64))?,
3557            ),
3558            (
3559                Interval::make::<f64>(None, None)?,
3560                Interval::make(Some(-0.0_f64), Some(0.0_f64))?,
3561                Interval::make::<f64>(None, None)?,
3562            ),
3563            (
3564                Interval::make::<f64>(None, Some(10.0_f64))?,
3565                Interval::make(Some(-0.0_f64), Some(0.0_f64))?,
3566                Interval::make::<f64>(None, None)?,
3567            ),
3568        ];
3569        for case in cases {
3570            let result = case.0.mul(case.1)?;
3571            if case.0.data_type().is_floating() {
3572                assert!(
3573                    result.lower().is_null() && case.2.lower().is_null()
3574                        || result.lower().le(case.2.lower())
3575                );
3576                assert!(
3577                    result.upper().is_null() && case.2.upper().is_null()
3578                        || result.upper().ge(case.2.upper())
3579                );
3580            } else {
3581                assert_eq!(result, case.2);
3582            }
3583        }
3584
3585        Ok(())
3586    }
3587
3588    #[test]
3589    fn test_div() -> Result<()> {
3590        let cases = vec![
3591            (
3592                Interval::make(Some(100_i64), Some(200_i64))?,
3593                Interval::make(Some(1_i64), Some(2_i64))?,
3594                Interval::make(Some(50_i64), Some(200_i64))?,
3595            ),
3596            (
3597                Interval::make(Some(-200_i64), Some(-100_i64))?,
3598                Interval::make(Some(-2_i64), Some(-1_i64))?,
3599                Interval::make(Some(50_i64), Some(200_i64))?,
3600            ),
3601            (
3602                Interval::make(Some(100_i64), Some(200_i64))?,
3603                Interval::make(Some(-2_i64), Some(-1_i64))?,
3604                Interval::make(Some(-200_i64), Some(-50_i64))?,
3605            ),
3606            (
3607                Interval::make(Some(-200_i64), Some(-100_i64))?,
3608                Interval::make(Some(1_i64), Some(2_i64))?,
3609                Interval::make(Some(-200_i64), Some(-50_i64))?,
3610            ),
3611            (
3612                Interval::make(Some(-200_i64), Some(100_i64))?,
3613                Interval::make(Some(1_i64), Some(2_i64))?,
3614                Interval::make(Some(-200_i64), Some(100_i64))?,
3615            ),
3616            (
3617                Interval::make(Some(-100_i64), Some(200_i64))?,
3618                Interval::make(Some(1_i64), Some(2_i64))?,
3619                Interval::make(Some(-100_i64), Some(200_i64))?,
3620            ),
3621            (
3622                Interval::make(Some(10_i64), Some(20_i64))?,
3623                Interval::make::<i64>(None, None)?,
3624                Interval::make::<i64>(None, None)?,
3625            ),
3626            (
3627                Interval::make(Some(-100_i64), Some(200_i64))?,
3628                Interval::make(Some(-1_i64), Some(2_i64))?,
3629                Interval::make::<i64>(None, None)?,
3630            ),
3631            (
3632                Interval::make(Some(-100_i64), Some(200_i64))?,
3633                Interval::make(Some(-2_i64), Some(1_i64))?,
3634                Interval::make::<i64>(None, None)?,
3635            ),
3636            (
3637                Interval::make(Some(100_i64), Some(200_i64))?,
3638                Interval::make(Some(0_i64), Some(1_i64))?,
3639                Interval::make(Some(100_i64), None)?,
3640            ),
3641            (
3642                Interval::make(Some(100_i64), Some(200_i64))?,
3643                Interval::make(None, Some(0_i64))?,
3644                Interval::make(None, Some(0_i64))?,
3645            ),
3646            (
3647                Interval::make(Some(100_i64), Some(200_i64))?,
3648                Interval::make(Some(0_i64), Some(0_i64))?,
3649                Interval::make::<i64>(None, None)?,
3650            ),
3651            (
3652                Interval::make(Some(0_i64), Some(1_i64))?,
3653                Interval::make(Some(100_i64), Some(200_i64))?,
3654                Interval::make(Some(0_i64), Some(0_i64))?,
3655            ),
3656            (
3657                Interval::make(Some(0_i64), Some(1_i64))?,
3658                Interval::make(Some(100_i64), Some(200_i64))?,
3659                Interval::make(Some(0_i64), Some(0_i64))?,
3660            ),
3661            (
3662                Interval::make(Some(1_u32), Some(2_u32))?,
3663                Interval::make(Some(0_u32), Some(0_u32))?,
3664                Interval::make::<u32>(None, None)?,
3665            ),
3666            (
3667                Interval::make(Some(10_u32), Some(20_u32))?,
3668                Interval::make(None, Some(2_u32))?,
3669                Interval::make(Some(5_u32), None)?,
3670            ),
3671            (
3672                Interval::make(Some(10_u32), Some(20_u32))?,
3673                Interval::make(Some(0_u32), Some(2_u32))?,
3674                Interval::make(Some(5_u32), None)?,
3675            ),
3676            (
3677                Interval::make(Some(10_u32), Some(20_u32))?,
3678                Interval::make(Some(0_u32), Some(0_u32))?,
3679                Interval::make::<u32>(None, None)?,
3680            ),
3681            (
3682                Interval::make(Some(12_u64), Some(48_u64))?,
3683                Interval::make(Some(10_u64), Some(20_u64))?,
3684                Interval::make(Some(0_u64), Some(4_u64))?,
3685            ),
3686            (
3687                Interval::make(Some(12_u64), Some(48_u64))?,
3688                Interval::make(None, Some(2_u64))?,
3689                Interval::make(Some(6_u64), None)?,
3690            ),
3691            (
3692                Interval::make(Some(12_u64), Some(48_u64))?,
3693                Interval::make(Some(0_u64), Some(2_u64))?,
3694                Interval::make(Some(6_u64), None)?,
3695            ),
3696            (
3697                Interval::make(None, Some(48_u64))?,
3698                Interval::make(Some(0_u64), Some(2_u64))?,
3699                Interval::make::<u64>(None, None)?,
3700            ),
3701            (
3702                Interval::make(Some(f32::MAX), Some(f32::MAX))?,
3703                Interval::make(Some(-0.1_f32), Some(0.1_f32))?,
3704                Interval::make::<f32>(None, None)?,
3705            ),
3706            (
3707                Interval::make(Some(f32::MIN), None)?,
3708                Interval::make(Some(0.1_f32), Some(0.1_f32))?,
3709                Interval::make::<f32>(None, None)?,
3710            ),
3711            (
3712                Interval::make(Some(-10.0_f32), Some(10.0_f32))?,
3713                Interval::make(Some(-0.1_f32), Some(-0.1_f32))?,
3714                Interval::make(Some(-100.0_f32), Some(100.0_f32))?,
3715            ),
3716            (
3717                Interval::make(Some(-10.0_f32), Some(f32::MAX))?,
3718                Interval::make::<f32>(None, None)?,
3719                Interval::make::<f32>(None, None)?,
3720            ),
3721            (
3722                Interval::make(Some(f32::MIN), Some(10.0_f32))?,
3723                Interval::make(Some(1.0_f32), None)?,
3724                Interval::make(Some(f32::MIN), Some(10.0_f32))?,
3725            ),
3726            (
3727                Interval::make(Some(-0.0_f32), Some(0.0_f32))?,
3728                Interval::make(Some(f32::MAX), None)?,
3729                Interval::make(Some(-0.0_f32), Some(0.0_f32))?,
3730            ),
3731            (
3732                Interval::make(Some(-0.0_f32), Some(0.0_f32))?,
3733                Interval::make(None, Some(-0.0_f32))?,
3734                Interval::make::<f32>(None, None)?,
3735            ),
3736            (
3737                Interval::make(Some(0.0_f32), Some(0.0_f32))?,
3738                Interval::make(Some(f32::MAX), None)?,
3739                Interval::make(Some(0.0_f32), Some(0.0_f32))?,
3740            ),
3741            (
3742                Interval::make(Some(1.0_f32), Some(2.0_f32))?,
3743                Interval::make(Some(0.0_f32), Some(4.0_f32))?,
3744                Interval::make(Some(0.25_f32), None)?,
3745            ),
3746            (
3747                Interval::make(Some(1.0_f32), Some(2.0_f32))?,
3748                Interval::make(Some(-4.0_f32), Some(-0.0_f32))?,
3749                Interval::make(None, Some(-0.25_f32))?,
3750            ),
3751            (
3752                Interval::make(Some(-4.0_f64), Some(2.0_f64))?,
3753                Interval::make(Some(10.0_f64), Some(20.0_f64))?,
3754                Interval::make(Some(-0.4_f64), Some(0.2_f64))?,
3755            ),
3756            (
3757                Interval::make(Some(-0.0_f64), Some(-0.0_f64))?,
3758                Interval::make(None, Some(-0.0_f64))?,
3759                Interval::make(Some(0.0_f64), None)?,
3760            ),
3761            (
3762                Interval::make(Some(1.0_f64), Some(2.0_f64))?,
3763                Interval::make::<f64>(None, None)?,
3764                Interval::make(Some(0.0_f64), None)?,
3765            ),
3766        ];
3767        for case in cases {
3768            let result = case.0.div(case.1)?;
3769            if case.0.data_type().is_floating() {
3770                assert!(
3771                    result.lower().is_null() && case.2.lower().is_null()
3772                        || result.lower().le(case.2.lower())
3773                );
3774                assert!(
3775                    result.upper().is_null() && case.2.upper().is_null()
3776                        || result.upper().ge(case.2.upper())
3777                );
3778            } else {
3779                assert_eq!(result, case.2);
3780            }
3781        }
3782
3783        Ok(())
3784    }
3785
3786    #[test]
3787    fn test_overflow_handling() -> Result<()> {
3788        // Test integer overflow handling:
3789        let dt = DataType::Int32;
3790        let op = Operator::Plus;
3791        let lhs = ScalarValue::Int32(Some(i32::MAX));
3792        let rhs = ScalarValue::Int32(Some(1));
3793        let result = handle_overflow::<true>(&dt, op, &lhs, &rhs);
3794        assert_eq!(result, ScalarValue::Int32(None));
3795        let result = handle_overflow::<false>(&dt, op, &lhs, &rhs);
3796        assert_eq!(result, ScalarValue::Int32(Some(i32::MAX)));
3797
3798        // Test float overflow handling:
3799        let dt = DataType::Float32;
3800        let op = Operator::Multiply;
3801        let lhs = ScalarValue::Float32(Some(f32::MAX));
3802        let rhs = ScalarValue::Float32(Some(2.0));
3803        let result = handle_overflow::<true>(&dt, op, &lhs, &rhs);
3804        assert_eq!(result, ScalarValue::Float32(None));
3805        let result = handle_overflow::<false>(&dt, op, &lhs, &rhs);
3806        assert_eq!(result, ScalarValue::Float32(Some(f32::MAX)));
3807
3808        // Test float underflow handling:
3809        let lhs = ScalarValue::Float32(Some(f32::MIN));
3810        let rhs = ScalarValue::Float32(Some(2.0));
3811        let result = handle_overflow::<true>(&dt, op, &lhs, &rhs);
3812        assert_eq!(result, ScalarValue::Float32(Some(f32::MIN)));
3813        let result = handle_overflow::<false>(&dt, op, &lhs, &rhs);
3814        assert_eq!(result, ScalarValue::Float32(None));
3815
3816        // Test integer underflow handling:
3817        let dt = DataType::Int64;
3818        let op = Operator::Minus;
3819        let lhs = ScalarValue::Int64(Some(i64::MIN));
3820        let rhs = ScalarValue::Int64(Some(1));
3821        let result = handle_overflow::<true>(&dt, op, &lhs, &rhs);
3822        assert_eq!(result, ScalarValue::Int64(Some(i64::MIN)));
3823        let result = handle_overflow::<false>(&dt, op, &lhs, &rhs);
3824        assert_eq!(result, ScalarValue::Int64(None));
3825
3826        // Test unsigned integer handling:
3827        let dt = DataType::UInt32;
3828        let op = Operator::Minus;
3829        let lhs = ScalarValue::UInt32(Some(0));
3830        let rhs = ScalarValue::UInt32(Some(1));
3831        let result = handle_overflow::<true>(&dt, op, &lhs, &rhs);
3832        assert_eq!(result, ScalarValue::UInt32(Some(0)));
3833        let result = handle_overflow::<false>(&dt, op, &lhs, &rhs);
3834        assert_eq!(result, ScalarValue::UInt32(None));
3835
3836        // Test decimal handling:
3837        let dt = DataType::Decimal128(38, 35);
3838        let op = Operator::Plus;
3839        let lhs =
3840            ScalarValue::Decimal128(Some(54321543215432154321543215432154321), 35, 35);
3841        let rhs = ScalarValue::Decimal128(Some(10000), 20, 0);
3842        let result = handle_overflow::<true>(&dt, op, &lhs, &rhs);
3843        assert_eq!(result, ScalarValue::Decimal128(None, 38, 35));
3844        let result = handle_overflow::<false>(&dt, op, &lhs, &rhs);
3845        assert_eq!(
3846            result,
3847            ScalarValue::Decimal128(Some(99999999999999999999999999999999999999), 38, 35)
3848        );
3849
3850        Ok(())
3851    }
3852
3853    #[test]
3854    fn test_width_of_intervals() -> Result<()> {
3855        let intervals = [
3856            (
3857                Interval::make(Some(0.25_f64), Some(0.50_f64))?,
3858                ScalarValue::from(0.25_f64),
3859            ),
3860            (
3861                Interval::make(Some(0.5_f64), Some(1.0_f64))?,
3862                ScalarValue::from(0.5_f64),
3863            ),
3864            (
3865                Interval::make(Some(1.0_f64), Some(2.0_f64))?,
3866                ScalarValue::from(1.0_f64),
3867            ),
3868            (
3869                Interval::make(Some(32.0_f64), Some(64.0_f64))?,
3870                ScalarValue::from(32.0_f64),
3871            ),
3872            (
3873                Interval::make(Some(-0.50_f64), Some(-0.25_f64))?,
3874                ScalarValue::from(0.25_f64),
3875            ),
3876            (
3877                Interval::make(Some(-32.0_f64), Some(-16.0_f64))?,
3878                ScalarValue::from(16.0_f64),
3879            ),
3880            (
3881                Interval::make(Some(-0.50_f64), Some(0.25_f64))?,
3882                ScalarValue::from(0.75_f64),
3883            ),
3884            (
3885                Interval::make(Some(-32.0_f64), Some(16.0_f64))?,
3886                ScalarValue::from(48.0_f64),
3887            ),
3888            (
3889                Interval::make(Some(-32_i64), Some(16_i64))?,
3890                ScalarValue::from(48_i64),
3891            ),
3892        ];
3893        for (interval, expected) in intervals {
3894            assert_eq!(interval.width()?, expected);
3895        }
3896
3897        Ok(())
3898    }
3899
3900    #[test]
3901    fn test_cardinality_of_intervals() -> Result<()> {
3902        // In IEEE 754 standard for floating-point arithmetic, if we keep the sign and exponent fields same,
3903        // we can represent 4503599627370496+1 different numbers by changing the mantissa
3904        // (4503599627370496 = 2^52, since there are 52 bits in mantissa, and 2^23 = 8388608 for f32).
3905        // TODO: Add tests for non-exponential boundary aligned intervals too.
3906        let distinct_f64 = 4503599627370497;
3907        let distinct_f32 = 8388609;
3908        let intervals = [
3909            Interval::make(Some(0.25_f64), Some(0.50_f64))?,
3910            Interval::make(Some(0.5_f64), Some(1.0_f64))?,
3911            Interval::make(Some(1.0_f64), Some(2.0_f64))?,
3912            Interval::make(Some(32.0_f64), Some(64.0_f64))?,
3913            Interval::make(Some(-0.50_f64), Some(-0.25_f64))?,
3914            Interval::make(Some(-32.0_f64), Some(-16.0_f64))?,
3915        ];
3916        for interval in intervals {
3917            assert_eq!(interval.cardinality().unwrap(), distinct_f64);
3918        }
3919
3920        let intervals = [
3921            Interval::make(Some(0.25_f32), Some(0.50_f32))?,
3922            Interval::make(Some(-1_f32), Some(-0.5_f32))?,
3923        ];
3924        for interval in intervals {
3925            assert_eq!(interval.cardinality().unwrap(), distinct_f32);
3926        }
3927
3928        // The regular logarithmic distribution of floating-point numbers are
3929        // only applicable outside of the `(-phi, phi)` interval where `phi`
3930        // denotes the largest positive subnormal floating-point number. Since
3931        // the following intervals include such subnormal points, we cannot use
3932        // a simple powers-of-two type formula for our expectations. Therefore,
3933        // we manually supply the actual expected cardinality.
3934        let interval = Interval::make(Some(-0.0625), Some(0.0625))?;
3935        assert_eq!(interval.cardinality().unwrap(), 9178336040581070850);
3936
3937        let interval = Interval::try_new(
3938            ScalarValue::UInt64(Some(1)),
3939            ScalarValue::UInt64(Some(u64::MAX)),
3940        )?;
3941        assert_eq!(interval.cardinality().unwrap(), u64::MAX);
3942
3943        let interval = Interval::try_new(
3944            ScalarValue::Int64(Some(i64::MIN + 1)),
3945            ScalarValue::Int64(Some(i64::MAX)),
3946        )?;
3947        assert_eq!(interval.cardinality().unwrap(), u64::MAX);
3948
3949        let interval = Interval::try_new(
3950            ScalarValue::Float32(Some(-0.0_f32)),
3951            ScalarValue::Float32(Some(0.0_f32)),
3952        )?;
3953        assert_eq!(interval.cardinality().unwrap(), 2);
3954
3955        Ok(())
3956    }
3957
3958    #[test]
3959    fn test_satisfy_comparison() -> Result<()> {
3960        let cases = vec![
3961            (
3962                Interval::make(Some(1000_i64), None)?,
3963                Interval::make(None, Some(1000_i64))?,
3964                true,
3965                Interval::make(Some(1000_i64), None)?,
3966                Interval::make(None, Some(1000_i64))?,
3967            ),
3968            (
3969                Interval::make(None, Some(1000_i64))?,
3970                Interval::make(Some(1000_i64), None)?,
3971                true,
3972                Interval::make(Some(1000_i64), Some(1000_i64))?,
3973                Interval::make(Some(1000_i64), Some(1000_i64))?,
3974            ),
3975            (
3976                Interval::make(Some(1000_i64), None)?,
3977                Interval::make(None, Some(1000_i64))?,
3978                false,
3979                Interval::make(Some(1000_i64), None)?,
3980                Interval::make(None, Some(1000_i64))?,
3981            ),
3982            (
3983                Interval::make(Some(0_i64), Some(1000_i64))?,
3984                Interval::make(Some(500_i64), Some(1500_i64))?,
3985                true,
3986                Interval::make(Some(500_i64), Some(1000_i64))?,
3987                Interval::make(Some(500_i64), Some(1000_i64))?,
3988            ),
3989            (
3990                Interval::make(Some(500_i64), Some(1500_i64))?,
3991                Interval::make(Some(0_i64), Some(1000_i64))?,
3992                true,
3993                Interval::make(Some(500_i64), Some(1500_i64))?,
3994                Interval::make(Some(0_i64), Some(1000_i64))?,
3995            ),
3996            (
3997                Interval::make(Some(0_i64), Some(1000_i64))?,
3998                Interval::make(Some(500_i64), Some(1500_i64))?,
3999                false,
4000                Interval::make(Some(501_i64), Some(1000_i64))?,
4001                Interval::make(Some(500_i64), Some(999_i64))?,
4002            ),
4003            (
4004                Interval::make(Some(500_i64), Some(1500_i64))?,
4005                Interval::make(Some(0_i64), Some(1000_i64))?,
4006                false,
4007                Interval::make(Some(500_i64), Some(1500_i64))?,
4008                Interval::make(Some(0_i64), Some(1000_i64))?,
4009            ),
4010            (
4011                Interval::make::<i64>(None, None)?,
4012                Interval::make(Some(1_i64), Some(1_i64))?,
4013                false,
4014                Interval::make(Some(2_i64), None)?,
4015                Interval::make(Some(1_i64), Some(1_i64))?,
4016            ),
4017            (
4018                Interval::make::<i64>(None, None)?,
4019                Interval::make(Some(1_i64), Some(1_i64))?,
4020                true,
4021                Interval::make(Some(1_i64), None)?,
4022                Interval::make(Some(1_i64), Some(1_i64))?,
4023            ),
4024            (
4025                Interval::make(Some(1_i64), Some(1_i64))?,
4026                Interval::make::<i64>(None, None)?,
4027                false,
4028                Interval::make(Some(1_i64), Some(1_i64))?,
4029                Interval::make(None, Some(0_i64))?,
4030            ),
4031            (
4032                Interval::make(Some(1_i64), Some(1_i64))?,
4033                Interval::make::<i64>(None, None)?,
4034                true,
4035                Interval::make(Some(1_i64), Some(1_i64))?,
4036                Interval::make(None, Some(1_i64))?,
4037            ),
4038            (
4039                Interval::make(Some(1_i64), Some(1_i64))?,
4040                Interval::make::<i64>(None, None)?,
4041                false,
4042                Interval::make(Some(1_i64), Some(1_i64))?,
4043                Interval::make(None, Some(0_i64))?,
4044            ),
4045            (
4046                Interval::make(Some(1_i64), Some(1_i64))?,
4047                Interval::make::<i64>(None, None)?,
4048                true,
4049                Interval::make(Some(1_i64), Some(1_i64))?,
4050                Interval::make(None, Some(1_i64))?,
4051            ),
4052            (
4053                Interval::make::<i64>(None, None)?,
4054                Interval::make(Some(1_i64), Some(1_i64))?,
4055                false,
4056                Interval::make(Some(2_i64), None)?,
4057                Interval::make(Some(1_i64), Some(1_i64))?,
4058            ),
4059            (
4060                Interval::make::<i64>(None, None)?,
4061                Interval::make(Some(1_i64), Some(1_i64))?,
4062                true,
4063                Interval::make(Some(1_i64), None)?,
4064                Interval::make(Some(1_i64), Some(1_i64))?,
4065            ),
4066            (
4067                Interval::make(Some(-1000.0_f32), Some(1000.0_f32))?,
4068                Interval::make(Some(-500.0_f32), Some(500.0_f32))?,
4069                false,
4070                Interval::try_new(
4071                    next_value(ScalarValue::Float32(Some(-500.0))),
4072                    ScalarValue::Float32(Some(1000.0)),
4073                )?,
4074                Interval::make(Some(-500_f32), Some(500.0_f32))?,
4075            ),
4076            (
4077                Interval::make(Some(-500.0_f32), Some(500.0_f32))?,
4078                Interval::make(Some(-1000.0_f32), Some(1000.0_f32))?,
4079                true,
4080                Interval::make(Some(-500.0_f32), Some(500.0_f32))?,
4081                Interval::make(Some(-1000.0_f32), Some(500.0_f32))?,
4082            ),
4083            (
4084                Interval::make(Some(-500.0_f32), Some(500.0_f32))?,
4085                Interval::make(Some(-1000.0_f32), Some(1000.0_f32))?,
4086                false,
4087                Interval::make(Some(-500.0_f32), Some(500.0_f32))?,
4088                Interval::try_new(
4089                    ScalarValue::Float32(Some(-1000.0_f32)),
4090                    prev_value(ScalarValue::Float32(Some(500.0_f32))),
4091                )?,
4092            ),
4093            (
4094                Interval::make(Some(-1000.0_f64), Some(1000.0_f64))?,
4095                Interval::make(Some(-500.0_f64), Some(500.0_f64))?,
4096                true,
4097                Interval::make(Some(-500.0_f64), Some(1000.0_f64))?,
4098                Interval::make(Some(-500.0_f64), Some(500.0_f64))?,
4099            ),
4100            (
4101                Interval::make(Some(0_i64), Some(0_i64))?,
4102                Interval::make(Some(-0_i64), Some(0_i64))?,
4103                true,
4104                Interval::make(Some(0_i64), Some(0_i64))?,
4105                Interval::make(Some(-0_i64), Some(0_i64))?,
4106            ),
4107            (
4108                Interval::make(Some(-0_i64), Some(0_i64))?,
4109                Interval::make(Some(-0_i64), Some(-0_i64))?,
4110                true,
4111                Interval::make(Some(-0_i64), Some(0_i64))?,
4112                Interval::make(Some(-0_i64), Some(-0_i64))?,
4113            ),
4114            (
4115                Interval::make(Some(0.0_f64), Some(0.0_f64))?,
4116                Interval::make(Some(-0.0_f64), Some(0.0_f64))?,
4117                true,
4118                Interval::make(Some(0.0_f64), Some(0.0_f64))?,
4119                Interval::make(Some(-0.0_f64), Some(0.0_f64))?,
4120            ),
4121            (
4122                Interval::make(Some(0.0_f64), Some(0.0_f64))?,
4123                Interval::make(Some(-0.0_f64), Some(0.0_f64))?,
4124                false,
4125                Interval::make(Some(0.0_f64), Some(0.0_f64))?,
4126                Interval::make(Some(-0.0_f64), Some(-0.0_f64))?,
4127            ),
4128            (
4129                Interval::make(Some(-0.0_f64), Some(0.0_f64))?,
4130                Interval::make(Some(-0.0_f64), Some(-0.0_f64))?,
4131                true,
4132                Interval::make(Some(-0.0_f64), Some(0.0_f64))?,
4133                Interval::make(Some(-0.0_f64), Some(-0.0_f64))?,
4134            ),
4135            (
4136                Interval::make(Some(-0.0_f64), Some(0.0_f64))?,
4137                Interval::make(Some(-0.0_f64), Some(-0.0_f64))?,
4138                false,
4139                Interval::make(Some(0.0_f64), Some(0.0_f64))?,
4140                Interval::make(Some(-0.0_f64), Some(-0.0_f64))?,
4141            ),
4142            (
4143                Interval::make(Some(0_i64), None)?,
4144                Interval::make(Some(-0_i64), None)?,
4145                true,
4146                Interval::make(Some(0_i64), None)?,
4147                Interval::make(Some(-0_i64), None)?,
4148            ),
4149            (
4150                Interval::make(Some(0_i64), None)?,
4151                Interval::make(Some(-0_i64), None)?,
4152                false,
4153                Interval::make(Some(1_i64), None)?,
4154                Interval::make(Some(-0_i64), None)?,
4155            ),
4156            (
4157                Interval::make(Some(0.0_f64), None)?,
4158                Interval::make(Some(-0.0_f64), None)?,
4159                true,
4160                Interval::make(Some(0.0_f64), None)?,
4161                Interval::make(Some(-0.0_f64), None)?,
4162            ),
4163            (
4164                Interval::make(Some(0.0_f64), None)?,
4165                Interval::make(Some(-0.0_f64), None)?,
4166                false,
4167                Interval::make(Some(0.0_f64), None)?,
4168                Interval::make(Some(-0.0_f64), None)?,
4169            ),
4170        ];
4171        for (first, second, includes_endpoints, left_modified, right_modified) in cases {
4172            assert_eq!(
4173                satisfy_greater(&first, &second, !includes_endpoints)?.unwrap(),
4174                (left_modified, right_modified)
4175            );
4176        }
4177
4178        let infeasible_cases = vec![
4179            (
4180                Interval::make(None, Some(1000_i64))?,
4181                Interval::make(Some(1000_i64), None)?,
4182                false,
4183            ),
4184            (
4185                Interval::make(Some(-1000.0_f32), Some(1000.0_f32))?,
4186                Interval::make(Some(1500.0_f32), Some(2000.0_f32))?,
4187                false,
4188            ),
4189            (
4190                Interval::make(Some(0_i64), Some(0_i64))?,
4191                Interval::make(Some(-0_i64), Some(0_i64))?,
4192                false,
4193            ),
4194            (
4195                Interval::make(Some(-0_i64), Some(0_i64))?,
4196                Interval::make(Some(-0_i64), Some(-0_i64))?,
4197                false,
4198            ),
4199        ];
4200        for (first, second, includes_endpoints) in infeasible_cases {
4201            assert_eq!(satisfy_greater(&first, &second, !includes_endpoints)?, None);
4202        }
4203
4204        Ok(())
4205    }
4206
4207    #[test]
4208    fn test_interval_display() {
4209        let interval = Interval::make(Some(0.25_f32), Some(0.50_f32)).unwrap();
4210        assert_eq!(format!("{interval}"), "[0.25, 0.5]");
4211
4212        let interval = Interval::try_new(
4213            ScalarValue::Float32(Some(f32::NEG_INFINITY)),
4214            ScalarValue::Float32(Some(f32::INFINITY)),
4215        )
4216        .unwrap();
4217        assert_eq!(format!("{interval}"), "[NULL, NULL]");
4218    }
4219
4220    macro_rules! capture_mode_change {
4221        ($TYPE:ty) => {
4222            paste::item! {
4223                capture_mode_change_helper!([<capture_mode_change_ $TYPE>],
4224                                            [<create_interval_ $TYPE>],
4225                                            $TYPE);
4226            }
4227        };
4228    }
4229
4230    macro_rules! capture_mode_change_helper {
4231        ($TEST_FN_NAME:ident, $CREATE_FN_NAME:ident, $TYPE:ty) => {
4232            fn $CREATE_FN_NAME(lower: $TYPE, upper: $TYPE) -> Interval {
4233                Interval::try_new(
4234                    ScalarValue::try_from(Some(lower as $TYPE)).unwrap(),
4235                    ScalarValue::try_from(Some(upper as $TYPE)).unwrap(),
4236                )
4237                .unwrap()
4238            }
4239
4240            fn $TEST_FN_NAME(input: ($TYPE, $TYPE), expect_low: bool, expect_high: bool) {
4241                assert!(expect_low || expect_high);
4242                let interval1 = $CREATE_FN_NAME(input.0, input.0);
4243                let interval2 = $CREATE_FN_NAME(input.1, input.1);
4244                let result = interval1.add(&interval2).unwrap();
4245                let without_fe = $CREATE_FN_NAME(input.0 + input.1, input.0 + input.1);
4246                assert!(
4247                    (!expect_low || result.lower < without_fe.lower)
4248                        && (!expect_high || result.upper > without_fe.upper)
4249                );
4250            }
4251        };
4252    }
4253
4254    capture_mode_change!(f32);
4255    capture_mode_change!(f64);
4256
4257    #[cfg(all(
4258        any(target_arch = "x86_64", target_arch = "aarch64"),
4259        not(target_os = "windows")
4260    ))]
4261    #[test]
4262    fn test_add_intervals_lower_affected_f32() {
4263        // Lower is affected
4264        let lower = f32::from_bits(1073741887); //1000000000000000000000000111111
4265        let upper = f32::from_bits(1098907651); //1000001100000000000000000000011
4266        capture_mode_change_f32((lower, upper), true, false);
4267
4268        // Upper is affected
4269        let lower = f32::from_bits(1072693248); //111111111100000000000000000000
4270        let upper = f32::from_bits(715827883); //101010101010101010101010101011
4271        capture_mode_change_f32((lower, upper), false, true);
4272
4273        // Lower is affected
4274        let lower = 1.0; // 0x3FF0000000000000
4275        let upper = 0.3; // 0x3FD3333333333333
4276        capture_mode_change_f64((lower, upper), true, false);
4277
4278        // Upper is affected
4279        let lower = 1.4999999999999998; // 0x3FF7FFFFFFFFFFFF
4280        let upper = 0.000_000_000_000_000_022_044_604_925_031_31; // 0x3C796A6B413BB21F
4281        capture_mode_change_f64((lower, upper), false, true);
4282    }
4283
4284    #[cfg(any(
4285        not(any(target_arch = "x86_64", target_arch = "aarch64")),
4286        target_os = "windows"
4287    ))]
4288    #[test]
4289    fn test_next_impl_add_intervals_f64() {
4290        let lower = 1.5;
4291        let upper = 1.5;
4292        capture_mode_change_f64((lower, upper), true, true);
4293
4294        let lower = 1.5;
4295        let upper = 1.5;
4296        capture_mode_change_f32((lower, upper), true, true);
4297    }
4298
4299    #[test]
4300    fn test_is_superset() -> Result<()> {
4301        // Test cases: (interval1, interval2, strict, expected)
4302        let test_cases = vec![
4303            // Equal intervals - non-strict should be true, strict should be false
4304            (
4305                Interval::make(Some(10_i32), Some(50_i32))?,
4306                Interval::make(Some(10_i32), Some(50_i32))?,
4307                false,
4308                true,
4309            ),
4310            (
4311                Interval::make(Some(10_i32), Some(50_i32))?,
4312                Interval::make(Some(10_i32), Some(50_i32))?,
4313                true,
4314                false,
4315            ),
4316            // Unbounded intervals
4317            (
4318                Interval::make::<i32>(None, None)?,
4319                Interval::make(Some(10_i32), Some(50_i32))?,
4320                false,
4321                true,
4322            ),
4323            (
4324                Interval::make::<i32>(None, None)?,
4325                Interval::make::<i32>(None, None)?,
4326                false,
4327                true,
4328            ),
4329            (
4330                Interval::make::<i32>(None, None)?,
4331                Interval::make::<i32>(None, None)?,
4332                true,
4333                false,
4334            ),
4335            // Half-bounded intervals
4336            (
4337                Interval::make(Some(0_i32), None)?,
4338                Interval::make(Some(10_i32), Some(50_i32))?,
4339                false,
4340                true,
4341            ),
4342            (
4343                Interval::make(None, Some(100_i32))?,
4344                Interval::make(Some(10_i32), Some(50_i32))?,
4345                false,
4346                true,
4347            ),
4348            // Non-superset cases - partial overlap
4349            (
4350                Interval::make(Some(0_i32), Some(50_i32))?,
4351                Interval::make(Some(25_i32), Some(75_i32))?,
4352                false,
4353                false,
4354            ),
4355            (
4356                Interval::make(Some(0_i32), Some(50_i32))?,
4357                Interval::make(Some(25_i32), Some(75_i32))?,
4358                true,
4359                false,
4360            ),
4361            // Non-superset cases - disjoint intervals
4362            (
4363                Interval::make(Some(0_i32), Some(50_i32))?,
4364                Interval::make(Some(60_i32), Some(100_i32))?,
4365                false,
4366                false,
4367            ),
4368            // Subset relationship (reversed)
4369            (
4370                Interval::make(Some(20_i32), Some(80_i32))?,
4371                Interval::make(Some(0_i32), Some(100_i32))?,
4372                false,
4373                false,
4374            ),
4375            // Float cases
4376            (
4377                Interval::make(Some(0.0_f32), Some(100.0_f32))?,
4378                Interval::make(Some(25.5_f32), Some(75.5_f32))?,
4379                false,
4380                true,
4381            ),
4382            (
4383                Interval::make(Some(0.0_f64), Some(100.0_f64))?,
4384                Interval::make(Some(0.0_f64), Some(100.0_f64))?,
4385                true,
4386                false,
4387            ),
4388            // Edge cases with single point intervals
4389            (
4390                Interval::make(Some(0_i32), Some(100_i32))?,
4391                Interval::make(Some(50_i32), Some(50_i32))?,
4392                false,
4393                true,
4394            ),
4395            (
4396                Interval::make(Some(50_i32), Some(50_i32))?,
4397                Interval::make(Some(50_i32), Some(50_i32))?,
4398                false,
4399                true,
4400            ),
4401            (
4402                Interval::make(Some(50_i32), Some(50_i32))?,
4403                Interval::make(Some(50_i32), Some(50_i32))?,
4404                true,
4405                false,
4406            ),
4407            // Boundary touch cases
4408            (
4409                Interval::make(Some(0_i32), Some(50_i32))?,
4410                Interval::make(Some(0_i32), Some(25_i32))?,
4411                false,
4412                true,
4413            ),
4414            (
4415                Interval::make(Some(0_i32), Some(50_i32))?,
4416                Interval::make(Some(25_i32), Some(50_i32))?,
4417                false,
4418                true,
4419            ),
4420        ];
4421
4422        for (interval1, interval2, strict, expected) in test_cases {
4423            let result = interval1.is_superset(&interval2, strict)?;
4424            assert_eq!(
4425                result, expected,
4426                "Failed for interval1: {interval1}, interval2: {interval2}, strict: {strict}",
4427            );
4428        }
4429
4430        Ok(())
4431    }
4432
4433    #[test]
4434    fn nullable_and_test() -> Result<()> {
4435        // Test cases: (lhs, rhs, expected) => lhs AND rhs = expected
4436        #[rustfmt::skip]
4437        let cases = vec![
4438            (NullableInterval::TRUE, NullableInterval::TRUE, NullableInterval::TRUE),
4439            (NullableInterval::TRUE, NullableInterval::FALSE, NullableInterval::FALSE),
4440            (NullableInterval::TRUE, NullableInterval::UNKNOWN, NullableInterval::UNKNOWN),
4441            (NullableInterval::TRUE, NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE_OR_FALSE),
4442            (NullableInterval::TRUE, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN),
4443            (NullableInterval::TRUE, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN),
4444            (NullableInterval::TRUE, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::ANY_TRUTH_VALUE),
4445            (NullableInterval::FALSE, NullableInterval::TRUE, NullableInterval::FALSE),
4446            (NullableInterval::FALSE, NullableInterval::FALSE, NullableInterval::FALSE),
4447            (NullableInterval::FALSE, NullableInterval::UNKNOWN, NullableInterval::FALSE),
4448            (NullableInterval::FALSE, NullableInterval::TRUE_OR_FALSE, NullableInterval::FALSE),
4449            (NullableInterval::FALSE, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::FALSE),
4450            (NullableInterval::FALSE, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE),
4451            (NullableInterval::FALSE, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::FALSE),
4452            (NullableInterval::UNKNOWN, NullableInterval::TRUE, NullableInterval::UNKNOWN),
4453            (NullableInterval::UNKNOWN, NullableInterval::FALSE, NullableInterval::FALSE),
4454            (NullableInterval::UNKNOWN, NullableInterval::UNKNOWN, NullableInterval::UNKNOWN),
4455            (NullableInterval::UNKNOWN, NullableInterval::TRUE_OR_FALSE, NullableInterval::FALSE_OR_UNKNOWN),
4456            (NullableInterval::UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::UNKNOWN),
4457            (NullableInterval::UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN),
4458            (NullableInterval::UNKNOWN, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::FALSE_OR_UNKNOWN),
4459            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::TRUE, NullableInterval::ANY_TRUTH_VALUE),
4460            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::FALSE, NullableInterval::FALSE),
4461            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN),
4462            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::TRUE_OR_FALSE, NullableInterval::ANY_TRUTH_VALUE),
4463            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::ANY_TRUTH_VALUE),
4464            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN),
4465            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::ANY_TRUTH_VALUE),
4466            (NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE, NullableInterval::TRUE_OR_FALSE),
4467            (NullableInterval::TRUE_OR_FALSE, NullableInterval::FALSE, NullableInterval::FALSE),
4468            (NullableInterval::TRUE_OR_FALSE, NullableInterval::UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN),
4469            (NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE_OR_FALSE),
4470            (NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::ANY_TRUTH_VALUE),
4471            (NullableInterval::TRUE_OR_FALSE, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN),
4472            (NullableInterval::TRUE_OR_FALSE, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::ANY_TRUTH_VALUE),
4473            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE, NullableInterval::TRUE_OR_UNKNOWN),
4474            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::FALSE, NullableInterval::FALSE),
4475            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::UNKNOWN, NullableInterval::UNKNOWN),
4476            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE_OR_FALSE, NullableInterval::ANY_TRUTH_VALUE),
4477            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN),
4478            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN),
4479            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::ANY_TRUTH_VALUE),
4480            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::TRUE, NullableInterval::FALSE_OR_UNKNOWN),
4481            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE, NullableInterval::FALSE),
4482            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN),
4483            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::TRUE_OR_FALSE, NullableInterval::FALSE_OR_UNKNOWN),
4484            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN),
4485            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN),
4486            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::FALSE_OR_UNKNOWN),
4487        ];
4488
4489        for case in cases {
4490            assert_eq!(
4491                case.0.apply_operator(&Operator::And, &case.1).unwrap(),
4492                case.2,
4493                "Failed for {} AND {}",
4494                case.0,
4495                case.1
4496            );
4497        }
4498        Ok(())
4499    }
4500
4501    #[test]
4502    fn nullable_or_test() -> Result<()> {
4503        // Test cases: (lhs, rhs, expected) => lhs OR rhs = expected
4504        #[rustfmt::skip]
4505        let cases = vec![
4506            (NullableInterval::TRUE, NullableInterval::TRUE, NullableInterval::TRUE),
4507            (NullableInterval::TRUE, NullableInterval::FALSE, NullableInterval::TRUE),
4508            (NullableInterval::TRUE, NullableInterval::UNKNOWN, NullableInterval::TRUE),
4509            (NullableInterval::TRUE, NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE),
4510            (NullableInterval::TRUE, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE),
4511            (NullableInterval::TRUE, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::TRUE),
4512            (NullableInterval::TRUE, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::TRUE),
4513            (NullableInterval::FALSE, NullableInterval::TRUE, NullableInterval::TRUE),
4514            (NullableInterval::FALSE, NullableInterval::FALSE, NullableInterval::FALSE),
4515            (NullableInterval::FALSE, NullableInterval::UNKNOWN, NullableInterval::UNKNOWN),
4516            (NullableInterval::FALSE, NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE_OR_FALSE),
4517            (NullableInterval::FALSE, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN),
4518            (NullableInterval::FALSE, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN),
4519            (NullableInterval::FALSE, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::ANY_TRUTH_VALUE),
4520            (NullableInterval::UNKNOWN, NullableInterval::TRUE, NullableInterval::TRUE),
4521            (NullableInterval::UNKNOWN, NullableInterval::FALSE, NullableInterval::UNKNOWN),
4522            (NullableInterval::UNKNOWN, NullableInterval::UNKNOWN, NullableInterval::UNKNOWN),
4523            (NullableInterval::UNKNOWN, NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE_OR_UNKNOWN),
4524            (NullableInterval::UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN),
4525            (NullableInterval::UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::UNKNOWN),
4526            (NullableInterval::UNKNOWN, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::TRUE_OR_UNKNOWN),
4527            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::TRUE, NullableInterval::TRUE),
4528            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::FALSE, NullableInterval::ANY_TRUTH_VALUE),
4529            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN),
4530            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::TRUE_OR_FALSE, NullableInterval::ANY_TRUTH_VALUE),
4531            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN),
4532            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::ANY_TRUTH_VALUE),
4533            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::ANY_TRUTH_VALUE),
4534            (NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE, NullableInterval::TRUE),
4535            (NullableInterval::TRUE_OR_FALSE, NullableInterval::FALSE, NullableInterval::TRUE_OR_FALSE),
4536            (NullableInterval::TRUE_OR_FALSE, NullableInterval::UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN),
4537            (NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE_OR_FALSE),
4538            (NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN),
4539            (NullableInterval::TRUE_OR_FALSE, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::ANY_TRUTH_VALUE),
4540            (NullableInterval::TRUE_OR_FALSE, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::ANY_TRUTH_VALUE),
4541            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE, NullableInterval::TRUE),
4542            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::FALSE, NullableInterval::TRUE_OR_UNKNOWN),
4543            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN),
4544            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE_OR_FALSE, NullableInterval::TRUE_OR_UNKNOWN),
4545            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN),
4546            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN),
4547            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::TRUE_OR_UNKNOWN),
4548            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::TRUE, NullableInterval::TRUE),
4549            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE, NullableInterval::FALSE_OR_UNKNOWN),
4550            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::UNKNOWN, NullableInterval::UNKNOWN),
4551            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::TRUE_OR_FALSE, NullableInterval::ANY_TRUTH_VALUE),
4552            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::TRUE_OR_UNKNOWN),
4553            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE_OR_UNKNOWN),
4554            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::ANY_TRUTH_VALUE, NullableInterval::ANY_TRUTH_VALUE),
4555        ];
4556
4557        for case in cases {
4558            assert_eq!(
4559                case.0.apply_operator(&Operator::Or, &case.1).unwrap(),
4560                case.2,
4561                "Failed for {} OR {}",
4562                case.0,
4563                case.1
4564            );
4565        }
4566        Ok(())
4567    }
4568
4569    #[test]
4570    fn nullable_not_test() -> Result<()> {
4571        // Test cases: (interval, expected) => NOT interval = expected
4572        #[rustfmt::skip]
4573        let cases = vec![
4574            (NullableInterval::TRUE, NullableInterval::FALSE),
4575            (NullableInterval::FALSE, NullableInterval::TRUE),
4576            (NullableInterval::UNKNOWN, NullableInterval::UNKNOWN),
4577            (NullableInterval::TRUE_OR_FALSE,NullableInterval::TRUE_OR_FALSE),
4578            (NullableInterval::TRUE_OR_UNKNOWN,NullableInterval::FALSE_OR_UNKNOWN),
4579            (NullableInterval::FALSE_OR_UNKNOWN,NullableInterval::TRUE_OR_UNKNOWN),
4580            (NullableInterval::ANY_TRUTH_VALUE, NullableInterval::ANY_TRUTH_VALUE),
4581        ];
4582
4583        for case in cases {
4584            assert_eq!(case.0.not().unwrap(), case.1, "Failed for NOT {}", case.0,);
4585        }
4586        Ok(())
4587    }
4588
4589    #[test]
4590    fn nullable_interval_is_certainly_true() {
4591        // Test cases: (interval, expected) => interval.is_certainly_true() = expected
4592        #[rustfmt::skip]
4593        let test_cases = vec![
4594            (NullableInterval::TRUE, true),
4595            (NullableInterval::FALSE, false),
4596            (NullableInterval::UNKNOWN, false),
4597            (NullableInterval::TRUE_OR_FALSE, false),
4598            (NullableInterval::TRUE_OR_UNKNOWN, false),
4599            (NullableInterval::FALSE_OR_UNKNOWN, false),
4600            (NullableInterval::ANY_TRUTH_VALUE, false),
4601        ];
4602
4603        for (interval, expected) in test_cases {
4604            let result = interval.is_certainly_true();
4605            assert_eq!(result, expected, "Failed for interval: {interval}",);
4606        }
4607    }
4608
4609    #[test]
4610    fn nullable_interval_is_true() {
4611        // Test cases: (interval, expected) => interval.is_true() = expected
4612        #[rustfmt::skip]
4613        let test_cases = vec![
4614            (NullableInterval::TRUE, NullableInterval::TRUE),
4615            (NullableInterval::FALSE, NullableInterval::FALSE),
4616            (NullableInterval::UNKNOWN, NullableInterval::FALSE),
4617            (NullableInterval::TRUE_OR_FALSE,NullableInterval::TRUE_OR_FALSE),
4618            (NullableInterval::TRUE_OR_UNKNOWN,NullableInterval::TRUE_OR_FALSE),
4619            (NullableInterval::FALSE_OR_UNKNOWN, NullableInterval::FALSE),
4620            (NullableInterval::ANY_TRUTH_VALUE,NullableInterval::TRUE_OR_FALSE),
4621        ];
4622
4623        for (interval, expected) in test_cases {
4624            let result = interval.is_true().unwrap();
4625            assert_eq!(result, expected, "Failed for interval: {interval}",);
4626        }
4627    }
4628
4629    #[test]
4630    fn nullable_interval_is_certainly_false() {
4631        // Test cases: (interval, expected) => interval.is_certainly_false() = expected
4632        #[rustfmt::skip]
4633        let test_cases = vec![
4634            (NullableInterval::TRUE, false),
4635            (NullableInterval::FALSE, true),
4636            (NullableInterval::UNKNOWN, false),
4637            (NullableInterval::TRUE_OR_FALSE, false),
4638            (NullableInterval::TRUE_OR_UNKNOWN, false),
4639            (NullableInterval::FALSE_OR_UNKNOWN, false),
4640            (NullableInterval::ANY_TRUTH_VALUE, false),
4641        ];
4642
4643        for (interval, expected) in test_cases {
4644            let result = interval.is_certainly_false();
4645            assert_eq!(result, expected, "Failed for interval: {interval}",);
4646        }
4647    }
4648
4649    #[test]
4650    fn nullable_interval_is_false() {
4651        // Test cases: (interval, expected) => interval.is_false() = expected
4652        #[rustfmt::skip]
4653        let test_cases = vec![
4654            (NullableInterval::TRUE, NullableInterval::FALSE),
4655            (NullableInterval::FALSE, NullableInterval::TRUE),
4656            (NullableInterval::UNKNOWN, NullableInterval::FALSE),
4657            (NullableInterval::TRUE_OR_FALSE,NullableInterval::TRUE_OR_FALSE),
4658            (NullableInterval::TRUE_OR_UNKNOWN, NullableInterval::FALSE),
4659            (NullableInterval::FALSE_OR_UNKNOWN,NullableInterval::TRUE_OR_FALSE),
4660            (NullableInterval::ANY_TRUTH_VALUE,NullableInterval::TRUE_OR_FALSE),
4661        ];
4662
4663        for (interval, expected) in test_cases {
4664            let result = interval.is_false().unwrap();
4665            assert_eq!(result, expected, "Failed for interval: {interval}",);
4666        }
4667    }
4668
4669    #[test]
4670    fn nullable_interval_is_certainly_unknown() {
4671        // Test cases: (interval, expected) => interval.is_certainly_unknown() = expected
4672        #[rustfmt::skip]
4673        let test_cases = vec![
4674            (NullableInterval::TRUE, false),
4675            (NullableInterval::FALSE, false),
4676            (NullableInterval::UNKNOWN, true),
4677            (NullableInterval::TRUE_OR_FALSE, false),
4678            (NullableInterval::TRUE_OR_UNKNOWN, false),
4679            (NullableInterval::FALSE_OR_UNKNOWN, false),
4680            (NullableInterval::ANY_TRUTH_VALUE, false),
4681        ];
4682
4683        for (interval, expected) in test_cases {
4684            let result = interval.is_certainly_unknown();
4685            assert_eq!(result, expected, "Failed for interval: {interval}",);
4686        }
4687    }
4688
4689    #[test]
4690    fn nullable_interval_is_unknown() {
4691        // Test cases: (interval, expected) => interval.is_unknown() = expected
4692        #[rustfmt::skip]
4693        let test_cases = vec![
4694            (NullableInterval::TRUE, NullableInterval::FALSE),
4695            (NullableInterval::FALSE, NullableInterval::FALSE),
4696            (NullableInterval::UNKNOWN, NullableInterval::TRUE),
4697            (NullableInterval::TRUE_OR_FALSE, NullableInterval::FALSE),
4698            (NullableInterval::TRUE_OR_UNKNOWN,NullableInterval::TRUE_OR_FALSE),
4699            (NullableInterval::FALSE_OR_UNKNOWN,NullableInterval::TRUE_OR_FALSE),
4700            (NullableInterval::ANY_TRUTH_VALUE,NullableInterval::TRUE_OR_FALSE),
4701        ];
4702
4703        for (interval, expected) in test_cases {
4704            let result = interval.is_unknown().unwrap();
4705            assert_eq!(result, expected, "Failed for interval: {interval}",);
4706        }
4707    }
4708
4709    #[test]
4710    fn nullable_interval_contains_value() {
4711        // Test cases: (interval, value, expected) => interval.contains_value(value) = expected
4712        #[rustfmt::skip]
4713        let test_cases = vec![
4714            (NullableInterval::TRUE, ScalarValue::Boolean(Some(true)), true),
4715            (NullableInterval::TRUE, ScalarValue::Boolean(Some(false)), false),
4716            (NullableInterval::TRUE, ScalarValue::Boolean(None), false),
4717            (NullableInterval::TRUE, ScalarValue::Null, false),
4718            (NullableInterval::TRUE, ScalarValue::UInt32(None), false),
4719            (NullableInterval::FALSE, ScalarValue::Boolean(Some(true)), false),
4720            (NullableInterval::FALSE, ScalarValue::Boolean(Some(false)), true),
4721            (NullableInterval::FALSE, ScalarValue::Boolean(None), false),
4722            (NullableInterval::FALSE, ScalarValue::Null, false),
4723            (NullableInterval::FALSE, ScalarValue::UInt32(None), false),
4724            (NullableInterval::UNKNOWN, ScalarValue::Boolean(Some(true)), false),
4725            (NullableInterval::UNKNOWN, ScalarValue::Boolean(Some(false)), false),
4726            (NullableInterval::UNKNOWN, ScalarValue::Boolean(None), true),
4727            (NullableInterval::UNKNOWN, ScalarValue::Null, true),
4728            (NullableInterval::UNKNOWN, ScalarValue::UInt32(None), false),
4729            (NullableInterval::TRUE_OR_FALSE, ScalarValue::Boolean(Some(true)), true),
4730            (NullableInterval::TRUE_OR_FALSE, ScalarValue::Boolean(Some(false)), true),
4731            (NullableInterval::TRUE_OR_FALSE, ScalarValue::Boolean(None), false),
4732            (NullableInterval::TRUE_OR_FALSE, ScalarValue::Null, false),
4733            (NullableInterval::TRUE_OR_FALSE, ScalarValue::UInt32(None), false),
4734            (NullableInterval::TRUE_OR_UNKNOWN, ScalarValue::Boolean(Some(true)), true),
4735            (NullableInterval::TRUE_OR_UNKNOWN, ScalarValue::Boolean(Some(false)), false),
4736            (NullableInterval::TRUE_OR_UNKNOWN, ScalarValue::Boolean(None), true),
4737            (NullableInterval::TRUE_OR_UNKNOWN, ScalarValue::Null, true),
4738            (NullableInterval::TRUE_OR_UNKNOWN, ScalarValue::UInt32(None), false),
4739            (NullableInterval::FALSE_OR_UNKNOWN, ScalarValue::Boolean(Some(true)), false),
4740            (NullableInterval::FALSE_OR_UNKNOWN, ScalarValue::Boolean(Some(false)), true),
4741            (NullableInterval::FALSE_OR_UNKNOWN, ScalarValue::Boolean(None), true),
4742            (NullableInterval::FALSE_OR_UNKNOWN, ScalarValue::Null, true),
4743            (NullableInterval::FALSE_OR_UNKNOWN, ScalarValue::UInt32(None), false),
4744            (NullableInterval::ANY_TRUTH_VALUE, ScalarValue::Boolean(Some(true)), true),
4745            (NullableInterval::ANY_TRUTH_VALUE, ScalarValue::Boolean(Some(false)), true),
4746            (NullableInterval::ANY_TRUTH_VALUE, ScalarValue::Boolean(None), true),
4747            (NullableInterval::ANY_TRUTH_VALUE, ScalarValue::Null, true),
4748            (NullableInterval::ANY_TRUTH_VALUE, ScalarValue::UInt32(None), false),
4749        ];
4750
4751        for (interval, value, expected) in test_cases {
4752            let result = interval.contains_value(value.clone()).unwrap();
4753            assert_eq!(
4754                result, expected,
4755                "Failed for interval: {interval} and value {value:?}",
4756            );
4757        }
4758    }
4759}