Skip to main content

vortex_functions/
strpos.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use memchr::memmem;
5use vortex_array::AnyColumnar;
6use vortex_array::ArrayRef;
7use vortex_array::ExecutionCtx;
8use vortex_array::IntoArray;
9use vortex_array::arrays::ConstantArray;
10use vortex_array::arrays::PrimitiveArray;
11use vortex_array::arrays::VarBinViewArray;
12use vortex_array::dtype::DType;
13use vortex_array::dtype::Nullability;
14use vortex_array::dtype::PType;
15use vortex_array::require_input;
16use vortex_array::scalar::Scalar;
17use vortex_array::scalar_fn::Arity;
18use vortex_array::scalar_fn::ChildName;
19use vortex_array::scalar_fn::EmptyOptions;
20use vortex_array::scalar_fn::ExecutionArgs;
21use vortex_array::scalar_fn::ScalarFnExecutionResult;
22use vortex_array::scalar_fn::ScalarFnId;
23use vortex_array::scalar_fn::ScalarFnVTable;
24use vortex_buffer::Buffer;
25use vortex_error::VortexResult;
26use vortex_error::vortex_bail;
27use vortex_session::VortexSession;
28use vortex_session::registry::CachedId;
29/// One-based character position of the first occurrence of `search` in `input`, or zero when
30/// absent, matching SQL `strpos`. An empty `search` is found at position one.
31#[derive(Clone)]
32pub struct Strpos;
33
34impl ScalarFnVTable for Strpos {
35    type Options = EmptyOptions;
36
37    fn id(&self) -> ScalarFnId {
38        static ID: CachedId = CachedId::new("vortex.strpos");
39        *ID
40    }
41
42    fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
43        Ok(Some(vec![]))
44    }
45
46    fn deserialize(
47        &self,
48        _metadata: &[u8],
49        _session: &VortexSession,
50    ) -> VortexResult<Self::Options> {
51        Ok(EmptyOptions)
52    }
53
54    fn arity(&self, _options: &Self::Options) -> Arity {
55        Arity::Exact(2)
56    }
57
58    fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
59        match child_idx {
60            0 => ChildName::from("input"),
61            1 => ChildName::from("search"),
62            _ => unreachable!("Invalid child index {child_idx} for strpos()"),
63        }
64    }
65
66    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
67        let (input, search) = (&arg_dtypes[0], &arg_dtypes[1]);
68        if !input.is_utf8() || !search.is_utf8() {
69            vortex_bail!("strpos() requires Utf8 arguments, got {input} and {search}");
70        }
71        Ok(DType::Primitive(
72            PType::I64,
73            (input.is_nullable() || search.is_nullable()).into(),
74        ))
75    }
76
77    fn execute(
78        &self,
79        _options: &Self::Options,
80        args: &dyn ExecutionArgs,
81        ctx: &mut ExecutionCtx,
82    ) -> VortexResult<ArrayRef> {
83        let input = args.get(0)?;
84        let search = args.get(1)?;
85        let nullability =
86            Nullability::from(input.dtype().is_nullable() || search.dtype().is_nullable());
87        let input = input.execute::<VarBinViewArray>(ctx)?;
88        let haystack = input.resolved_views();
89
90        if let Some(search) = search.as_constant() {
91            let Some(needle) = search.as_utf8().value() else {
92                return Ok(ConstantArray::new(
93                    Scalar::null(DType::Primitive(PType::I64, Nullability::Nullable)),
94                    args.row_count(),
95                )
96                .into_array());
97            };
98            let finder = memmem::Finder::new(needle.as_bytes());
99            let positions: Buffer<i64> = (0..haystack.len())
100                .map(|i| position(haystack.bytes(i), finder.find(haystack.bytes(i))))
101                .collect();
102            let validity = input.validity()?.union_nullability(nullability);
103            return Ok(PrimitiveArray::new(positions, validity).into_array());
104        }
105
106        let search = search.execute::<VarBinViewArray>(ctx)?;
107        let needles = search.resolved_views();
108        let positions: Buffer<i64> = (0..haystack.len())
109            .map(|i| {
110                let bytes = haystack.bytes(i);
111                position(bytes, memmem::find(bytes, needles.bytes(i)))
112            })
113            .collect();
114        let validity = input
115            .validity()?
116            .and(search.validity()?)?
117            .union_nullability(nullability);
118        Ok(PrimitiveArray::new(positions, validity).into_array())
119    }
120
121    fn execute_step(
122        &self,
123        options: &Self::Options,
124        args: &dyn ExecutionArgs,
125        ctx: &mut ExecutionCtx,
126    ) -> VortexResult<ScalarFnExecutionResult> {
127        require_input!(args, 0 => AnyColumnar);
128        require_input!(args, 1 => AnyColumnar);
129        self.execute(options, args, ctx)
130            .map(ScalarFnExecutionResult::done)
131    }
132
133    fn is_strict(&self, _options: &Self::Options) -> bool {
134        true
135    }
136
137    fn is_infallible(&self, _options: &Self::Options) -> bool {
138        true
139    }
140}
141
142/// Converts a byte offset into a one-based character position, or zero when not found.
143fn position(haystack: &[u8], offset: Option<usize>) -> i64 {
144    let Some(offset) = offset else {
145        return 0;
146    };
147    // Utf8 arrays hold valid UTF-8, so each character starts with exactly one byte that is not
148    // a continuation byte (`0b10xx_xxxx`).
149    let chars = haystack[..offset]
150        .iter()
151        .filter(|&&byte| (byte as i8) >= -0x40)
152        .count();
153    // A Vortex string length is at most `u32::MAX` bytes, so the position fits in an `i64`.
154    chars as i64 + 1
155}
156
157#[cfg(test)]
158mod tests {
159    use std::sync::LazyLock;
160
161    use rstest::rstest;
162    use vortex_array::IntoArray;
163    use vortex_array::VortexSessionExecute;
164    use vortex_array::arrays::PrimitiveArray;
165    use vortex_array::arrays::RunEnd;
166    use vortex_array::arrays::StructArray;
167    use vortex_array::arrays::VarBinViewArray;
168    use vortex_array::assert_arrays_eq;
169    use vortex_error::VortexResult;
170    use vortex_expr::ArrayExprExt;
171    use vortex_expr::Expression;
172    use vortex_expr::get_item;
173    use vortex_expr::lit;
174    use vortex_expr::proto::ExprSerializeProtoExt;
175    use vortex_expr::root;
176    use vortex_session::VortexSession;
177
178    use crate::expr::strpos;
179
180    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
181        let session = VortexSession::empty();
182        vortex_array::initialize(&session);
183        crate::initialize(&session);
184        session
185    });
186
187    #[rstest]
188    #[case::ascii("xxhello", "hello", 3)]
189    #[case::after_multibyte("é📊h", "h", 3)]
190    #[case::absent("abc", "x", 0)]
191    #[case::empty_needle("abc", "", 1)]
192    #[case::empty_haystack("", "", 1)]
193    fn constant_needle(
194        #[case] haystack: &str,
195        #[case] needle: &str,
196        #[case] expected: i64,
197    ) -> VortexResult<()> {
198        let mut ctx = SESSION.create_execution_ctx();
199        let input = VarBinViewArray::from_iter_nullable_str([Some(haystack), None]).into_array();
200        assert_arrays_eq!(
201            input.apply(&strpos(root(), lit(needle)))?,
202            PrimitiveArray::from_option_iter([Some(expected), None]),
203            &mut ctx
204        );
205        Ok(())
206    }
207
208    #[test]
209    fn column_needle() -> VortexResult<()> {
210        let mut ctx = SESSION.create_execution_ctx();
211        let input = StructArray::from_fields(&[
212            (
213                "s",
214                VarBinViewArray::from_iter_nullable_str([
215                    Some("é📊hello"),
216                    Some("abc"),
217                    None,
218                    Some("abc"),
219                ])
220                .into_array(),
221            ),
222            (
223                "needle",
224                VarBinViewArray::from_iter_nullable_str([Some("h"), Some("x"), Some("a"), None])
225                    .into_array(),
226            ),
227        ])?
228        .into_array();
229        assert_arrays_eq!(
230            input.apply(&strpos(get_item("s", root()), get_item("needle", root())))?,
231            PrimitiveArray::from_option_iter([Some(3i64), Some(0), None, None]),
232            &mut ctx
233        );
234        Ok(())
235    }
236
237    #[test]
238    fn roundtrips_through_proto() -> VortexResult<()> {
239        let expr = strpos(root(), lit("x"));
240        assert_eq!(
241            Expression::from_proto(&expr.serialize_proto()?, &SESSION)?,
242            expr
243        );
244        Ok(())
245    }
246
247    #[test]
248    fn preserves_runs_of_a_slice() -> VortexResult<()> {
249        let mut ctx = SESSION.create_execution_ctx();
250        let input = RunEnd::try_new(
251            PrimitiveArray::from_iter([2u32, 5, 6]).into_array(),
252            VarBinViewArray::from_iter_nullable_str([Some("cat"), None, Some("a")]).into_array(),
253            &mut ctx,
254        )?
255        .into_array()
256        .slice(1..6)?;
257        let result = input
258            .apply(&strpos(root(), lit("a")))?
259            .execute_until::<RunEnd>(&mut ctx)?;
260        assert!(result.is::<RunEnd>());
261        assert_arrays_eq!(
262            result,
263            PrimitiveArray::from_option_iter([Some(2i64), None, None, None, Some(1)]),
264            &mut ctx
265        );
266        Ok(())
267    }
268}