Skip to main content

reifydb_function/text/
length.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4use reifydb_core::value::column::data::ColumnData;
5use reifydb_type::value::r#type::Type;
6
7use crate::{ScalarFunction, ScalarFunctionContext, error::ScalarFunctionError, propagate_options};
8
9pub struct TextLength;
10
11impl TextLength {
12	pub fn new() -> Self {
13		Self
14	}
15}
16
17impl ScalarFunction for TextLength {
18	fn scalar(&self, ctx: ScalarFunctionContext) -> crate::error::ScalarFunctionResult<ColumnData> {
19		if let Some(result) = propagate_options(self, &ctx) {
20			return result;
21		}
22
23		let columns = ctx.columns;
24		let row_count = ctx.row_count;
25
26		// Validate exactly 1 argument
27		if columns.len() != 1 {
28			return Err(ScalarFunctionError::ArityMismatch {
29				function: ctx.fragment.clone(),
30				expected: 1,
31				actual: columns.len(),
32			});
33		}
34
35		let column = columns.get(0).unwrap();
36
37		match &column.data() {
38			ColumnData::Utf8 {
39				container,
40				..
41			} => {
42				let mut result = Vec::with_capacity(row_count);
43				let mut bitvec = Vec::with_capacity(row_count);
44
45				for i in 0..row_count {
46					if container.is_defined(i) {
47						let text = &container[i];
48						// Return byte length, not character count
49						result.push(text.len() as i32);
50						bitvec.push(true);
51					} else {
52						result.push(0);
53						bitvec.push(false);
54					}
55				}
56
57				Ok(ColumnData::int4_with_bitvec(result, bitvec))
58			}
59			other => Err(ScalarFunctionError::InvalidArgumentType {
60				function: ctx.fragment.clone(),
61				argument_index: 0,
62				expected: vec![Type::Utf8],
63				actual: other.get_type(),
64			}),
65		}
66	}
67
68	fn return_type(&self, _input_types: &[Type]) -> Type {
69		Type::Int4
70	}
71}