terrio 0.5.0

Pure-Rust geospatial raster, vector and point cloud data I/O: read, write, convert and reproject GIS formats without C dependencies
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! A static k-d tree over 2D or 3D points, for nearest-neighbour and radius searches.

/// The most points in a leaf.
const LEAF: usize = 16;

/// A node: a leaf (a range of `order`) or a split.
#[derive(Debug, Clone, Copy)]
enum Node {
    Leaf { start: u32, end: u32 },
    Split { dim: u8, value: f64, left: u32, right: u32 },
}

/// A k-d tree of `D`-dimensional points.
#[derive(Debug, Clone)]
pub(crate) struct KdTree<const D: usize> {
    points: Vec<[f64; D]>,
    order: Vec<u32>,
    nodes: Vec<Node>,
}

impl<const D: usize> KdTree<D> {
    /// Builds the tree of points.
    pub fn new(points: Vec<[f64; D]>) -> Self {
        let mut order: Vec<u32> = (0..points.len() as u32).collect();
        let mut nodes = Vec::new();
        if !points.is_empty() {
            let n = order.len();
            build(&points, &mut order, 0, n, &mut nodes);
        }
        Self { points, order, nodes }
    }

    /// The point at an index.
    pub fn point(&self, i: usize) -> &[f64; D] {
        &self.points[i]
    }

    /// The `k` nearest points to `q`: `(squared distance, index)`, nearest first (ties by index).
    pub fn knn(&self, q: &[f64; D], k: usize, out: &mut Vec<(f64, u32)>) {
        out.clear();
        if self.nodes.is_empty() || k == 0 {
            return;
        }
        self.knn_node(0, q, k, out);
    }

    fn knn_node(&self, node: usize, q: &[f64; D], k: usize, out: &mut Vec<(f64, u32)>) {
        match self.nodes[node] {
            Node::Leaf { start, end } => {
                for &i in &self.order[start as usize..end as usize] {
                    let d = dist2(&self.points[i as usize], q);
                    if out.len() == k && !less(d, i, out[k - 1]) {
                        continue;
                    }
                    let at = out.partition_point(|e| less(e.0, e.1, (d, i)));
                    out.insert(at, (d, i));
                    out.truncate(k);
                }
            }
            Node::Split { dim, value, left, right } => {
                let diff = q[dim as usize] - value;
                let (near, far) = if diff < 0.0 { (left, right) } else { (right, left) };
                self.knn_node(near as usize, q, k, out);
                if out.len() < k || diff * diff <= out[k - 1].0 {
                    self.knn_node(far as usize, q, k, out);
                }
            }
        }
    }

    /// The number of points closer than `r` to `q` (squared distance below `r²`).
    pub fn count_within(&self, q: &[f64; D], r: f64) -> usize {
        let mut n = 0;
        self.within(q, r, &mut |_| n += 1);
        n
    }

    /// Calls `f` with the index of each point closer than `r` to `q`.
    pub fn within(&self, q: &[f64; D], r: f64, f: &mut impl FnMut(u32)) {
        if !self.nodes.is_empty() {
            self.within_node(0, q, r * r, f);
        }
    }

    /// Calls `f` with the index of each point in a box (bounds included).
    pub fn within_box(&self, lo: &[f64; D], hi: &[f64; D], f: &mut impl FnMut(u32)) {
        if !self.nodes.is_empty() {
            self.box_node(0, lo, hi, f);
        }
    }

    fn box_node(&self, node: usize, lo: &[f64; D], hi: &[f64; D], f: &mut impl FnMut(u32)) {
        match self.nodes[node] {
            Node::Leaf { start, end } => {
                for &i in &self.order[start as usize..end as usize] {
                    let p = &self.points[i as usize];
                    if (0..D).all(|k| p[k] >= lo[k] && p[k] <= hi[k]) {
                        f(i);
                    }
                }
            }
            Node::Split { dim, value, left, right } => {
                if lo[dim as usize] <= value {
                    self.box_node(left as usize, lo, hi, f);
                }
                if hi[dim as usize] >= value {
                    self.box_node(right as usize, lo, hi, f);
                }
            }
        }
    }

