Skip to main content

vortex_array/scalar_fn/fns/not/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod kernel;
5
6pub use kernel::*;
7use vortex_error::VortexResult;
8use vortex_error::vortex_bail;
9use vortex_error::vortex_panic;
10use vortex_session::VortexSession;
11use vortex_session::registry::CachedId;
12
13use crate::AnyColumnar;
14use crate::ArrayRef;
15use crate::ExecutionCtx;
16use crate::IntoArray;
17use crate::arrays::Bool;
18use crate::arrays::BoolArray;
19use crate::arrays::ConstantArray;
20use crate::arrays::ScalarFnArray;
21use crate::arrays::bool::BoolArrayExt;
22use crate::dtype::DType;
23use crate::scalar::Scalar;
24use crate::scalar_fn::Arity;
25use crate::scalar_fn::ChildName;
26use crate::scalar_fn::EmptyOptions;
27use crate::scalar_fn::ExecutionArgs;
28use crate::scalar_fn::ScalarFnExecutionResult;
29use crate::scalar_fn::ScalarFnId;
30use crate::scalar_fn::ScalarFnVTable;
31use crate::scalar_fn::ScalarFnVTableExt;
32
33/// Expression that logically inverts boolean values.
34#[derive(Clone)]
35pub struct Not;
36
37impl Not {
38    /// Creates a lazy boolean inversion of `input`.
39    ///
40    /// # Errors
41    ///
42    /// Returns an error if `input` is not boolean data.
43    pub fn try_new(input: ArrayRef) -> VortexResult<ScalarFnArray> {
44        ScalarFnArray::try_new(Not.bind(EmptyOptions), [input])
45    }
46}
47
48impl ScalarFnVTable for Not {
49    type Options = EmptyOptions;
50
51    fn id(&self) -> ScalarFnId {
52        static ID: CachedId = CachedId::new("vortex.not");
53        *ID
54    }
55
56    fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
57        Ok(Some(vec![]))
58    }
59
60    fn deserialize(
61        &self,
62        _metadata: &[u8],
63        _session: &VortexSession,
64    ) -> VortexResult<Self::Options> {
65        Ok(EmptyOptions)
66    }
67
68    fn arity(&self, _options: &Self::Options) -> Arity {
69        Arity::Exact(1)
70    }
71
72    fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
73        match child_idx {
74            0 => ChildName::from("input"),
75            _ => unreachable!("Invalid child index {} for Not expression", child_idx),
76        }
77    }
78
79    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
80        let child_dtype = &arg_dtypes[0];
81        if !matches!(child_dtype, DType::Bool(_)) {
82            vortex_bail!(
83                "Not expression expects a boolean child, got: {}",
84                child_dtype
85            );
86        }
87        Ok(child_dtype.clone())
88    }
89
90    fn execute(
91        &self,
92        _options: &Self::Options,
93        _args: &dyn ExecutionArgs,
94        _ctx: &mut ExecutionCtx,
95    ) -> VortexResult<ArrayRef> {
96        vortex_panic!("Not implements execute_step, so execute is never called")
97    }
98
99    fn execute_step(
100        &self,
101        _data: &Self::Options,
102        args: &dyn ExecutionArgs,
103        _ctx: &mut ExecutionCtx,
104    ) -> VortexResult<ScalarFnExecutionResult> {
105        match not_columnar(&args.get(0)?, args.row_count())? {
106            Some(result) => Ok(ScalarFnExecutionResult::done(result)),
107            None => Ok(ScalarFnExecutionResult::execute_input::<AnyColumnar>(0)),
108        }
109    }
110
111    fn is_strict(&self, _options: &Self::Options) -> bool {
112        true
113    }
114
115    fn is_infallible(&self, _options: &Self::Options) -> bool {
116        true
117    }
118}
119
120/// Inverts a constant or canonical boolean `child`, returning `None` for any other encoding.
121fn not_columnar(child: &ArrayRef, row_count: usize) -> VortexResult<Option<ArrayRef>> {
122    if let Some(scalar) = child.as_constant() {
123        let value = match scalar.as_bool().value() {
124            Some(b) => Scalar::bool(!b, child.dtype().nullability()),
125            None => Scalar::null(child.dtype().clone()),
126        };
127        return Ok(Some(ConstantArray::new(value, row_count).into_array()));
128    }
129
130    if let Some(bool) = child.as_opt::<Bool>() {
131        return Ok(Some(
132            BoolArray::new(!bool.to_bit_buffer(), bool.validity()?).into_array(),
133        ));
134    }
135
136    Ok(None)
137}
138
139#[cfg(test)]
140mod tests {
141    use std::sync::LazyLock;
142
143    use vortex_error::VortexResult;
144    use vortex_session::VortexSession;
145
146    use crate::Canonical;
147    use crate::IntoArray;
148    use crate::VortexSessionExecute;
149    use crate::arrays::ChunkedArray;
150    use crate::assert_arrays_eq;
151    use crate::dtype::DType;
152    use crate::dtype::Nullability;
153    use crate::expr::col;
154    use crate::expr::get_item;
155    use crate::expr::not;
156    use crate::expr::root;
157    use crate::expr::test_harness;
158    use crate::scalar_fn::fns::not::BoolArray;
159    use crate::scalar_fn::fns::not::Not;
160
161    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
162
163    #[test]
164    fn is_strict() {
165        assert!(
166            not(root())
167                .as_scalar()
168                .is_some_and(|f| f.signature().is_strict())
169        );
170    }
171
172    #[test]
173    fn executes_non_columnar_input_iteratively() -> VortexResult<()> {
174        let mut ctx = SESSION.create_execution_ctx();
175        let chunks = vec![
176            BoolArray::from_iter([Some(true), None]).into_array(),
177            BoolArray::from_iter([Some(false)]).into_array(),
178        ];
179        let dtype = chunks[0].dtype().clone();
180        let chunked = ChunkedArray::try_new(chunks, dtype)?.into_array();
181        let nested = Not::try_new(Not::try_new(Not::try_new(chunked)?.into_array())?.into_array())?;
182
183        let result = nested.into_array().execute::<Canonical>(&mut ctx)?;
184
185        assert_arrays_eq!(
186            result.into_array(),
187            BoolArray::from_iter([Some(false), None, Some(true)]),
188            &mut ctx
189        );
190        Ok(())
191    }
192
193    #[test]
194    fn preserves_nulls() -> VortexResult<()> {
195        let mut ctx = SESSION.create_execution_ctx();
196        let input = BoolArray::from_iter([Some(false), None, Some(true)]).into_array();
197
198        let result = input.apply(&not(root()))?;
199
200        assert_arrays_eq!(
201            result,
202            BoolArray::from_iter([Some(true), None, Some(false)]),
203            &mut ctx
204        );
205        Ok(())
206    }
207
208    #[test]
209    fn invert_booleans() {
210        let mut ctx = SESSION.create_execution_ctx();
211        let not_expr = not(root());
212        let bools = BoolArray::from_iter([false, true, false, false, true, true]);
213        let result = bools.into_array().apply(&not_expr).unwrap();
214        assert_arrays_eq!(
215            result,
216            BoolArray::from_iter([true, false, true, true, false, false]),
217            &mut ctx
218        );
219    }
220
221    #[test]
222    fn test_display_order_of_operations() {
223        let a = not(get_item("a", root()));
224        let b = get_item("a", not(root()));
225        assert_ne!(a.to_string(), b.to_string());
226        assert_eq!(a.to_string(), "vortex.not($.a)");
227        assert_eq!(b.to_string(), "vortex.not($).a");
228    }
229
230    #[test]
231    fn dtype() {
232        let not_expr = not(root());
233        let dtype = DType::Bool(Nullability::NonNullable);
234        assert_eq!(
235            not_expr.return_dtype(&dtype).unwrap(),
236            DType::Bool(Nullability::NonNullable)
237        );
238
239        let dtype = test_harness::struct_dtype();
240        assert_eq!(
241            not(col("bool1")).return_dtype(&dtype).unwrap(),
242            DType::Bool(Nullability::NonNullable)
243        );
244    }
245}