Skip to main content

vortex_array/scalar_fn/fns/
operators.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use core::fmt;
5use std::fmt::Display;
6use std::fmt::Formatter;
7
8use vortex_error::VortexError;
9
10use crate::dtype::NativePType;
11use crate::proto::expr::binary_opts::BinaryOp;
12
13/// Equalities, inequalities, and boolean operations over possibly null values.
14///
15/// For most operations, if either side is null, the result is null.
16///
17/// The Boolean operators (And, Or) obey [Kleene (three-valued) logic](https://en.wikipedia.org/wiki/Three-valued_logic#Kleene_and_Priest_logics).
18#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Hash)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20pub enum Operator {
21    /// Expressions are equal.
22    Eq,
23    /// Expressions are not equal.
24    NotEq,
25    /// Expression is greater than another
26    Gt,
27    /// Expression is greater or equal to another
28    Gte,
29    /// Expression is less than another
30    Lt,
31    /// Expression is less or equal to another
32    Lte,
33    /// Boolean AND (∧).
34    // TODO(joe): rename to KleeneAnd
35    And,
36    /// Boolean OR (∨).
37    // TODO(joe): rename to KleeneOr
38    Or,
39    /// The sum of the arguments.
40    ///
41    /// Errs at runtime if the sum would overflow or underflow.
42    Add,
43    /// The difference between the arguments.
44    ///
45    /// Errs at runtime if the sum would overflow or underflow.
46    ///
47    /// The result is null at any index that either input is null.
48    Sub,
49    /// Multiple two numbers
50    Mul,
51    /// Divide the left side by the right side
52    Div,
53}
54
55impl From<Operator> for i32 {
56    fn from(value: Operator) -> Self {
57        let op: BinaryOp = value.into();
58        op.into()
59    }
60}
61
62impl From<Operator> for BinaryOp {
63    fn from(value: Operator) -> Self {
64        match value {
65            Operator::Eq => BinaryOp::Eq,
66            Operator::NotEq => BinaryOp::NotEq,
67            Operator::Gt => BinaryOp::Gt,
68            Operator::Gte => BinaryOp::Gte,
69            Operator::Lt => BinaryOp::Lt,
70            Operator::Lte => BinaryOp::Lte,
71            Operator::And => BinaryOp::And,
72            Operator::Or => BinaryOp::Or,
73            Operator::Add => BinaryOp::Add,
74            Operator::Sub => BinaryOp::Sub,
75            Operator::Mul => BinaryOp::Mul,
76            Operator::Div => BinaryOp::Div,
77        }
78    }
79}
80
81impl TryFrom<i32> for Operator {
82    type Error = VortexError;
83
84    fn try_from(value: i32) -> Result<Self, Self::Error> {
85        Ok(BinaryOp::try_from(value)?.into())
86    }
87}
88
89impl From<BinaryOp> for Operator {
90    fn from(value: BinaryOp) -> Self {
91        match value {
92            BinaryOp::Eq => Operator::Eq,
93            BinaryOp::NotEq => Operator::NotEq,
94            BinaryOp::Gt => Operator::Gt,
95            BinaryOp::Gte => Operator::Gte,
96            BinaryOp::Lt => Operator::Lt,
97            BinaryOp::Lte => Operator::Lte,
98            BinaryOp::And => Operator::And,
99            BinaryOp::Or => Operator::Or,
100            BinaryOp::Add => Operator::Add,
101            BinaryOp::Sub => Operator::Sub,
102            BinaryOp::Mul => Operator::Mul,
103            BinaryOp::Div => Operator::Div,
104        }
105    }
106}
107
108impl Display for Operator {
109    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
110        let display = match &self {
111            Operator::Eq => "=",
112            Operator::NotEq => "!=",
113            Operator::Gt => ">",
114            Operator::Gte => ">=",
115            Operator::Lt => "<",
116            Operator::Lte => "<=",
117            Operator::And => "and",
118            Operator::Or => "or",
119            Operator::Add => "+",
120            Operator::Sub => "-",
121            Operator::Mul => "*",
122            Operator::Div => "/",
123        };
124        Display::fmt(display, f)
125    }
126}
127
128impl Operator {
129    pub fn inverse(self) -> Option<Self> {
130        match self {
131            Operator::Eq => Some(Operator::NotEq),
132            Operator::NotEq => Some(Operator::Eq),
133            Operator::Gt => Some(Operator::Lte),
134            Operator::Gte => Some(Operator::Lt),
135            Operator::Lt => Some(Operator::Gte),
136            Operator::Lte => Some(Operator::Gt),
137            Operator::And
138            | Operator::Or
139            | Operator::Add
140            | Operator::Sub
141            | Operator::Mul
142            | Operator::Div => None,
143        }
144    }
145
146    pub fn logical_inverse(self) -> Option<Self> {
147        match self {
148            Operator::And => Some(Operator::Or),
149            Operator::Or => Some(Operator::And),
150            _ => None,
151        }
152    }
153
154    /// Change the sides of the operator, so that changing lhs and rhs won't change the result of the operation
155    pub fn swap(self) -> Option<Self> {
156        match self {
157            Operator::Eq => Some(Operator::Eq),
158            Operator::NotEq => Some(Operator::NotEq),
159            Operator::Gt => Some(Operator::Lt),
160            Operator::Gte => Some(Operator::Lte),
161            Operator::Lt => Some(Operator::Gt),
162            Operator::Lte => Some(Operator::Gte),
163            Operator::And => Some(Operator::And),
164            Operator::Or => Some(Operator::Or),
165            Operator::Add => Some(Operator::Add),
166            Operator::Mul => Some(Operator::Mul),
167            Operator::Sub | Operator::Div => None,
168        }
169    }
170
171    pub fn is_arithmetic(&self) -> bool {
172        matches!(self, Self::Add | Self::Sub | Self::Mul | Self::Div)
173    }
174
175    pub fn is_comparison(&self) -> bool {
176        self.to_compare_operator().is_some()
177    }
178
179    /// Return the [`CompareOperator`] for this operator, or `None` if it is not a comparison.
180    ///
181    /// Prefer this over [`CompareOperator::try_from`] when a non-comparison operator is an expected
182    /// case, since it does not construct an error.
183    pub fn to_compare_operator(self) -> Option<CompareOperator> {
184        match self {
185            Operator::Eq => Some(CompareOperator::Eq),
186            Operator::NotEq => Some(CompareOperator::NotEq),
187            Operator::Gt => Some(CompareOperator::Gt),
188            Operator::Gte => Some(CompareOperator::Gte),
189            Operator::Lt => Some(CompareOperator::Lt),
190            Operator::Lte => Some(CompareOperator::Lte),
191            Operator::And
192            | Operator::Or
193            | Operator::Add
194            | Operator::Sub
195            | Operator::Mul
196            | Operator::Div => None,
197        }
198    }
199}
200
201/// The six comparison operators, providing compile-time guarantees that only
202/// comparison variants are used where comparisons are expected.
203#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Hash)]
204#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
205pub enum CompareOperator {
206    /// Expressions are equal.
207    Eq,
208    /// Expressions are not equal.
209    NotEq,
210    /// Expression is greater than another.
211    Gt,
212    /// Expression is greater or equal to another.
213    Gte,
214    /// Expression is less than another.
215    Lt,
216    /// Expression is less or equal to another.
217    Lte,
218}
219
220impl CompareOperator {
221    /// Return the logical inverse of this comparison operator.
222    pub fn inverse(self) -> Self {
223        match self {
224            CompareOperator::Eq => CompareOperator::NotEq,
225            CompareOperator::NotEq => CompareOperator::Eq,
226            CompareOperator::Gt => CompareOperator::Lte,
227            CompareOperator::Gte => CompareOperator::Lt,
228            CompareOperator::Lt => CompareOperator::Gte,
229            CompareOperator::Lte => CompareOperator::Gt,
230        }
231    }
232
233    /// Swap the sides of the operator so that swapping lhs and rhs preserves the result.
234    pub fn swap(self) -> Self {
235        match self {
236            CompareOperator::Eq => CompareOperator::Eq,
237            CompareOperator::NotEq => CompareOperator::NotEq,
238            CompareOperator::Gt => CompareOperator::Lt,
239            CompareOperator::Gte => CompareOperator::Lte,
240            CompareOperator::Lt => CompareOperator::Gt,
241            CompareOperator::Lte => CompareOperator::Gte,
242        }
243    }
244
245    /// Returns the total-order comparison that this operator applies to two native values.
246    pub fn to_predicate<T: NativePType>(self) -> fn(T, T) -> bool {
247        match self {
248            CompareOperator::Eq => T::is_eq,
249            CompareOperator::NotEq => |lhs, rhs| !lhs.is_eq(rhs),
250            CompareOperator::Gt => T::is_gt,
251            CompareOperator::Gte => T::is_ge,
252            CompareOperator::Lt => T::is_lt,
253            CompareOperator::Lte => T::is_le,
254        }
255    }
256}
257
258impl Display for CompareOperator {
259    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
260        let display = match self {
261            CompareOperator::Eq => "=",
262            CompareOperator::NotEq => "!=",
263            CompareOperator::Gt => ">",
264            CompareOperator::Gte => ">=",
265            CompareOperator::Lt => "<",
266            CompareOperator::Lte => "<=",
267        };
268        Display::fmt(display, f)
269    }
270}
271
272impl From<CompareOperator> for Operator {
273    fn from(value: CompareOperator) -> Self {
274        match value {
275            CompareOperator::Eq => Operator::Eq,
276            CompareOperator::NotEq => Operator::NotEq,
277            CompareOperator::Gt => Operator::Gt,
278            CompareOperator::Gte => Operator::Gte,
279            CompareOperator::Lt => Operator::Lt,
280            CompareOperator::Lte => Operator::Lte,
281        }
282    }
283}
284
285impl TryFrom<Operator> for CompareOperator {
286    type Error = VortexError;
287
288    fn try_from(value: Operator) -> Result<Self, Self::Error> {
289        value
290            .to_compare_operator()
291            .ok_or_else(|| vortex_error::vortex_err!("{value} is not a comparison operator"))
292    }
293}
294
295#[cfg(feature = "arbitrary")]
296impl<'a> arbitrary::Arbitrary<'a> for CompareOperator {
297    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
298        Ok(match u.int_in_range(0..=5)? {
299            0 => CompareOperator::Eq,
300            1 => CompareOperator::NotEq,
301            2 => CompareOperator::Gt,
302            3 => CompareOperator::Gte,
303            4 => CompareOperator::Lt,
304            5 => CompareOperator::Lte,
305            _ => unreachable!(),
306        })
307    }
308}