    fn within_node(&self, node: usize, q: &[f64; D], r2: f64, f: &mut impl FnMut(u32)) {
        match self.nodes[node] {
            Node::Leaf { start, end } => {
                for &i in &self.order[start as usize..end as usize] {
                    if dist2(&self.points[i as usize], q) < r2 {
                        f(i);
                    }
                }
            }
            Node::Split { dim, value, left, right } => {
                let diff = q[dim as usize] - value;
                if diff < 0.0 || diff * diff < r2 {
                    self.within_node(left as usize, q, r2, f);
                }
                if diff >= 0.0 || diff * diff < r2 {
                    self.within_node(right as usize, q, r2, f);
                }
            }
        }
    }
}

/// Whether `(d, i)` comes before `e`: nearer, or as near with a smaller index.
fn less(d: f64, i: u32, e: (f64, u32)) -> bool {
    d < e.0 || (d == e.0 && i < e.1)
}

fn dist2<const D: usize>(a: &[f64; D], b: &[f64; D]) -> f64 {
    let mut s = 0.0;
    for k in 0..D {
        let d = a[k] - b[k];
        s += d * d;
    }
    s
}

/// Builds the subtree of `order[start..end]`, split at the median of the dimension of largest
/// spread; returns its node.
fn build<const D: usize>(points: &[[f64; D]], order: &mut [u32], start: usize, end: usize, nodes: &mut Vec<Node>) -> u32 {
    let at = nodes.len() as u32;
    if end - start <= LEAF {
        nodes.push(Node::Leaf { start: start as u32, end: end as u32 });
        return at;
    }
    let mut lo = [f64::INFINITY; D];
    let mut hi = [f64::NEG_INFINITY; D];
    for &i in &order[start..end] {
        for k in 0..D {
            lo[k] = lo[k].min(points[i as usize][k]);
            hi[k] = hi[k].max(points[i as usize][k]);
        }
    }
    let dim = (0..D).max_by(|&a, &b| (hi[a] - lo[a]).total_cmp(&(hi[b] - lo[b]))).unwrap_or(0);
    if hi[dim] - lo[dim] <= 0.0 {
        // All the points are at the same place.
        nodes.push(Node::Leaf { start: start as u32, end: end as u32 });
        return at;
    }
    let mid = (start + end) / 2;
    order[start..end].select_nth_unstable_by(mid - start, |&a, &b| points[a as usize][dim].total_cmp(&points[b as usize][dim]));
    let value = points[order[mid] as usize][dim];
    nodes.push(Node::Leaf { start: 0, end: 0 });
    // The left part has the points at or below the median's value, the right part those at or
    // above it.
    let left = build(points, order, start, mid, nodes);
    let right = build(points, order, mid, end, nodes);
    nodes[at as usize] = Node::Split { dim: dim as u8, value, left, right };
    at
}

/// A k-d tree built and searched as nanoflann 1.3 (which PDAL uses) builds and searches it: split
/// in the middle of the widest dimension, leaves of up to `leaf` points. Neighbours as far as
/// each other come in the order nanoflann finds them, so that results that depend on which of
/// them are kept (PDAL's SMRF fills empty cells with the mean of 8) are PDAL's.
#[derive(Debug, Clone)]
pub(crate) struct NanoKdTree<const D: usize> {
    points: Vec<[f64; D]>,
    vind: Vec<usize>,
    nodes: Vec<NanoNode>,
    root_bbox: [(f64, f64); D],
}

#[derive(Debug, Clone, Copy)]
enum NanoNode {
    Leaf { left: usize, right: usize },
    Split { divfeat: usize, divlow: f64, divhigh: f64, child1: usize, child2: usize },
}

impl<const D: usize> NanoKdTree<D> {
    /// Builds the index of points, with leaves of up to `leaf` points (PDAL: 100).
    pub fn new(points: Vec<[f64; D]>, leaf: usize) -> Self {
        let n = points.len();
        let mut t = Self { points, vind: (0..n).collect(), nodes: Vec::new(), root_bbox: [(0.0, 0.0); D] };
        if n == 0 {
            return t;
        }
        let mut bbox = [(f64::INFINITY, f64::NEG_INFINITY); D];
        for p in &t.points {
            for k in 0..D {
                bbox[k].0 = bbox[k].0.min(p[k]);
                bbox[k].1 = bbox[k].1.max(p[k]);
            }
        }
        t.root_bbox = bbox;
        t.divide(0, n, &mut bbox, leaf);
        t
    }

