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