reifydb_function/text/
char.rs1use reifydb_core::value::column::data::ColumnData;
5use reifydb_type::value::{constraint::bytes::MaxBytes, container::utf8::Utf8Container, r#type::Type};
6
7use crate::{
8 ScalarFunction, ScalarFunctionContext,
9 error::{ScalarFunctionError, ScalarFunctionResult},
10 propagate_options,
11};
12
13pub struct TextChar;
14
15impl TextChar {
16 pub fn new() -> Self {
17 Self
18 }
19}
20
21impl ScalarFunction for TextChar {
22 fn scalar(&self, ctx: ScalarFunctionContext) -> ScalarFunctionResult<ColumnData> {
23 if let Some(result) = propagate_options(self, &ctx) {
24 return result;
25 }
26
27 let columns = ctx.columns;
28 let row_count = ctx.row_count;
29
30 if columns.len() != 1 {
31 return Err(ScalarFunctionError::ArityMismatch {
32 function: ctx.fragment.clone(),
33 expected: 1,
34 actual: columns.len(),
35 });
36 }
37
38 let col = columns.get(0).unwrap();
39
40 match col.data() {
41 ColumnData::Int1(c) => {
42 convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
43 }
44 ColumnData::Int2(c) => {
45 convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
46 }
47 ColumnData::Int4(c) => {
48 convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
49 }
50 ColumnData::Int8(c) => {
51 convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
52 }
53 ColumnData::Uint1(c) => {
54 convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
55 }
56 ColumnData::Uint2(c) => {
57 convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
58 }
59 ColumnData::Uint4(c) => {
60 convert_to_char(row_count, c.data().len(), |i| c.get(i).map(|&v| v as u32))
61 }
62 other => Err(ScalarFunctionError::InvalidArgumentType {
63 function: ctx.fragment.clone(),
64 argument_index: 0,
65 expected: vec![Type::Int1, Type::Int2, Type::Int4, Type::Int8],
66 actual: other.get_type(),
67 }),
68 }
69 }
70
71 fn return_type(&self, _input_types: &[Type]) -> Type {
72 Type::Utf8
73 }
74}
75
76fn convert_to_char<F>(row_count: usize, _capacity: usize, get_value: F) -> 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}