Skip to main content

reifydb_routine/function/math/
gcd.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::r#type::Type;
6
7use crate::function::{Function, FunctionCapability, FunctionContext, FunctionInfo, error::FunctionError};
8
9pub struct Gcd {
10	info: FunctionInfo,
11}
12
13impl Default for Gcd {
14	fn default() -> Self {
15		Self::new()
16	}
17}
18
19impl Gcd {
20	pub fn new() -> Self {
21		Self {
22			info: FunctionInfo::new("math::gcd"),
23		}
24	}
25}
26
27fn numeric_to_i64(data: &ColumnData, i: usize) -> Option<i64> {
28	match data {
29		ColumnData::Int1(c) => c.get(i).map(|&v| v as i64),
30		ColumnData::Int2(c) => c.get(i).map(|&v| v as i64),
31		ColumnData::Int4(c) => c.get(i).map(|&v| v as i64),
32		ColumnData::Int8(c) => c.get(i).copied(),
33		ColumnData::Int16(c) => c.get(i).map(|&v| v as i64),
34		ColumnData::Uint1(c) => c.get(i).map(|&v| v as i64),
35		ColumnData::Uint2(c) => c.get(i).map(|&v| v as i64),
36		ColumnData::Uint4(c) => c.get(i).map(|&v| v as i64),
37		ColumnData::Uint8(c) => c.get(i).map(|&v| v as i64),
38		_ => None,
39	}
40}
41
42fn compute_gcd(mut a: i64, mut b: i64) -> i64 {
43	a = a.abs();
44	b = b.abs();
45	while b != 0 {
46		let t = b;
47		b = a % b;
48		a = t;
49	}
50	a
51}
52
53impl Function for Gcd {
54	fn info(&self) -> &FunctionInfo {
55		&self.info
56	}
57
58	fn capabilities(&self) -> &[FunctionCapability] {
59		&[FunctionCapability::Scalar]
60	}
61
62	fn return_type(&self, _input_types: &[Type]) -> Type {
63		Type::Int8
64	}
65
66	fn execute(&self, ctx: &FunctionContext, args: &Columns) -> Result<Columns, FunctionError> {
67		if args.len() != 2 {
68			return Err(FunctionError::ArityMismatch {
69				function: ctx.fragment.clone(),
70				expected: 2,
71				actual: args.len(),
72			});
73		}
74
75		let a_col = &args[0];
76		let b_col = &args[1];
77
78		let (a_data, a_bitvec) = a_col.data().unwrap_option();
79		let (b_data, b_bitvec) = b_col.data().unwrap_option();
80		let row_count = a_data.len();
81
82		let expected_types = vec![
83			Type::Int1,
84			Type::Int2,
85			Type::Int4,
86			Type::Int8,
87			Type::Uint1,
88			Type::Uint2,
89			Type::Uint4,
90			Type::Uint8,
91		];
92		if !a_data.get_type().is_number() {
93			return Err(FunctionError::InvalidArgumentType {
94				function: ctx.fragment.clone(),
95				argument_index: 0,
96				expected: expected_types,
97				actual: a_data.get_type(),
98			});
99		}
100		if !b_data.get_type().is_number() {
101			return Err(FunctionError::InvalidArgumentType {
102				function: ctx.fragment.clone(),
103				argument_index: 1,
104				expected: expected_types,
105				actual: b_data.get_type(),
106			});
107		}
108
109		let mut result = Vec::with_capacity(row_count);
110		let mut res_bitvec = Vec::with_capacity(row_count);
111
112		for i in 0..row_count {
113			match (numeric_to_i64(a_data, i), numeric_to_i64(b_data, i)) {
114				(Some(a), Some(b)) => {
115					result.push(compute_gcd(a, b));
116					res_bitvec.push(true);
117				}
118				_ => {
119					result.push(0);
120					res_bitvec.push(false);
121				}
122			}
123		}
124
125		let result_data = ColumnData::int8_with_bitvec(result, res_bitvec);
126		let combined_bitvec = match (a_bitvec, b_bitvec) {
127			(Some(a), Some(b)) => Some(a.and(b)),
128			(Some(a), None) => Some(a.clone()),
129			(None, Some(b)) => Some(b.clone()),
130			(None, None) => None,
131		};
132
133		let final_data = if let Some(bv) = combined_bitvec {
134			ColumnData::Option {
135				inner: Box::new(result_data),
136				bitvec: bv,
137			}
138		} else {
139			result_data
140		};
141
142		Ok(Columns::new(vec![Column::new(ctx.fragment.clone(), final_data)]))
143	}
144}