    /// The number of points.
    pub fn len(&self) -> usize {
        self.points.len()
    }

    fn get(&self, i: usize, k: usize) -> f64 {
        self.points[i][k]
    }

    fn divide(&mut self, left: usize, right: usize, bbox: &mut [(f64, f64); D], leaf: usize) -> usize {
        let at = self.nodes.len();
        self.nodes.push(NanoNode::Leaf { left, right });
        if right - left <= leaf {
            for (k, b) in bbox.iter_mut().enumerate() {
                *b = (self.get(self.vind[left], k), self.get(self.vind[left], k));
            }
            for j in left + 1..right {
                for (k, b) in bbox.iter_mut().enumerate() {
                    let v = self.get(self.vind[j], k);
                    if b.0 > v {
                        b.0 = v;
                    }
                    if b.1 < v {
                        b.1 = v;
                    }
                }
            }
            return at;
        }
        let (idx, cutfeat, cutval) = self.middle_split(left, right - left, bbox);
        let mut left_bbox = *bbox;
        left_bbox[cutfeat].1 = cutval;
        let child1 = self.divide(left, left + idx, &mut left_bbox, leaf);
        let mut right_bbox = *bbox;
        right_bbox[cutfeat].0 = cutval;
        let child2 = self.divide(left + idx, right, &mut right_bbox, leaf);
        self.nodes[at] = NanoNode::Split { divfeat: cutfeat, divlow: left_bbox[cutfeat].1, divhigh: right_bbox[cutfeat].0, child1, child2 };
        for k in 0..D {
            bbox[k] = (left_bbox[k].0.min(right_bbox[k].0), left_bbox[k].1.max(right_bbox[k].1));
        }
        at
    }

    fn min_max(&self, start: usize, count: usize, k: usize) -> (f64, f64) {
        let mut lo = self.get(self.vind[start], k);
        let mut hi = lo;
        for j in 1..count {
            let v = self.get(self.vind[start + j], k);
            if v < lo {
                lo = v;
            }
            if v > hi {
                hi = v;
            }
        }
        (lo, hi)
    }

    fn middle_split(&mut self, start: usize, count: usize, bbox: &[(f64, f64); D]) -> (usize, usize, f64) {
        const EPS: f64 = 0.00001;
        let mut max_span = bbox[0].1 - bbox[0].0;
        for b in bbox.iter().skip(1) {
            if b.1 - b.0 > max_span {
                max_span = b.1 - b.0;
            }
        }
        let mut max_spread = -1.0;
        let mut cutfeat = 0;
        for (k, b) in bbox.iter().enumerate() {
            if b.1 - b.0 > (1.0 - EPS) * max_span {
                let (lo, hi) = self.min_max(start, count, k);
                if hi - lo > max_spread {
                    cutfeat = k;
                    max_spread = hi - lo;
                }
            }
        }
        let split_val = (bbox[cutfeat].0 + bbox[cutfeat].1) / 2.0;
        let (lo, hi) = self.min_max(start, count, cutfeat);
        let cutval = if split_val < lo {
            lo
        } else if split_val > hi {
            hi
        } else {
            split_val
        };
        let (lim1, lim2) = self.plane_split(start, count, cutfeat, cutval);
        let index = if lim1 > count / 2 {
            lim1
        } else if lim2 < count / 2 {
            lim2
        } else {
            count / 2
        };
        (index, cutfeat, cutval)
    }

    fn plane_split(&mut self, start: usize, count: usize, cutfeat: usize, cutval: f64) -> (usize, usize) {
        let v = |t: &Self, j: usize| t.get(t.vind[start + j], cutfeat);
        let mut left = 0usize;
        let mut right = count - 1;
        loop {
            while left <= right && v(self, left) < cutval {
                left += 1;
            }
            while right > 0 && left <= right && v(self, right) >= cutval {
                right -= 1;
            }
            if left > right || right == 0 {
                break;
            }
            self.vind.swap(start + left, start + right);
            left += 1;
            right -= 1;
        }
        let lim1 = left;
        right = count - 1;
        loop {
            while left <= right && v(self, left) <= cutval {
                left += 1;
            }
            while right > 0 && left <= right && v(self, right) > cutval {
                right -= 1;
            }
            if left > right || right == 0 {
                break;
            }
            self.vind.swap(start + left, start + right);
            left += 1;
            right -= 1;
        }
        (lim1, left)
    }

