1use std::cmp::Ordering;
27use std::sync::Arc;
28
29use arrow::array::{Array, ArrayRef, AsArray, make_array};
30use arrow::datatypes::{
31 ArrowPrimitiveType, DataType, Float16Type, Float32Type, Float64Type,
32};
33use half::f16;
34
35pub trait FloatSemantics: Copy {
38 fn needs_normalization(self) -> bool;
42
43 fn normalize(self) -> Self;
45
46 fn compare(self, other: Self) -> Ordering;
48}
49
50macro_rules! impl_float_semantics {
51 ($(($t:ty, $bits:ty, $zero:expr)),+ $(,)?) => {
52 $(impl FloatSemantics for $t {
53 #[inline]
54 fn needs_normalization(self) -> bool {
55 self.to_bits() == 1 << (<$bits>::BITS - 1)
58 }
59
60 #[inline]
61 fn normalize(self) -> Self {
62 if self.needs_normalization() { $zero } else { self }
63 }
64
65 #[inline]
66 fn compare(self, other: Self) -> Ordering {
67 self.total_cmp(&other)
68 }
69 })+
70 };
71}
72impl_float_semantics!((f16, u16, f16::ZERO), (f32, u32, 0.0), (f64, u64, 0.0));
73
74#[inline]
78pub fn normalize_float<T: FloatSemantics>(v: T) -> T {
79 v.normalize()
80}
81
82#[inline]
89pub fn compare_floats<T: FloatSemantics>(left: T, right: T) -> Ordering {
90 left.compare(right)
91}
92
93#[inline]
96pub fn float_lt<T: FloatSemantics>(left: T, right: T) -> bool {
97 compare_floats(left, right).is_lt()
98}
99
100#[inline]
103pub fn float_gt<T: FloatSemantics>(left: T, right: T) -> bool {
104 compare_floats(left, right).is_gt()
105}
106
107#[inline]
111pub fn hash_input<T: FloatSemantics>(v: T) -> T {
112 normalize_float(v)
113}
114
115pub fn normalize_floats(array: &ArrayRef) -> ArrayRef {
127 match array.data_type() {
128 DataType::Float16 => normalize_primitive::<Float16Type>(array),
129 DataType::Float32 => normalize_primitive::<Float32Type>(array),
130 DataType::Float64 => normalize_primitive::<Float64Type>(array),
131 dt if has_float_leaf(dt) => {
132 let data = array.to_data();
133 let children = data
134 .child_data()
135 .iter()
136 .map(|child| normalize_floats(&make_array(child.clone())).to_data())
137 .collect::<Vec<_>>();
138 if children
139 .iter()
140 .zip(data.child_data())
141 .all(|(new, old)| new.ptr_eq(old))
142 {
143 return Arc::clone(array);
144 }
145 make_array(
146 data.into_builder()
147 .child_data(children)
148 .build()
149 .expect("rewriting float leaves preserves the array layout"),
150 )
151 }
152 _ => Arc::clone(array),
153 }
154}
155
156fn normalize_primitive<T>(array: &ArrayRef) -> ArrayRef
157where
158 T: ArrowPrimitiveType,
159 T::Native: FloatSemantics,
160{
161 let arr = array.as_primitive::<T>();
162 if !arr.values().iter().any(|v| v.needs_normalization()) {
163 return Arc::clone(array);
164 }
165 Arc::new(arr.unary::<_, T>(normalize_float))
166}
167
168pub fn has_float_leaf(data_type: &DataType) -> bool {
171 match data_type {
172 DataType::Float16 | DataType::Float32 | DataType::Float64 => true,
173 DataType::List(f)
174 | DataType::LargeList(f)
175 | DataType::ListView(f)
176 | DataType::LargeListView(f)
177 | DataType::FixedSizeList(f, _)
178 | DataType::Map(f, _)
179 | DataType::RunEndEncoded(_, f) => has_float_leaf(f.data_type()),
180 DataType::Struct(fields) => fields.iter().any(|f| has_float_leaf(f.data_type())),
181 DataType::Union(fields, _) => {
182 fields.iter().any(|(_, f)| has_float_leaf(f.data_type()))
183 }
184 DataType::Dictionary(_, values) => has_float_leaf(values),
185 _ => false,
186 }
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192 use crate::{Result, ScalarValue};
193 use arrow::array::{
194 DictionaryArray, Float16Array, Float32Array, Float64Array, Int8Array, Int32Array,
195 ListArray,
196 };
197 use arrow::datatypes::{Field, Int8Type, Int32Type};
198
199 #[test]
200 fn normalize_float_folds_negative_zero() {
201 assert_eq!(normalize_float(-0.0_f64).to_bits(), 0.0_f64.to_bits());
202 assert_eq!(normalize_float(-0.0_f32).to_bits(), 0.0_f32.to_bits());
203 assert_eq!(
204 normalize_float(f16::NEG_ZERO).to_bits(),
205 f16::ZERO.to_bits()
206 );
207 assert_eq!(
208 hash_input(-0.0_f64).to_bits(),
209 hash_input(0.0_f64).to_bits()
210 );
211 assert!((-0.0_f64).needs_normalization());
212 assert!(!0.0_f64.needs_normalization());
213 }
214
215 #[test]
216 fn normalize_float_keeps_other_values() {
217 let neg_nan = f64::from_bits(f64::NAN.to_bits() | (1 << 63));
218 let payload_nan = f64::from_bits(f64::NAN.to_bits() | 1);
219 for v in [
220 1.5,
221 -1.5,
222 f64::INFINITY,
223 f64::NEG_INFINITY,
224 f64::MIN_POSITIVE,
225 -f64::MIN_POSITIVE,
226 f64::NAN,
227 neg_nan,
228 payload_nan,
229 ] {
230 assert!(!v.needs_normalization());
231 assert_eq!(normalize_float(v).to_bits(), v.to_bits());
232 }
233 }
234
235 #[test]
236 fn compare_floats_is_total_order() {
237 let neg_nan = f64::from_bits(f64::NAN.to_bits() | (1 << 63));
238 assert_eq!(compare_floats(1.0_f64, 2.0), Ordering::Less);
239 assert_eq!(compare_floats(-0.0_f64, 0.0), Ordering::Less);
240 assert_eq!(compare_floats(f64::NAN, f64::INFINITY), Ordering::Greater);
241 assert_eq!(compare_floats(neg_nan, f64::NEG_INFINITY), Ordering::Less);
242 assert_eq!(compare_floats(f16::ONE, f16::ZERO), Ordering::Greater);
243 assert!(float_lt(1.0_f64, 2.0) && !float_lt(2.0_f64, 1.0));
244 assert!(float_gt(f64::NAN, f64::INFINITY) && !float_gt(1.0_f64, 1.0));
245 }
246
247 #[test]
248 fn normalize_floats_rewrites_negative_zero() {
249 let array: ArrayRef =
250 Arc::new(Float64Array::from(vec![Some(-0.0), None, Some(1.0)]));
251 let result = normalize_floats(&array);
252 let result = result.as_primitive::<Float64Type>();
253 assert_eq!(result.value(0).to_bits(), 0.0_f64.to_bits());
254 assert!(result.is_null(1));
255 assert_eq!(result.value(2), 1.0);
256
257 let array: ArrayRef = Arc::new(Float32Array::from(vec![-0.0_f32]));
258 let result = normalize_floats(&array);
259 assert_eq!(
260 result.as_primitive::<Float32Type>().value(0).to_bits(),
261 0.0_f32.to_bits()
262 );
263
264 let array: ArrayRef = Arc::new(Float16Array::from(vec![f16::NEG_ZERO]));
265 let result = normalize_floats(&array);
266 assert_eq!(
267 result.as_primitive::<Float16Type>().value(0).to_bits(),
268 f16::ZERO.to_bits()
269 );
270 }
271
272 #[test]
273 fn normalize_floats_reuses_normalized_input() {
274 let array: ArrayRef = Arc::new(Float64Array::from(vec![0.0, 1.0, f64::NAN]));
275 assert!(Arc::ptr_eq(&normalize_floats(&array), &array));
276
277 let array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2]));
278 assert!(Arc::ptr_eq(&normalize_floats(&array), &array));
279 }
280
281 #[test]
282 fn normalize_floats_rewrites_nested_floats() {
283 let list = ListArray::from_iter_primitive::<Float64Type, _, _>(vec![
284 Some(vec![Some(-0.0), Some(2.0)]),
285 None,
286 ]);
287 let array: ArrayRef = Arc::new(list);
288 let result = normalize_floats(&array);
289 assert!(!Arc::ptr_eq(&result, &array));
290 let values = result.as_list::<i32>().value(0);
291 assert_eq!(
292 values.as_primitive::<Float64Type>().value(0).to_bits(),
293 0.0_f64.to_bits()
294 );
295 assert!(result.is_null(1));
296
297 let list =
298 ListArray::from_iter_primitive::<Int32Type, _, _>(vec![Some(vec![Some(1)])]);
299 let array: ArrayRef = Arc::new(list);
300 assert!(Arc::ptr_eq(&normalize_floats(&array), &array));
301 }
302
303 #[test]
304 fn normalize_floats_in_dictionary_arrays_and_scalars() -> Result<()> {
305 let nan = f64::from_bits(0x7ff8_0000_0000_0001);
306 let keys = Int8Array::from(vec![Some(0), Some(1), None, Some(2)]);
307 let array: ArrayRef = Arc::new(DictionaryArray::try_new(
308 keys.clone(),
309 Arc::new(Float64Array::from(vec![-0.0, nan, 1.0])),
310 )?);
311
312 let normalized = normalize_floats(&array);
313 let dictionary = normalized.as_dictionary::<Int8Type>();
314 assert_eq!(dictionary.keys(), &keys);
315 let values = dictionary.values().as_primitive::<Float64Type>();
316 assert_eq!(values.value(0).to_bits(), 0.0_f64.to_bits());
317 assert_eq!(values.value(1).to_bits(), nan.to_bits());
318 assert_eq!(values.value(2), 1.0);
319
320 assert!(Arc::ptr_eq(&normalize_floats(&normalized), &normalized));
321
322 assert_eq!(
323 ScalarValue::try_from_array(&array, 0)?.normalize(),
324 ScalarValue::try_from_array(&normalized, 0)?
325 );
326
327 Ok(())
328 }
329
330 #[test]
331 fn normalize_preserves_union_and_run_metadata() -> Result<()> {
332 use arrow::datatypes::{UnionFields, UnionMode};
333
334 let run_ends = Arc::new(Field::new("ends", DataType::Int32, false));
335 let values = Arc::new(Field::new("samples", DataType::Float64, true));
336 let fields = UnionFields::try_new(
337 [7, 42],
338 [
339 Field::new(
340 "runs",
341 DataType::RunEndEncoded(Arc::clone(&run_ends), Arc::clone(&values)),
342 true,
343 ),
344 Field::new("other", DataType::Int32, true),
345 ],
346 )?;
347 let nan = f64::from_bits(0x7ff8_0000_0000_0001);
348 for mode in [UnionMode::Sparse, UnionMode::Dense] {
349 let wrap = |value| {
350 ScalarValue::Union(
351 Some((
352 7,
353 Box::new(ScalarValue::RunEndEncoded(
354 Arc::clone(&run_ends),
355 Arc::clone(&values),
356 Box::new(ScalarValue::Float64(value)),
357 )),
358 )),
359 fields.clone(),
360 mode,
361 )
362 };
363 for (value, expected) in [
364 (Some(-0.0), Some(0.0)),
365 (Some(nan), Some(nan)),
366 (None, None),
367 ] {
368 assert_eq!(wrap(value).normalize(), wrap(expected));
369 }
370 let null = ScalarValue::Union(None, fields.clone(), mode);
371 assert_eq!(null.clone().normalize(), null);
372 }
373 Ok(())
374 }
375
376 #[test]
377 fn normalize_preserves_sliced_list() {
378 let nan = f64::from_bits(0x7ff8_0000_0000_0001);
379 let list = Arc::new(
380 ListArray::from_iter_primitive::<Float64Type, _, _>([
381 Some(vec![Some(99.0)]),
382 Some(vec![Some(-0.0), Some(nan), None]),
383 Some(vec![Some(42.0)]),
384 ])
385 .slice(1, 1),
386 );
387 let ScalarValue::List(normalized) = ScalarValue::List(list).normalize() else {
388 panic!("normalization must preserve the scalar variant");
389 };
390 assert_eq!(normalized.len(), 1);
391 let child = normalized.value(0);
392 let child = child.as_primitive::<Float64Type>();
393 assert_eq!(child.len(), 3);
394 assert_eq!(child.value(0).to_bits(), 0.0_f64.to_bits());
395 assert_eq!(child.value(1).to_bits(), nan.to_bits());
396 assert!(child.is_null(2));
397 }
398}