1use fearless_simd::Level;
25use fearless_simd::Simd;
26use fearless_simd::dispatch;
27use fearless_simd_macros::simd;
28use vortex_buffer::BitBuffer;
29use vortex_mask::Mask;
30
31use crate::dtype::NativePType;
32use crate::dtype::half::f16;
33use crate::dtype::i256;
34
35const LANES: usize = 16;
37
38const CHUNK_LEN: usize = 1 << 31;
41
42pub trait MajorityKey: Copy + Default {
47 fn key_eq(self, other: Self) -> bool;
49}
50
51macro_rules! native_majority_key {
52 ($($T:ty),*) => {
53 $(
54 impl MajorityKey for $T {
55 #[inline]
56 fn key_eq(self, other: Self) -> bool {
57 NativePType::is_eq(self, other)
58 }
59 }
60 )*
61 };
62}
63
64native_majority_key!(u8, u16, u32, u64, i8, i16, i32, i64, f16, f32, f64);
65
66impl<const N: usize> MajorityKey for [u8; N]
68where
69 [u8; N]: Default,
70{
71 #[inline]
72 fn key_eq(self, other: Self) -> bool {
73 self == other
74 }
75}
76
77impl MajorityKey for i128 {
78 #[inline]
79 fn key_eq(self, other: Self) -> bool {
80 self == other
81 }
82}
83
84impl MajorityKey for i256 {
85 #[inline]
86 fn key_eq(self, other: Self) -> bool {
87 self == other
88 }
89}
90
91pub fn majority_candidate<T: MajorityKey>(values: &[T], validity: &Mask) -> Option<T> {
98 dispatch!(Level::new(), simd => majority_candidate_simd(simd, values, validity))
99}
100
101#[simd]
107fn majority_candidate_simd<S: Simd, T: MajorityKey>(
108 _: S,
109 values: &[T],
110 validity: &Mask,
111) -> Option<T> {
112 let first_valid = match validity {
113 Mask::AllTrue(len) => (*len > 0).then_some(0)?,
114 Mask::AllFalse(_) => return None,
115 Mask::Values(mask_values) => mask_values.bit_buffer().set_indices().next()?,
116 };
117 let mut merged = (T::default(), 0usize);
118 for (index, chunk) in values.chunks(CHUNK_LEN).enumerate() {
119 let start = index * CHUNK_LEN;
120 let vote = match validity {
121 Mask::Values(mask_values) => masked_lane_vote(
122 chunk,
123 &mask_values.bit_buffer().slice(start..start + chunk.len()),
124 ),
125 _ => lane_vote(chunk),
126 };
127 merged = merge_vote(merged, (vote.0, vote.1 as usize));
128 }
129 Some(if merged.1 > 0 {
132 merged.0
133 } else {
134 values[first_valid]
135 })
136}
137
138#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
140#[inline(always)]
141fn vote<T: MajorityKey>(candidate: &mut T, count: &mut u32, value: T) {
142 let empty = *count == 0;
143 let agrees = candidate.key_eq(value);
144 *candidate = if empty { value } else { *candidate };
145 *count = if empty | agrees {
146 *count + 1
147 } else {
148 *count - 1
149 };
150}
151
152#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
155#[inline(always)]
156fn masked_vote<T: MajorityKey>(candidate: &mut T, count: &mut u32, value: T, valid: bool) {
157 let empty = *count == 0;
158 let agrees = candidate.key_eq(value);
159 *candidate = if valid & empty { value } else { *candidate };
160 let up = valid & (empty | agrees);
161 let down = valid & !(empty | agrees);
162 *count = *count + u32::from(up) - u32::from(down);
163}
164
165#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
171#[inline(always)]
172fn merge_vote<
173 T: MajorityKey,
174 C: Copy + Ord + std::ops::Add<Output = C> + std::ops::Sub<Output = C>,
175>(
176 (candidate, count): (T, C),
177 (other, other_count): (T, C),
178) -> (T, C) {
179 if candidate.key_eq(other) {
180 (candidate, count + other_count)
181 } else if count >= other_count {
182 (candidate, count - other_count)
183 } else {
184 (other, other_count - count)
185 }
186}
187
188fn merge_lanes<T: MajorityKey>(candidates: [T; LANES], counts: [u32; LANES]) -> (T, u32) {
190 candidates
191 .into_iter()
192 .zip(counts)
193 .fold((T::default(), 0), merge_vote)
194}
195
196#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
197#[inline(always)]
198fn lane_vote<T: MajorityKey>(values: &[T]) -> (T, u32) {
199 let mut candidates = [T::default(); LANES];
200 let mut counts = [0u32; LANES];
201 let (chunks, remainder) = values.as_chunks::<LANES>();
202 for chunk in chunks {
203 for lane in 0..LANES {
204 vote(&mut candidates[lane], &mut counts[lane], chunk[lane]);
205 }
206 }
207 for (lane, &value) in remainder.iter().enumerate() {
208 vote(&mut candidates[lane], &mut counts[lane], value);
209 }
210 merge_lanes(candidates, counts)
211}
212
213#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
214#[inline(always)]
215fn masked_lane_vote<T: MajorityKey>(values: &[T], validity: &BitBuffer) -> (T, u32) {
216 let mut candidates = [T::default(); LANES];
217 let mut counts = [0u32; LANES];
218 let mut words = validity.chunks().iter_padded();
219 let (chunks, remainder) = values.as_chunks::<64>();
220 for (chunk, bits) in chunks.iter().zip(&mut words) {
221 for block in 0..64 / LANES {
222 for lane in 0..LANES {
223 let index = block * LANES + lane;
224 let valid = (bits >> index) & 1 == 1;
225 masked_vote(
226 &mut candidates[lane],
227 &mut counts[lane],
228 chunk[index],
229 valid,
230 );
231 }
232 }
233 }
234 let bits = words.next().unwrap_or(0);
235 for (index, &value) in remainder.iter().enumerate() {
236 let valid = (bits >> index) & 1 == 1;
237 masked_vote(
238 &mut candidates[index % LANES],
239 &mut counts[index % LANES],
240 value,
241 valid,
242 );
243 }
244 merge_lanes(candidates, counts)
245}
246
247#[cfg(test)]
248mod tests {
249 use rstest::rstest;
250
251 use super::*;
252
253 #[rstest]
254 #[case::shorter_than_lanes(7)]
255 #[case::not_a_multiple_of_64(1_001)]
256 fn wide_keys(#[case] len: usize) {
257 let values: Vec<i256> = (0..len)
258 .map(|index| {
259 if index % 3 == 0 {
260 i256::from_i128(index as i128)
261 } else {
262 i256::MAX
263 }
264 })
265 .collect();
266 assert_eq!(
267 majority_candidate(&values, &Mask::new_true(len)),
268 Some(i256::MAX)
269 );
270 }
271
272 #[test]
273 fn fixed_size_bytes() {
274 let values: Vec<[u8; 16]> = (0u8..100)
275 .map(|index| {
276 if index % 4 == 0 {
277 [index; 16]
278 } else {
279 *b"0123456789abcdef"
280 }
281 })
282 .collect();
283 assert_eq!(
284 majority_candidate(&values, &Mask::new_true(values.len())),
285 Some(*b"0123456789abcdef")
286 );
287 }
288
289 #[rstest]
291 #[case::all_valid(Mask::new_true(32))]
292 #[case::nullable(Mask::from_iter((0..32).map(|index| index % 2 == 1)))]
293 fn cancelled_votes_return_a_valid_value(#[case] validity: Mask) {
294 let values: Vec<u32> = (1..=32).collect();
295 let candidate = majority_candidate(&values, &validity).expect("values are valid");
296 let index = values.iter().position(|&value| value == candidate);
297 assert!(index.is_some_and(|index| validity.value(index)));
298 }
299
300 #[test]
301 fn nothing_valid() {
302 assert_eq!(majority_candidate::<u32>(&[], &Mask::new_true(0)), None);
303 assert_eq!(majority_candidate(&[5u32; 10], &Mask::new_false(10)), None);
304 }
305
306 #[rstest]
308 #[case::short(40)]
309 #[case::long(8_000)]
310 fn invalid_values_do_not_vote(#[case] len: usize) {
311 let values: Vec<u64> = (0..len)
312 .map(|index| if index % 8 < 3 { 9 } else { 0 })
313 .collect();
314 let validity = Mask::from_iter((0..len).map(|index| index % 8 < 4));
315 assert_eq!(majority_candidate(&values, &validity), Some(9));
316 }
317}