    /// The `k` nearest points (at most the number of points): `(squared distance, index)`, in
    /// nanoflann's order.
    pub fn knn(&self, q: &[f64; D], k: usize, out: &mut Vec<(f64, usize)>) {
        out.clear();
        let k = k.min(self.points.len());
        if k == 0 {
            return;
        }
        let mut dists = vec![0.0; D];
        let mut distsq = 0.0;
        for i in 0..D {
            if q[i] < self.root_bbox[i].0 {
                dists[i] = (q[i] - self.root_bbox[i].0).powi(2);
                distsq += dists[i];
            }
            if q[i] > self.root_bbox[i].1 {
                dists[i] = (q[i] - self.root_bbox[i].1).powi(2);
                distsq += dists[i];
            }
        }
        let mut rs = KnnResult { idx: vec![0; k], dist: vec![0.0; k], count: 0 };
        rs.dist[k - 1] = f64::MAX;
        self.search_level(&mut rs, q, 0, distsq, &mut dists);
        out.extend(rs.dist.iter().zip(&rs.idx).take(rs.count).map(|(d, i)| (*d, *i)));
    }

    fn search_level(&self, rs: &mut KnnResult, q: &[f64; D], node: usize, mut mindistsq: f64, dists: &mut [f64]) {
        match self.nodes[node] {
            NanoNode::Leaf { left, right } => {
                let worst = rs.worst();
                for i in left..right {
                    let index = self.vind[i];
                    let d = dist2(&self.points[index], q);
                    if d < worst {
                        rs.add(d, index);
                    }
                }
            }
            NanoNode::Split { divfeat, divlow, divhigh, child1, child2 } => {
                let val = q[divfeat];
                let diff1 = val - divlow;
                let diff2 = val - divhigh;
                let (best, other, cut_dist) =
                    if diff1 + diff2 < 0.0 { (child1, child2, (val - divhigh).powi(2)) } else { (child2, child1, (val - divlow).powi(2)) };
                self.search_level(rs, q, best, mindistsq, dists);
                let dst = dists[divfeat];
                mindistsq = mindistsq + cut_dist - dst;
                dists[divfeat] = cut_dist;
                if mindistsq <= rs.worst() {
                    self.search_level(rs, q, other, mindistsq, dists);
                }
                dists[divfeat] = dst;
            }
        }
    }
}

impl<const D: usize> NanoKdTree<D> {
    /// The points closer than `r` to `q` (squared distance below `r²`), nearest first, as PDAL's
    /// radius searches return them: in the order nanoflann finds them, then sorted by distance
    /// with libstdc++'s `std::sort` (so that points as near come in PDAL's order).
    pub fn radius(&self, q: &[f64; D], r: f64, out: &mut Vec<(usize, f64)>) {
        out.clear();
        if self.points.is_empty() {
            return;
        }
        let mut dists = vec![0.0; D];
        let mut distsq = 0.0;
        for i in 0..D {
            if q[i] < self.root_bbox[i].0 {
                dists[i] = (q[i] - self.root_bbox[i].0).powi(2);
                distsq += dists[i];
            }
            if q[i] > self.root_bbox[i].1 {
                dists[i] = (q[i] - self.root_bbox[i].1).powi(2);
                distsq += dists[i];
            }
        }
        self.radius_level(out, q, r * r, 0, distsq, &mut dists);
        libstdcxx_sort(out, |a, b| a.1 < b.1);
    }

