Skip to main content

reifydb_routine/function/math/
modulo.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use num_traits::ToPrimitive;
5use reifydb_core::value::column::{ColumnWithName, buffer::ColumnBuffer, columns::Columns};
6use reifydb_type::value::r#type::{Type, input_types::InputTypes};
7
8use crate::routine::{Function, FunctionKind, Routine, RoutineInfo, context::FunctionContext, error::RoutineError};
9
10pub struct Modulo {
11	info: RoutineInfo,
12}
13
14impl Default for Modulo {
15	fn default() -> Self {
16		Self::new()
17	}
18}
19
20impl Modulo {
21	pub fn new() -> Self {
22		Self {
23			info: RoutineInfo::new("math::mod"),
24		}
25	}
26}
27
28fn numeric_to_f64(data: &ColumnBuffer, i: usize) -> Option<f64> {
29	match data {
30		ColumnBuffer::Int1(c) => c.get(i).map(|&v| v as f64),
31		ColumnBuffer::Int2(c) => c.get(i).map(|&v| v as f64),
32		ColumnBuffer::Int4(c) => c.get(i).map(|&v| v as f64),
33		ColumnBuffer::Int8(c) => c.get(i).map(|&v| v as f64),
34		ColumnBuffer::Int16(c) => c.get(i).map(|&v| v as f64),
35		ColumnBuffer::Uint1(c) => c.get(i).map(|&v| v as f64),
36		ColumnBuffer::Uint2(c) => c.get(i).map(|&v| v as f64),
37		ColumnBuffer::Uint4(c) => c.get(i).map(|&v| v as f64),
38		ColumnBuffer::Uint8(c) => c.get(i).map(|&v| v as f64),
39		ColumnBuffer::Uint16(c) => c.get(i).map(|&v| v as f64),
40		ColumnBuffer::Float4(c) => c.get(i).map(|&v| v as f64),
41		ColumnBuffer::Float8(c) => c.get(i).copied(),
42		ColumnBuffer::Int {
43			container,
44			..
45		} => container.get(i).map(|v| v.0.to_f64().unwrap_or(0.0)),
46		ColumnBuffer::Uint {
47			container,
48			..
49		} => container.get(i).map(|v| v.0.to_f64().unwrap_or(0.0)),
50		ColumnBuffer::Decimal {
51			container,
52			..
53		} => container.get(i).map(|v| v.0.to_f64().unwrap_or(0.0)),
54		_ => None,
55	}
56}
57
58impl<'a> Routine<FunctionContext<'a>> for Modulo {
59	fn info(&self) -> &RoutineInfo {
60		&self.info
61	}
62
63	fn return_type(&self, _input_types: &[Type]) -> Type {
64		Type::Float8
65	}
66
67	fn execute(&self, ctx: &mut FunctionContext<'a>, args: &Columns) -> Result<Columns, RoutineError> {
68		if args.len() != 2 {
69			return Err(RoutineError::FunctionArityMismatch {
70				function: ctx.fragment.clone(),
71				expected: 2,
72				actual: args.len(),
73			});
74		}
75
76		let a_col = &args[0];
77		let b_col = &args[1];
78
79		let (a_data, a_bitvec) = a_col.unwrap_option();
80		let (b_data, b_bitvec) = b_col.unwrap_option();
81		let row_count = a_data.len();
82
83		if !a_data.get_type().is_number() {
84			return Err(RoutineError::FunctionInvalidArgumentType {
85				function: ctx.fragment.clone(),
86				argument_index: 0,
87				expected: InputTypes::numeric().expected_at(0).to_vec(),
88				actual: a_data.get_type(),
89			});
90		}
91		if !b_data.get_type().is_number() {
92			return Err(RoutineError::FunctionInvalidArgumentType {
93				function: ctx.fragment.clone(),
94				argument_index: 1,
95				expected: InputTypes::numeric().expected_at(0).to_vec(),
96				actual: b_data.get_type(),
97			});
98		}
99
100		let mut result = Vec::with_capacity(row_count);
101		let mut res_bitvec = Vec::with_capacity(row_count);
102
103		for i in 0..row_count {
104			match (numeric_to_f64(a_data, i), numeric_to_f64(b_data, i)) {
105				(Some(a), Some(b)) => {
106					if b == 0.0 {
107						result.push(f64::NAN);
108					} else {
109						result.push(a % b);
110					}
111					res_bitvec.push(true);
112				}
113				_ => {
114					result.push(0.0);
115					res_bitvec.push(false);
116				}
117			}
118		}
119
120		let result_data = ColumnBuffer::float8_with_bitvec(result, res_bitvec);
121		let combined_bitvec = match (a_bitvec, b_bitvec) {
122			(Some(a), Some(b)) => Some(a.and(b)),
123			(Some(a), None) => Some(a.clone()),
124			(None, Some(b)) => Some(b.clone()),
125			(None, None) => None,
126		};
127
128		let final_data = if let Some(bv) = combined_bitvec {
129			ColumnBuffer::Option {
130				inner: Box::new(result_data),
131				bitvec: bv,
132			}
133		} else {
134			result_data
135		};
136
137		Ok(Columns::new(vec![ColumnWithName::new(ctx.fragment.clone(), final_data)]))
138	}
139}
140
141impl Function for Modulo {
142	fn kinds(&self) -> &[FunctionKind] {
143		&[FunctionKind::Scalar]
144	}
145}