use fearless_simd::Level;
use fearless_simd::Simd;
use fearless_simd::dispatch;
use fearless_simd_macros::simd;
use vortex_buffer::BitBuffer;
use vortex_mask::Mask;
use crate::dtype::NativePType;
use crate::dtype::half::f16;
use crate::dtype::i256;
const LANES: usize = 16;
const CHUNK_LEN: usize = 1 << 31;
pub trait MajorityKey: Copy + Default {
fn key_eq(self, other: Self) -> bool;
}
macro_rules! native_majority_key {
($($T:ty),*) => {
$(
impl MajorityKey for $T {
#[inline]
fn key_eq(self, other: Self) -> bool {
NativePType::is_eq(self, other)
}
}
)*
};
}
native_majority_key!(u8, u16, u32, u64, i8, i16, i32, i64, f16, f32, f64);
impl<const N: usize> MajorityKey for [u8; N]
where
[u8; N]: Default,
{
#[inline]
fn key_eq(self, other: Self) -> bool {
self == other
}
}
impl MajorityKey for i128 {
#[inline]
fn key_eq(self, other: Self) -> bool {
self == other
}
}
impl MajorityKey for i256 {
#[inline]
fn key_eq(self, other: Self) -> bool {
self == other
}
}
pub fn majority_candidate<T: MajorityKey>(values: &[T], validity: &Mask) -> Option<T> {
dispatch!(Level::new(), simd => majority_candidate_simd(simd, values, validity))
}
#[simd]
fn majority_candidate_simd<S: Simd, T: MajorityKey>(
_: S,
values: &[T],
validity: &Mask,
) -> Option<T> {
let first_valid = match validity {
Mask::AllTrue(len) => (*len > 0).then_some(0)?,
Mask::AllFalse(_) => return None,
Mask::Values(mask_values) => mask_values.bit_buffer().set_indices().next()?,
};
let mut merged = (T::default(), 0usize);
for (index, chunk) in values.chunks(CHUNK_LEN).enumerate() {
let start = index * CHUNK_LEN;
let vote = match validity {
Mask::Values(mask_values) => masked_lane_vote(
chunk,
&mask_values.bit_buffer().slice(start..start + chunk.len()),
),
_ => lane_vote(chunk),
};
merged = merge_vote(merged, (vote.0, vote.1 as usize));
}
Some(if merged.1 > 0 {
merged.0
} else {
values[first_valid]
})
}
#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
#[inline(always)]
fn vote<T: MajorityKey>(candidate: &mut T, count: &mut u32, value: T) {
let empty = *count == 0;
let agrees = candidate.key_eq(value);
*candidate = if empty { value } else { *candidate };
*count = if empty | agrees {
*count + 1
} else {
*count - 1
};
}
#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
#[inline(always)]
fn masked_vote<T: MajorityKey>(candidate: &mut T, count: &mut u32, value: T, valid: bool) {
let empty = *count == 0;
let agrees = candidate.key_eq(value);
*candidate = if valid & empty { value } else { *candidate };
let up = valid & (empty | agrees);
let down = valid & !(empty | agrees);
*count = *count + u32::from(up) - u32::from(down);
}
#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
#[inline(always)]
fn merge_vote<
T: MajorityKey,
C: Copy + Ord + std::ops::Add<Output = C> + std::ops::Sub<Output = C>,
>(
(candidate, count): (T, C),
(other, other_count): (T, C),
) -> (T, C) {
if candidate.key_eq(other) {
(candidate, count + other_count)
} else if count >= other_count {
(candidate, count - other_count)
} else {
(other, other_count - count)
}
}
fn merge_lanes<T: MajorityKey>(candidates: [T; LANES], counts: [u32; LANES]) -> (T, u32) {
candidates
.into_iter()
.zip(counts)
.fold((T::default(), 0), merge_vote)
}
#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
#[inline(always)]
fn lane_vote<T: MajorityKey>(values: &[T]) -> (T, u32) {
let mut candidates = [T::default(); LANES];
let mut counts = [0u32; LANES];
let (chunks, remainder) = values.as_chunks::<LANES>();
for chunk in chunks {
for lane in 0..LANES {
vote(&mut candidates[lane], &mut counts[lane], chunk[lane]);
}
}
for (lane, &value) in remainder.iter().enumerate() {
vote(&mut candidates[lane], &mut counts[lane], value);
}
merge_lanes(candidates, counts)
}
#[expect(clippy::inline_always, reason = "see `majority_candidate_simd`")]
#[inline(always)]
fn masked_lane_vote<T: MajorityKey>(values: &[T], validity: &BitBuffer) -> (T, u32) {
let mut candidates = [T::default(); LANES];
let mut counts = [0u32; LANES];
let mut words = validity.chunks().iter_padded();
let (chunks, remainder) = values.as_chunks::<64>();
for (chunk, bits) in chunks.iter().zip(&mut words) {
for block in 0..64 / LANES {
for lane in 0..LANES {
let index = block * LANES + lane;
let valid = (bits >> index) & 1 == 1;
masked_vote(
&mut candidates[lane],
&mut counts[lane],
chunk[index],
valid,
);
}
}
}
let bits = words.next().unwrap_or(0);
for (index, &value) in remainder.iter().enumerate() {
let valid = (bits >> index) & 1 == 1;
masked_vote(
&mut candidates[index % LANES],
&mut counts[index % LANES],
value,
valid,
);
}
merge_lanes(candidates, counts)
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::*;
#[rstest]
#[case::shorter_than_lanes(7)]
#[case::not_a_multiple_of_64(1_001)]
fn wide_keys(#[case] len: usize) {
let values: Vec<i256> = (0..len)
.map(|index| {
if index % 3 == 0 {
i256::from_i128(index as i128)
} else {
i256::MAX
}
})
.collect();
assert_eq!(
majority_candidate(&values, &Mask::new_true(len)),
Some(i256::MAX)
);
}
#[test]
fn fixed_size_bytes() {
let values: Vec<[u8; 16]> = (0u8..100)
.map(|index| {
if index % 4 == 0 {
[index; 16]
} else {
*b"0123456789abcdef"
}
})
.collect();
assert_eq!(
majority_candidate(&values, &Mask::new_true(values.len())),
Some(*b"0123456789abcdef")
);
}
#[rstest]
#[case::all_valid(Mask::new_true(32))]
#[case::nullable(Mask::from_iter((0..32).map(|index| index % 2 == 1)))]
fn cancelled_votes_return_a_valid_value(#[case] validity: Mask) {
let values: Vec<u32> = (1..=32).collect();
let candidate = majority_candidate(&values, &validity).expect("values are valid");
let index = values.iter().position(|&value| value == candidate);
assert!(index.is_some_and(|index| validity.value(index)));
}
#[test]
fn nothing_valid() {
assert_eq!(majority_candidate::<u32>(&[], &Mask::new_true(0)), None);
assert_eq!(majority_candidate(&[5u32; 10], &Mask::new_false(10)), None);
}
#[rstest]
#[case::short(40)]
#[case::long(8_000)]
fn invalid_values_do_not_vote(#[case] len: usize) {
let values: Vec<u64> = (0..len)
.map(|index| if index % 8 < 3 { 9 } else { 0 })
.collect();
let validity = Mask::from_iter((0..len).map(|index| index % 8 < 4));
assert_eq!(majority_candidate(&values, &validity), Some(9));
}
}