    fn radius_level(&self, out: &mut Vec<(usize, f64)>, q: &[f64; D], r2: f64, node: usize, mut mindistsq: f64, dists: &mut [f64]) {
        match self.nodes[node] {
            NanoNode::Leaf { left, right } => {
                for i in left..right {
                    let index = self.vind[i];
                    let d = dist2(&self.points[index], q);
                    if d < r2 {
                        out.push((index, d));
                    }
                }
            }
            NanoNode::Split { divfeat, divlow, divhigh, child1, child2 } => {
                let val = q[divfeat];
                let diff1 = val - divlow;
                let diff2 = val - divhigh;
                let (best, other, cut_dist) =
                    if diff1 + diff2 < 0.0 { (child1, child2, (val - divhigh).powi(2)) } else { (child2, child1, (val - divlow).powi(2)) };
                self.radius_level(out, q, r2, best, mindistsq, dists);
                let dst = dists[divfeat];
                mindistsq = mindistsq + cut_dist - dst;
                dists[divfeat] = cut_dist;
                if mindistsq <= r2 {
                    self.radius_level(out, q, r2, other, mindistsq, dists);
                }
                dists[divfeat] = dst;
            }
        }
    }
}

/// Sorts as libstdc++'s `std::sort` does (introsort, median-of-three pivots, heapsort past the
/// depth limit, a final insertion sort), so that elements that compare equal end in the same
/// order.
pub(crate) fn libstdcxx_sort<T: Copy>(v: &mut [T], less: impl Fn(&T, &T) -> bool + Copy) {
    const THRESHOLD: usize = 16;
    fn introsort<T: Copy>(v: &mut [T], mut depth: u32, less: impl Fn(&T, &T) -> bool + Copy) {
        let mut last = v.len();
        while last > THRESHOLD {
            if depth == 0 {
                heap_sort(&mut v[..last], less);
                return;
            }
            depth -= 1;
            let s = &mut v[..last];
            let mid = s.len() / 2;
            // __move_median_to_first(first, first + 1, mid, last - 1).
            let (a, b, c) = (1, mid, s.len() - 1);
            let m = if less(&s[a], &s[b]) {
                if less(&s[b], &s[c]) {
                    b
                } else if less(&s[a], &s[c]) {
                    c
                } else {
                    a
                }
            } else if less(&s[a], &s[c]) {
                a
            } else if less(&s[b], &s[c]) {
                c
            } else {
                b
            };
            s.swap(0, m);
            // __unguarded_partition(first + 1, last, first).
            let (mut lo, mut hi) = (1, s.len());
            let cut = loop {
                while less(&s[lo], &s[0]) {
                    lo += 1;
                }
                hi -= 1;
                while less(&s[0], &s[hi]) {
                    hi -= 1;
                }
                if lo >= hi {
                    break lo;
                }
                s.swap(lo, hi);
                lo += 1;
            };
            introsort(&mut s[cut..], depth, less);
            last = cut;
        }
    }
    fn heap_sort<T: Copy>(v: &mut [T], less: impl Fn(&T, &T) -> bool + Copy) {
        // std::make_heap, then std::sort_heap, with libstdc++'s __adjust_heap.
        fn adjust<T: Copy>(v: &mut [T], mut hole: usize, len: usize, value: T, less: impl Fn(&T, &T) -> bool) {
            let top = hole;
            let mut child = hole;
            while child < (len.saturating_sub(1)) / 2 {
                child = 2 * (child + 1);
                if less(&v[child], &v[child - 1]) {
                    child -= 1;
                }
                v[hole] = v[child];
                hole = child;
            }
            if len.is_multiple_of(2) && len >= 2 && child == (len - 2) / 2 {
                child = 2 * (child + 1);
                v[hole] = v[child - 1];
                hole = child - 1;
            }
            // __push_heap.
            let mut parent = hole.wrapping_sub(1) / 2;
            while hole > top && less(&v[parent], &value) {
                v[hole] = v[parent];
                hole = parent;
                parent = hole.wrapping_sub(1) / 2;
            }
            v[hole] = value;
        }
        let len = v.len();
        if len >= 2 {
            let mut parent = (len - 2) / 2;
            loop {
                let value = v[parent];
                adjust(v, parent, len, value, less);
                if parent == 0 {
                    break;
                }
                parent -= 1;
            }
        }
        let mut last = len;
        while last > 1 {
            last -= 1;
            let value = v[last];
            v[last] = v[0];
            adjust(v, 0, last, value, less);
        }
    }
    fn linear_insert<T: Copy>(v: &mut [T], mut i: usize, less: impl Fn(&T, &T) -> bool) {
        let val = v[i];
        while less(&val, &v[i - 1]) {
            v[i] = v[i - 1];
            i -= 1;
        }
        v[i] = val;
    }
    fn insertion_sort<T: Copy>(v: &mut [T], less: impl Fn(&T, &T) -> bool + Copy) {
        for i in 1..v.len() {
            if less(&v[i], &v[0]) {
                let val = v[i];
                v.copy_within(0..i, 1);
                v[0] = val;
            } else {
                linear_insert(v, i, less);
            }
        }
    }
    let n = v.len();
    if n < 2 {
        return;
    }
    introsort(v, 2 * n.ilog2(), less);
    if n > THRESHOLD {
        insertion_sort(&mut v[..THRESHOLD], less);
        for i in THRESHOLD..n {
            linear_insert(v, i, less);
        }
    } else {
        insertion_sort(v, less);
    }
}

