kiddo 6.0.0-alpha.2

A high-performance, flexible, ergonomic k-d tree library. Ideal for geo- and astro- nearest-neighbour and k-nearest-neighbor queries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Type-specific block comparison traits for Donnelly SIMD strategies.
//!
//! Replaces size_of-based dispatch with explicit trait implementations per type.

use std::ptr::NonNull;

/// Trait for comparing a query value against 7 pivots in a Block3 (3-level block).
///
/// Block3 produces 8 possible children (2^3).
///
/// Default implementation panics - types must provide actual implementations to support Block3.
pub trait CompareBlock3: Copy {
    /// Compare query value against block pivots, returning child index (0-7).
    ///
    /// # Arguments
    /// * `stems_ptr` - Pointer to start of stems array (cast to u8 for offset calc)
    /// * `query_val` - Query value in this dimension
    /// * `block_base_idx` - Cache-line base index for this block
    ///
    /// # Returns
    /// Child index (0-7) indicating which of 8 children the query falls into.
    ///
    /// # Panics
    /// Default implementation panics. Override this method to support Block3 traversal.
    fn compare_block3_impl(
        _stems_ptr: NonNull<u8>,
        _query_val: Self,
        _block_base_idx: usize,
    ) -> u8 {
        unimplemented!(
            "Type {} does not support Block3 comparison. Use a supported type (f32, f64, or fixed-point types) \
             or implement CompareBlock3 trait.",
            std::any::type_name::<Self>()
        )
    }
}

/// Trait for comparing a query value against 15 pivots in a Block4 (4-level block).
///
/// Block4 produces 16 possible children (2^4).
///
/// Default implementation panics - types must provide actual implementations to support Block4.
pub trait CompareBlock4: Copy {
    /// Compare query value against block pivots, returning child index (0-15).
    ///
    /// # Arguments
    /// * `stems_ptr` - Pointer to start of stems array (cast to u8 for offset calc)
    /// * `query_val` - Query value in this dimension
    /// * `block_base_idx` - Cache-line base index for this block
    ///
    /// # Returns
    /// Child index (0-15) indicating which of 16 children the query falls into.
    ///
    /// # Panics
    /// Default implementation panics. Override this method to support Block4 traversal.
    fn compare_block4_impl(
        _stems_ptr: NonNull<u8>,
        _query_val: Self,
        _block_base_idx: usize,
    ) -> u8 {
        unimplemented!(
            "Type {} does not support Block4 comparison. Use a supported type (f32, or f64 on 128-byte cache line systems) \
             or implement CompareBlock4 trait.",
            std::any::type_name::<Self>()
        )
    }
}

/// Autovectorization-friendly comparison macro for block traversal.
///
/// Compares query value against `$pivot_count + 1` pivots (includes padding).
/// Returns count of pivots <= query_val, which maps to child index.
///
/// # Parameters
/// * `$pivot_count` - Number of actual pivots (7 for Block3, 15 for Block4)
/// * `$ty` - Type of values being compared
/// * `$stems_ptr` - `NonNull<u8>` pointer to stems
/// * `$block_base_idx` - Cache line base index
/// * `$query_val` - Query value to compare
macro_rules! autovec_compare_block {
    ($pivot_count:expr, $ty:ty, $stems_ptr:expr, $block_base_idx:expr, $query_val:expr) => {{
        unsafe {
            let ptr = $stems_ptr
                .as_ptr()
                .add($block_base_idx * std::mem::size_of::<$ty>())
                as *const $ty;
            let mut count = 0u8;
            // Loop over pivot_count + 1 to include padding
            for i in 0..($pivot_count + 1) {
                if $query_val >= *ptr.add(i) {
                    count += 1;
                }
            }
            count
        }
    }};
}

// ====================================================================================
// f64 implementations
// ====================================================================================

impl CompareBlock3 for f64 {
    #[inline(always)]
    fn compare_block3_impl(stems_ptr: NonNull<u8>, query_val: Self, block_base_idx: usize) -> u8 {
        #[cfg(all(feature = "simd", target_arch = "x86_64"))]
        {
            #[cfg(target_feature = "avx512f")]
            {
                unsafe {
                    use std::arch::x86_64::*;

                    let ptr = stems_ptr.as_ptr().add(block_base_idx * 8) as *const f64;
                    let pivots = _mm512_loadu_pd(ptr);
                    let query_vec = _mm512_set1_pd(query_val);
                    let mask = _mm512_cmp_pd_mask(query_vec, pivots, _CMP_GE_OQ);
                    _popcnt32(mask as i32) as u8
                }
            }

            #[cfg(not(target_feature = "avx512f"))]
            {
                unsafe {
                    use std::arch::x86_64::*;

                    let ptr = stems_ptr.as_ptr().add(block_base_idx * 8) as *const f64;
                    let pivots_low = _mm256_loadu_pd(ptr);
                    let pivots_high = _mm256_loadu_pd(ptr.add(4));
                    let query_vec = _mm256_set1_pd(query_val);

                    let cmp_low = _mm256_cmp_pd(query_vec, pivots_low, _CMP_GE_OQ);
                    let cmp_high = _mm256_cmp_pd(query_vec, pivots_high, _CMP_GE_OQ);

                    let mask_low = _mm256_movemask_pd(cmp_low) as u32;
                    let mask_high = _mm256_movemask_pd(cmp_high) as u32;
                    let mask = mask_low | (mask_high << 4);

                    _popcnt32(mask as i32) as u8
                }
            }
        }

        #[cfg(all(feature = "simd", target_arch = "aarch64"))]
        {
            unsafe {
                crate::stem_strategy::donnelly::simd_full::aarch64::compare_block3_f64_neon(
                    stems_ptr,
                    block_base_idx,
                    query_val,
                )
            }
        }

        #[cfg(not(any(
            all(feature = "simd", target_arch = "x86_64"),
            all(feature = "simd", target_arch = "aarch64")
        )))]
        {
            unsafe {
                crate::stem_strategy::donnelly::simd_full::autovec::compare_block3_f64_autovec(
                    stems_ptr,
                    block_base_idx,
                    query_val,
                )
            }
        }
    }
}

