Skip to main content

reifydb_routine/function/text/
trim_end.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use reifydb_core::value::column::{Column, columns::Columns, data::ColumnData};
5use reifydb_type::value::{container::utf8::Utf8Container, r#type::Type};
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
8
9pub struct TextTrimEnd {
10	info: FunctionInfo,
11}
12
13impl Default for TextTrimEnd {
14	fn default() -> Self {
15		Self::new()
16	}
17}
18
19impl TextTrimEnd {
20	pub fn new() -> Self {
21		Self {
22			info: FunctionInfo::new("text::trim_end"),
23		}
24	}
25}
26
27impl Function for TextTrimEnd {
28	fn info(&self) -> &FunctionInfo {
29		&self.info
30	}
31
32	fn capabilities(&self) -> &[FunctionCapability] {
33		&[FunctionCapability::Scalar]
34	}
35
36	fn return_type(&self, _input_types: &[Type]) -> Type {
37		Type::Utf8
38	}
39
40	fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
41		if args.len() != 1 {
42			return Err(FunctionError::ArityMismatch {
43				function: ctx.fragment.clone(),
44				expected: 1,
45				actual: args.len(),
46			});
47		}
48
49		let column = &args[0];
50		let (data, bitvec) = column.data().unwrap_option();
51		let row_count = data.len();
52
53		match data {
54			ColumnData::Utf8 {
55				container,
56				max_bytes,
57			} => {
58				let mut result_data = Vec::with_capacity(row_count);
59
60				for i in 0..row_count {
61					if container.is_defined(i) {
62						let original_str = &container[i];
63						let trimmed_str = original_str.trim_end();
64						result_data.push(trimmed_str.to_string());
65					} else {
66						result_data.push(String::new());
67					}
68				}
69
70				let result_col_data = ColumnData::Utf8 {
71					container: Utf8Container::new(result_data),
72					max_bytes: *max_bytes,
73				};
74				let final_data = match bitvec {
75					Some(bv) => ColumnData::Option {
76						inner: Box::new(result_col_data),
77						bitvec: bv.clone(),
78					},
79					None => result_col_data,
80				};
81				Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
82			}
83			other => Err(FunctionError::InvalidArgumentType {
84				function: ctx.fragment.clone(),
85				argument_index: 0,
86				expected: vec![Type::Utf8],
87				actual: other.get_type(),
88			}),
89		}
90	}
91}