vortex_array/aggregate_fn/fns/is_constant/
primitive.rs1use vortex_error::VortexExpect;
5
6use crate::arrays::PrimitiveArray;
7use crate::match_each_ptype_width;
8
9cfg_if::cfg_if! {
10 if #[cfg(target_feature = "avx2")] {
11 pub const IS_CONST_LANE_WIDTH: usize = 32;
12 } else {
13 pub const IS_CONST_LANE_WIDTH: usize = 16;
14 }
15}
16
17pub fn compute_is_constant<T: Copy + PartialEq, const WIDTH: usize>(values: &[T]) -> bool {
22 let first_value = values[0];
23 let first_vec = &[first_value; WIDTH];
24
25 let (chunks, remainder) = values[1..].as_chunks::<WIDTH>();
26 for chunk in chunks {
27 if first_vec != chunk {
28 return false;
29 }
30 }
31
32 for value in remainder {
33 if *value != first_value {
34 return false;
35 }
36 }
37
38 true
39}
40
41pub(super) fn check_primitive_constant(array: &PrimitiveArray) -> bool {
42 let values = array
43 .buffer_handle()
44 .as_host_opt()
45 .vortex_expect("is_constant requires host values");
46
47 match_each_ptype_width!(
48 array.ptype(),
49 |W| {
50 compute_is_constant::<_, { IS_CONST_LANE_WIDTH / W }>(
51 values.as_slice().as_chunks::<W>().0,
52 )
53 },
54 _ => { unreachable!("primitive widths are specialized") },
55 )
56}
57
58#[cfg(test)]
59mod tests {
60 use rstest::rstest;
61
62 use super::check_primitive_constant;
63 use crate::arrays::PrimitiveArray;
64
65 #[rstest]
66 #[case::zero(&[0], true)]
67 #[case::signed_zero(&[0, 0x80000000], false)]
68 #[case::infinity(&[0x7f800000], true)]
69 #[case::same_nan(&[0x7fc00001], true)]
70 #[case::different_nan(&[0x7fc00001, 0x7fc00002], false)]
71 fn compares_stored_bits(
72 #[case] bits: &[u32],
73 #[case] expected: bool,
74 #[values(2, 16, 17, 65)] len: usize,
75 ) {
76 let values = bits.iter().copied().cycle().take(len).map(f32::from_bits);
77 let array = PrimitiveArray::from_iter(values);
78 assert_eq!(check_primitive_constant(&array), expected);
79 }
80}