// f64 Block4: Only compile on 128-byte cache line systems
#[cfg(cache_line_128)]
impl CompareBlock4 for f64 {
    #[inline(always)]
    fn compare_block4_impl(stems_ptr: NonNull<u8>, query_val: Self, block_base_idx: usize) -> u8 {
        // For now, only autovec (no SIMD intrinsics for f64 Block4 yet)
        autovec_compare_block!(15, f64, stems_ptr, block_base_idx, query_val)
    }
}

// f64 Block4 on 64-byte cache lines: use default unimplemented!() from trait
#[cfg(not(cache_line_128))]
impl CompareBlock4 for f64 {}

// ====================================================================================
// f32 implementations
// ====================================================================================

impl CompareBlock3 for f32 {
    #[inline(always)]
    fn compare_block3_impl(stems_ptr: NonNull<u8>, query_val: Self, block_base_idx: usize) -> u8 {
        #[cfg(all(feature = "simd", target_arch = "x86_64"))]
        {
            #[cfg(target_feature = "avx512f")]
            {
                unsafe {
                    use std::arch::x86_64::*;

                    let ptr = stems_ptr.as_ptr().add(block_base_idx * 4) as *const f32;
                    let pivots = _mm256_loadu_ps(ptr);
                    let query_vec = _mm256_set1_ps(query_val);
                    let mask = _mm256_cmp_ps_mask(query_vec, pivots, _CMP_GE_OQ);
                    _popcnt32(mask as i32) as u8
                }
            }

            #[cfg(not(target_feature = "avx512f"))]
            {
                unsafe {
                    use std::arch::x86_64::*;

                    let ptr = stems_ptr.as_ptr().add(block_base_idx * 4) as *const f32;
                    let pivots = _mm256_loadu_ps(ptr);
                    let query_vec = _mm256_set1_ps(query_val);

                    let cmp = _mm256_cmp_ps(query_vec, pivots, _CMP_GE_OQ);
                    let mask = _mm256_movemask_ps(cmp) as u32;

                    _popcnt32(mask as i32) as u8
                }
            }
        }

        #[cfg(all(feature = "simd", target_arch = "aarch64"))]
        {
            unsafe {
                crate::stem_strategy::donnelly::simd_full::aarch64::compare_block3_f32_neon(
                    stems_ptr,
                    block_base_idx,
                    query_val,
                )
            }
        }

        #[cfg(not(any(
            all(feature = "simd", target_arch = "x86_64"),
            all(feature = "simd", target_arch = "aarch64")
        )))]
        {
            unsafe {
                crate::stem_strategy::donnelly::simd_full::autovec::compare_block3_f32_autovec(
                    stems_ptr,
                    block_base_idx,
                    query_val,
                )
            }
        }
    }
}

