Skip to main content

vortex_array/scalar_fn/builtin/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}