Skip to main content

reifydb_function/text/
char.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::{constraint::bytes::MaxBytes, container::utf8::Utf8Container, r#type::Type};
6
7use crate::{ScalarFunction, ScalarFunctionContext, error::ScalarFunctionError, propagate_options};
8
9pub struct TextChar;
10
11impl TextChar {
12	pub fn new() -> Self {
13		Self
14	}
15}
16
17impl ScalarFunction for TextChar {
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		if columns.len() != 1 {
27			return Err(ScalarFunctionError::ArityMismatch {
28				function: ctx.fragment.clone(),
29				expected: 1,
30				actual: columns.len(),
31			});
32		}
33
34		let col = columns.get(0).unwrap();
35
36		match col.data() {
37			ColumnData::Int1(c) => {
38				convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
39			}
40			ColumnData::Int2(c) => {
41				convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
42			}
43			ColumnData::Int4(c) => {
44				convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
45			}
46			ColumnData::Int8(c) => {
47				convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
48			}
49			ColumnData::Uint1(c) => {
50				convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
51			}
52			ColumnData::Uint2(c) => {
53				convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
54			}
55			ColumnData::Uint4(c) => {
56				convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
57			}
58			other => Err(ScalarFunctionError::InvalidArgumentType {
59				function: ctx.fragment.clone(),
60				argument_index: 0,
61				expected: vec![Type::Int1, Type::Int2, Type::Int4, Type::Int8],
62				actual: other.get_type(),
63			}),
64		}
65	}
66
67	fn return_type(&self, _input_types: &[Type]) -> Type {
68		Type::Utf8
69	}
70}
71
72fn convert_to_char<F>(
73	row_count: usize,
74	_capacity: usize,
75	get_value: F,
76) -> crate::error::ScalarFunctionResult<ColumnData>
77where
78	F: Fn(usize) -> Option<u32>,
79{
80	let mut result_data = Vec::with_capacity(row_count);
81
82	for i in 0..row_count {
83		match get_value(i) {
84			Some(code_point) => {
85				if let Some(ch) = char::from_u32(code_point) {
86					result_data.push(ch.to_string());
87				} else {
88					result_data.push(String::new());
89				}
90			}
91			None => {
92				result_data.push(String::new());
93			}
94		}
95	}
96
97	Ok(ColumnData::Utf8 {
98		container: Utf8Container::new(result_data),
99		max_bytes: MaxBytes::MAX,
100	})
101}