Skip to main content

vortex_functions/
byte_length.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use num_traits::AsPrimitive;
5use vortex_array::ArrayRef;
6use vortex_array::ArrayView;
7use vortex_array::ExecutionCtx;
8use vortex_array::IntoArray;
9use vortex_array::VTable;
10use vortex_array::arrays::ConstantArray;
11use vortex_array::arrays::PrimitiveArray;
12use vortex_array::arrays::VarBinViewArray;
13use vortex_array::arrays::scalar_fn::ExactScalarFn;
14use vortex_array::arrays::scalar_fn::ScalarFnArrayView;
15use vortex_array::arrays::varbinview::VarBinViewArrayExt;
16use vortex_array::dtype::DType;
17use vortex_array::dtype::Nullability;
18use vortex_array::dtype::PType;
19use vortex_array::kernel::ExecuteParentKernel;
20use vortex_array::scalar::Scalar;
21use vortex_array::scalar_fn::Arity;
22use vortex_array::scalar_fn::ChildName;
23use vortex_array::scalar_fn::EmptyOptions;
24use vortex_array::scalar_fn::ExecutionArgs;
25use vortex_array::scalar_fn::ScalarFnId;
26use vortex_array::scalar_fn::ScalarFnVTable;
27use vortex_buffer::Buffer;
28use vortex_error::VortexExpect;
29use vortex_error::VortexResult;
30use vortex_error::vortex_bail;
31use vortex_error::vortex_ensure_eq;
32use vortex_session::VortexSession;
33use vortex_session::registry::CachedId;
34
35pub trait ByteLengthKernel: VTable {
36    fn byte_length(
37        array: ArrayView<'_, Self>,
38        ctx: &mut ExecutionCtx,
39    ) -> VortexResult<Option<ArrayRef>>;
40}
41
42#[derive(Default, Debug)]
43pub struct ByteLengthExecuteAdaptor<V>(pub V);
44
45impl<V: ByteLengthKernel> ExecuteParentKernel<V> for ByteLengthExecuteAdaptor<V> {
46    type Parent = ExactScalarFn<ByteLength>;
47
48    fn execute_parent(
49        &self,
50        array: ArrayView<'_, V>,
51        _parent: ScalarFnArrayView<'_, ByteLength>,
52        child_idx: usize,
53        ctx: &mut ExecutionCtx,
54    ) -> VortexResult<Option<ArrayRef>> {
55        vortex_ensure_eq!(child_idx, 0);
56        V::byte_length(array, ctx)
57    }
58}
59
60/// Byte length of each element in a Utf8 or Binary array.
61#[derive(Clone)]
62pub struct ByteLength;
63
64impl ScalarFnVTable for ByteLength {
65    type Options = EmptyOptions;
66
67    fn id(&self) -> ScalarFnId {
68        static ID: CachedId = CachedId::new("vortex.byte_length");
69        *ID
70    }
71
72    fn serialize(&self, _instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
73        Ok(Some(vec![]))
74    }
75
76    fn deserialize(
77        &self,
78        _metadata: &[u8],
79        _session: &VortexSession,
80    ) -> VortexResult<Self::Options> {
81        Ok(EmptyOptions)
82    }
83
84    fn arity(&self, _options: &Self::Options) -> Arity {
85        Arity::Exact(1)
86    }
87
88    fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
89        match child_idx {
90            0 => ChildName::from("input"),
91            _ => unreachable!("Invalid child index {child_idx} for byte_length()"),
92        }
93    }
94
95    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
96        match &arg_dtypes[0] {
97            DType::Utf8(nullable) | DType::Binary(nullable) => {
98                Ok(DType::Primitive(PType::U64, *nullable))
99            }
100            other => {
101                vortex_bail!("byte_length() requires Utf8 or Binary, got {other}")
102            }
103        }
104    }
105
106    fn execute(
107        &self,
108        _options: &Self::Options,
109        args: &dyn ExecutionArgs,
110        ctx: &mut ExecutionCtx,
111    ) -> VortexResult<ArrayRef> {
112        let input = args.get(0)?;
113        let nullability = input.dtype().nullability();
114
115        if let Some(scalar) = input.as_constant() {
116            let len_scalar = scalar_byte_length(scalar, nullability)?;
117            return Ok(ConstantArray::new(len_scalar, args.row_count()).into_array());
118        }
119
120        match input.dtype() {
121            DType::Utf8(_) | DType::Binary(_) => byte_length(&input, nullability, ctx),
122            other => {
123                vortex_bail!("byte_length() requires Utf8 or Binary, got {other}")
124            }
125        }
126    }
127
128    fn is_strict(&self, _options: &Self::Options) -> bool {
129        true
130    }
131
132    fn is_infallible(&self, _options: &Self::Options) -> bool {
133        true
134    }
135}
136
137fn scalar_byte_length(scalar: &Scalar, nullability: Nullability) -> VortexResult<Scalar> {
138    if scalar.is_null() {
139        let dtype = DType::Primitive(PType::U64, Nullability::Nullable);
140        return Ok(Scalar::null(dtype));
141    }
142    let len = match scalar.dtype() {
143        DType::Utf8(_) => scalar
144            .as_utf8()
145            .value()
146            .vortex_expect("null utf-8 scalar")
147            .len(),
148        DType::Binary(_) => scalar
149            .as_binary()
150            .value()
151            .vortex_expect("null binary scalar")
152            .len(),
153        other => {
154            vortex_bail!("byte_length() requires Utf8 or Binary, got {other}")
155        }
156    };
157    let len: u64 = len.as_();
158    Ok(Scalar::primitive(len, nullability))
159}
160
161pub(crate) fn byte_length(
162    array: &ArrayRef,
163    nullability: Nullability,
164    ctx: &mut ExecutionCtx,
165) -> VortexResult<ArrayRef> {
166    let array = array.clone().execute::<VarBinViewArray>(ctx)?;
167    let validity = array.varbinview_validity();
168    let lengths: Buffer<u64> = array.views().iter().map(|v| v.len() as u64).collect();
169    Ok(PrimitiveArray::new(lengths, validity.union_nullability(nullability)).into_array())
170}
171
172#[cfg(test)]
173mod tests {
174    use std::sync::LazyLock;
175
176    use rstest::rstest;
177    use vortex_array::ArrayRef;
178    use vortex_array::IntoArray;
179    use vortex_array::VortexSessionExecute;
180    use vortex_array::arrays::ConstantArray;
181    use vortex_array::arrays::PrimitiveArray;
182    use vortex_array::arrays::VarBinArray;
183    use vortex_array::arrays::VarBinViewArray;
184    use vortex_array::assert_arrays_eq;
185    use vortex_array::dtype::DType;
186    use vortex_array::dtype::Nullability;
187    use vortex_array::scalar::Scalar;
188    use vortex_error::VortexResult;
189    use vortex_expr::ArrayExprExt;
190    use vortex_expr::root;
191    use vortex_session::VortexSession;
192
193    use crate::expr::byte_length;
194
195    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
196        let session = VortexSession::empty();
197
198        vortex_array::initialize(&session);
199
200        crate::initialize(&session);
201
202        session
203    });
204
205    #[rstest]
206    #[case(VarBinArray::from_strs(vec!["hello", "world", ""]).into_array(), vec![5u64, 5, 0])]
207    #[case(VarBinArray::from_bytes(vec![b"ab".as_ref(), b"cde"]).into_array(), vec![2u64, 3])]
208    #[case(VarBinArray::from_strs(vec!["Пуховички"]).into_array(), vec![18u64])]
209    #[case(VarBinArray::from_bytes(vec!["Пуховички".as_ref()]).into_array(), vec![18u64])]
210    fn test_bytes_byte_length(
211        #[case] array: ArrayRef,
212        #[case] expected_lens: Vec<u64>,
213    ) -> VortexResult<()> {
214        let mut ctx = SESSION.create_execution_ctx();
215        let result = array.apply(&byte_length(root()))?;
216        let expected = PrimitiveArray::from_iter(expected_lens);
217        assert_arrays_eq!(result, expected, &mut ctx);
218        Ok(())
219    }
220
221    #[test]
222    fn test_varbinview_byte_length() -> VortexResult<()> {
223        let mut ctx = SESSION.create_execution_ctx();
224        let array = VarBinViewArray::from_iter_str(["short", "a longer string here"]).into_array();
225        let result = array.apply(&byte_length(root()))?;
226        let expected = PrimitiveArray::from_iter(vec![5u64, 20]);
227        assert_arrays_eq!(result, expected, &mut ctx);
228        Ok(())
229    }
230
231    #[test]
232    fn test_nullable_string_byte_length() -> VortexResult<()> {
233        let array = VarBinArray::from_nullable_strs(vec![Some("hello"), None, Some("Пуховички")])
234            .into_array();
235        let result = array.apply(&byte_length(root()))?;
236
237        let mut ctx = SESSION.create_execution_ctx();
238        assert!(result.is_valid(0, &mut ctx)?);
239        assert!(!result.is_valid(1, &mut ctx)?);
240        assert!(result.is_valid(2, &mut ctx)?);
241        assert_eq!(
242            result.execute_scalar(0, &mut SESSION.create_execution_ctx())?,
243            Scalar::primitive(5u64, Nullability::Nullable),
244        );
245        assert_eq!(
246            result.execute_scalar(2, &mut SESSION.create_execution_ctx())?,
247            Scalar::primitive(18u64, Nullability::Nullable),
248        );
249        assert_arrays_eq!(
250            result,
251            PrimitiveArray::from_option_iter([Some(5u64), None, Some(18)]),
252            &mut ctx
253        );
254        Ok(())
255    }
256
257    #[test]
258    fn test_null_scalar_byte_length() -> VortexResult<()> {
259        let null_scalar = Scalar::null(DType::Utf8(Nullability::Nullable));
260        let array = ConstantArray::new(null_scalar, 2).into_array();
261        let result = array.apply(&byte_length(root()))?;
262        let mut ctx = SESSION.create_execution_ctx();
263        assert!(!result.is_valid(0, &mut ctx)?);
264        assert!(!result.is_valid(1, &mut ctx)?);
265        assert_arrays_eq!(
266            result,
267            PrimitiveArray::from_option_iter([None::<u64>, None]),
268            &mut ctx
269        );
270        Ok(())
271    }
272
273    #[test]
274    fn test_display() {
275        let expr = byte_length(root());
276        assert_eq!(expr.to_string(), "vortex.byte_length($)");
277    }
278}