impl CompareBlock4 for f32 {
    #[inline(always)]
    fn compare_block4_impl(stems_ptr: NonNull<u8>, query_val: Self, block_base_idx: usize) -> u8 {
        #[cfg(all(feature = "simd", target_arch = "x86_64"))]
        {
            #[cfg(target_feature = "avx512f")]
            {
                unsafe {
                    use std::arch::x86_64::*;

                    let ptr = stems_ptr.as_ptr().add(block_base_idx * 4) as *const f32;
                    let pivots = _mm512_loadu_ps(ptr);
                    let query_vec = _mm512_set1_ps(query_val);

                    let mask = _mm512_cmp_ps_mask(query_vec, pivots, _CMP_GE_OQ);
                    _popcnt32(mask as i32) as u8
                }
            }

            #[cfg(not(target_feature = "avx512f"))]
            {
                unsafe {
                    use std::arch::x86_64::*;

                    let ptr = stems_ptr.as_ptr().add(block_base_idx * 4) as *const f32;
                    let pivots_low = _mm256_loadu_ps(ptr);
                    let pivots_high = _mm256_loadu_ps(ptr.add(8));
                    let query_vec = _mm256_set1_ps(query_val);

                    let cmp_low = _mm256_cmp_ps(query_vec, pivots_low, _CMP_GE_OQ);
                    let cmp_high = _mm256_cmp_ps(query_vec, pivots_high, _CMP_GE_OQ);

                    let mask_low = _mm256_movemask_ps(cmp_low) as u32;
                    let mask_high = _mm256_movemask_ps(cmp_high) as u32;
                    let mask = mask_low | (mask_high << 8);

                    _popcnt32(mask as i32) as u8
                }
            }
        }

        #[cfg(all(feature = "simd", target_arch = "aarch64"))]
        {
            unsafe {
                crate::stem_strategy::donnelly::simd_full::aarch64::compare_block4_f32_neon(
                    stems_ptr,
                    block_base_idx,
                    query_val,
                )
            }
        }

        #[cfg(not(any(
            all(feature = "simd", target_arch = "x86_64"),
            all(feature = "simd", target_arch = "aarch64")
        )))]
        {
            unsafe {
                crate::stem_strategy::donnelly::simd_full::autovec::compare_block4_f32_autovec(
                    stems_ptr,
                    block_base_idx,
                    query_val,
                )
            }
        }
    }
}

// ====================================================================================
// Fixed-point implementations
// ====================================================================================

#[cfg(feature = "fixed")]
mod fixed_impls {
    use super::*;
    use fixed::{types::extra, FixedI32, FixedU16};

    type U0 = extra::U0;
    type U16 = extra::U16;
    type U8 = extra::U8;

    /// Macro to implement CompareBlock traits for fixed-point types.
    ///
    /// Currently uses autovec for all architectures. Future work could add
    /// integer SIMD intrinsics (e.g., _mm256_cmpgt_epi32 for signed comparisons).
    ///
    /// Note: The $frac parameter is preserved even though comparison logic is the same
    /// for all fractional bit variants, because future SIMD implementations may need
    /// type-specific handling for other operations.
    macro_rules! impl_compare_fixed {
        ($fixed_ty:ty, $frac:ty) => {
            impl CompareBlock3 for $fixed_ty {
                #[inline(always)]
                fn compare_block3_impl(
                    stems_ptr: NonNull<u8>,
                    query_val: Self,
                    block_base_idx: usize,
                ) -> u8 {
                    autovec_compare_block!(7, $fixed_ty, stems_ptr, block_base_idx, query_val)
                }
            }

            impl CompareBlock4 for $fixed_ty {
                #[inline(always)]
                fn compare_block4_impl(
                    stems_ptr: NonNull<u8>,
                    query_val: Self,
                    block_base_idx: usize,
                ) -> u8 {
                    autovec_compare_block!(15, $fixed_ty, stems_ptr, block_base_idx, query_val)
                }
            }
        };
    }

    // Implement for all fixed-point types that have AxisUnified impls
    impl_compare_fixed!(FixedI32<U16>, U16);
    impl_compare_fixed!(FixedI32<U0>, U0);
    impl_compare_fixed!(FixedU16<U8>, U8);
}

// ====================================================================================
// f16 implementations
// ====================================================================================

#[cfg(feature = "f16")]
mod f16_impls {
    use super::*;
    use half::f16;

    impl CompareBlock3 for f16 {
        #[inline(always)]
        fn compare_block3_impl(
            stems_ptr: NonNull<u8>,
            query_val: Self,
            block_base_idx: usize,
        ) -> u8 {
            // Autovec for now; future optimization could widen to f32 for SIMD
            autovec_compare_block!(7, f16, stems_ptr, block_base_idx, query_val)
        }
    }

    impl CompareBlock4 for f16 {
        #[inline(always)]
        fn compare_block4_impl(
            stems_ptr: NonNull<u8>,
            query_val: Self,
            block_base_idx: usize,
        ) -> u8 {
            autovec_compare_block!(15, f16, stems_ptr, block_base_idx, query_val)
        }
    }
}

/// Macro to implement CompareBlock traits for uint types.
///
/// Currently uses autovec for all architectures. Future work could add
/// integer SIMD intrinsics (e.g., _mm256_cmpgt_epi32 for comparisons).
macro_rules! impl_compare_uint {
    ($uint_ty:ty) => {
        impl CompareBlock3 for $uint_ty {
            #[inline(always)]
            fn compare_block3_impl(
                stems_ptr: NonNull<u8>,
                query_val: Self,
                block_base_idx: usize,
            ) -> u8 {
                autovec_compare_block!(7, $uint_ty, stems_ptr, block_base_idx, query_val)
            }
        }

        impl CompareBlock4 for $uint_ty {
            #[inline(always)]
            fn compare_block4_impl(
                stems_ptr: NonNull<u8>,
                query_val: Self,
                block_base_idx: usize,
            ) -> u8 {
                autovec_compare_block!(15, $uint_ty, stems_ptr, block_base_idx, query_val)
            }
        }
    };
}

impl_compare_uint!(u8);
impl_compare_uint!(u16);
impl_compare_uint!(u32);