/// nanoflann's `KNNResultSet`.
struct KnnResult {
    idx: Vec<usize>,
    dist: Vec<f64>,
    count: usize,
}

impl KnnResult {
    fn worst(&self) -> f64 {
        self.dist[self.dist.len() - 1]
    }

    fn add(&mut self, d: f64, index: usize) {
        let cap = self.dist.len();
        let mut i = self.count;
        while i > 0 {
            if self.dist[i - 1] > d {
                if i < cap {
                    self.dist[i] = self.dist[i - 1];
                    self.idx[i] = self.idx[i - 1];
                }
            } else {
                break;
            }
            i -= 1;
        }
        if i < cap {
            self.dist[i] = d;
            self.idx[i] = index;
        }
        if self.count < cap {
            self.count += 1;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn finds_the_nearest_points_as_brute_force_does() {
        let mut s = 7u64;
        let mut r = || {
            s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
            ((s >> 33) % 1000) as f64 / 10.0
        };
        let pts: Vec<[f64; 3]> = (0..2000).map(|_| [r(), r(), r()]).collect();
        let t = KdTree::new(pts.clone());
        let mut out = Vec::new();
        for q in pts.iter().take(50) {
            t.knn(q, 9, &mut out);
            let mut all: Vec<(f64, u32)> = pts.iter().enumerate().map(|(i, p)| (dist2(p, q), i as u32)).collect();
            all.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
            assert_eq!(out, all[..9].to_vec());
            assert_eq!(t.count_within(q, 5.0), all.iter().filter(|e| e.0 < 25.0).count());
            // nanoflann's tree finds the same distances.
            let nano = NanoKdTree::new(pts.clone(), 10);
            let mut found = Vec::new();
            nano.knn(q, 9, &mut found);
            let d: Vec<f64> = found.iter().map(|e| e.0).collect();
            assert_eq!(d, all[..9].iter().map(|e| e.0).collect::<Vec<_>>());
            // Radius searches find the same points, nearest first.
            let mut near = Vec::new();
            nano.radius(q, 5.0, &mut near);
            let mut idx: Vec<usize> = near.iter().map(|e| e.0).collect();
            assert!(near.windows(2).all(|w| w[0].1 <= w[1].1));
            idx.sort_unstable();
            let mut want: Vec<usize> = all.iter().filter(|e| e.0 < 25.0).map(|e| e.1 as usize).collect();
            want.sort_unstable();
            assert_eq!(idx, want);
        }
    }

    #[test]
    fn sorts_as_libstdcxx() {
        // Sorted, whatever the length; up to 16 elements, by insertion (stably).
        let mut s = 3u64;
        for n in [0, 1, 2, 5, 16, 17, 40, 1000, 5000] {
            let mut v: Vec<(u32, u32)> = (0..n)
                .map(|i| {
                    s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
                    ((s >> 60) as u32, i)
                })
                .collect();
            libstdcxx_sort(&mut v, |a, b| a.0 < b.0);
            assert!(v.windows(2).all(|w| w[0].0 <= w[1].0), "{n}");
            if n <= 16 {
                assert!(v.windows(2).all(|w| w[0].0 < w[1].0 || w[0].1 < w[1].1), "{n}");
            }
        }
        // Past the depth limit, heapsort: all equal but one, adversarial for the partition.
        let mut v: Vec<(u32, u32)> = (0..300).map(|i| (u32::from(i % 2 == 0) * (i % 7), i)).collect();
        libstdcxx_sort(&mut v, |a, b| a.0 < b.0);
        assert!(v.windows(2).all(|w| w[0].0 <= w[1].0));
    }
}