Skip to main content

reifydb_function/text/
reverse.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::{container::utf8::Utf8Container, r#type::Type};
6
7use crate::{
8	ScalarFunction, ScalarFunctionContext,
9	error::{ScalarFunctionError, ScalarFunctionResult},
10	propagate_options,
11};
12
13pub struct TextReverse;
14
15impl TextReverse {
16	pub fn new() -> Self {
17		Self
18	}
19}
20
21impl ScalarFunction for TextReverse {
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 column = columns.get(0).unwrap();
39
40		match &column.data() {
41			ColumnData::Utf8 {
42				container,
43				max_bytes,
44			} => {
45				let mut result_data = Vec::with_capacity(row_count);
46
47				for i in 0..row_count {
48					if container.is_defined(i) {
49						let reversed: String = container[i].chars().rev().collect();
50						result_data.push(reversed);
51					} else {
52						result_data.push(String::new());
53					}
54				}
55
56				Ok(ColumnData::Utf8 {
57					container: Utf8Container::new(result_data),
58					max_bytes: *max_bytes,
59				})
60			}
61			other => Err(ScalarFunctionError::InvalidArgumentType {
62				function: ctx.fragment.clone(),
63				argument_index: 0,
64				expected: vec![Type::Utf8],
65				actual: other.get_type(),
66			}),
67		}
68	}
69
70	fn return_type(&self, _input_types: &[Type]) -> Type {
71		Type::Utf8
72	}
73}