legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//! The trait every variant implements, and the search that runs it.

use std::fmt;
use std::ops::Range;
use std::thread;
use std::time::{Duration, Instant};

use crate::kernel::Hit;
use crate::value::Value;

/// A searchable set of records: one of the crate's variants, or one of your own.
///
/// A variant does one thing, [`collect`](Self::collect): for each query, push the position and
/// distance of every record within the radius. [`search`] and [`search_batch`] build on it: they
/// split the work across threads, apply the caller's limits, and resolve positions into ids and
/// values. Every variant of the crate collects exactly the positions [`Reference`] collects; the
/// test suite checks it.
///
/// [`Reference`]: crate::Reference
pub trait Search<V: Value>: Send + Sync + fmt::Debug {
    /// A short name for reports, such as `scan/avx512` or `multi-index/4x16`.
    fn variant(&self) -> String;

    /// How many records the set holds.
    fn len(&self) -> usize;

    /// Whether the set holds no records.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Whether the records carry ids.
    fn has_ids(&self) -> bool;

    /// The id of the record at `position`, if the records carry ids.
    ///
    /// # Panics
    ///
    /// May panic if `position` is past the end.
    fn id(&self, position: usize) -> Option<u64>;

    /// The value of the record at `position`.
    ///
    /// # Panics
    ///
    /// May panic if `position` is past the end.
    fn value(&self, position: usize) -> V;

    /// The memory the set and its index take.
    fn memory(&self) -> Memory;

    /// Push to `out[i]` every record within `radius` of `queries[i]`, for this share of the work.
    ///
    /// The shares `0..share.count` of one call together push every record within the radius
    /// exactly once: no record is missed, and none is pushed twice, whether by two shares or by
    /// one. After each run of pushes onto a list, call [`HitList::trim`], which keeps the list
    /// within the caller's bound. Each [`HitList`] also counts the candidates its query cost: records whose distance was
    /// computed, or for an index, the entries it read. Returns whether `stop` cut the work short,
    /// in which case the hits are those found before it did.
    ///
    /// A list may carry the [`Plan`] that [`plan`](Self::plan) chose for its query
    /// ([`HitList::plan`]); a variant that plans follows it, and plans the query itself when the
    /// list carries none.
    fn collect(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool;

    /// Decide how to answer each of `queries` within `radius`, and on how many of the `threads`
    /// given, at least 1. [`search_batch`] calls it once a call, before any `collect`, hands each
    /// query's plan to `collect` on its [`HitList`], and reports it in [`Found::plan`].
    ///
    /// Planning is part of the search: a variant whose planning takes work watches `stop`, the
    /// deadline of the search it plans for, and once it has passed leaves the queries it hasn't
    /// planned without an estimate, so the search stops cut by time.
    ///
    /// The default plans nothing and uses every thread given: a variant with one way to answer a
    /// query has nothing to choose. [`Planned`](crate::Planned) chooses between a scan and its
    /// tables per query, and the threads from the work it expects.
    fn plan(&self, queries: &[V], radius: u32, threads: usize, stop: &Stop) -> Planning {
        let _ = (queries, radius, stop);
        Planning::unplanned(threads)
    }
}

/// How a query is answered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Strategy {
    /// Every record compared with the query.
    Scan,
    /// The multi-index tables probed with every key near the query's chunks, and each record
    /// they hold under those keys compared with the query.
    MultiIndex,
}

impl Strategy {
    /// The strategy's name in a report: `scan` or `multi-index`.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Scan => "scan",
            Self::MultiIndex => "multi-index",
        }
    }
}

impl fmt::Display for Strategy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// What a query was expected to cost each way, in records scanned: the numbers a plan was chosen
/// by.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Estimate {
    /// The keys a probe of the tables looks up.
    pub keys: u64,
    /// The table entries those keys hold, which a probe reads and compares with the query: the
    /// sum of the tables' own bucket sizes, so exact when [`counted`](Self::counted) is true.
    pub candidates: u64,
    /// Whether [`candidates`](Self::candidates) is the full count. Counting stops as soon as the
    /// probe is sure to cost more than a scan, and doesn't start when the keys alone outnumber
    /// the records; the count is then a lower bound.
    pub counted: bool,
    /// The probe's cost: its keys, plus its candidates times
    /// [`Planned::CANDIDATE_COST`](crate::Planned::CANDIDATE_COST).
    pub probe_cost: u64,
    /// A scan's cost: the records.
    pub scan_cost: u64,
}

/// The plan a query ran with: its strategy, and the estimate that chose it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Plan {
    /// How the query was answered.
    pub strategy: Strategy,
    /// The costs compared to choose it, or `None` where there was nothing to compare: a variant
    /// with no tables, a [`MultiIndex`](crate::MultiIndex), which scans only when its keys
    /// outnumber its records, or a query whose planning the search's time budget cut short.
    pub estimate: Option<Estimate>,
    /// Whether the strategy was forced rather than chosen by the estimate.
    pub forced: bool,
}

impl Plan {
    /// A plan of `strategy`, chosen by `estimate` unless `forced`.
    #[must_use]
    pub const fn new(strategy: Strategy, estimate: Option<Estimate>, forced: bool) -> Self {
        Self {
            strategy,
            estimate,
            forced,
        }
    }
}

/// The plans for one call of a search, and the threads it runs on: what [`Search::plan`]
/// returns.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Planning {
    /// A plan for each query, in query order, or none at all.
    pub plans: Vec<Plan>,
    /// The threads to split the call across, at least 1.
    pub threads: usize,
}

impl Planning {
    /// One plan a query, on `threads` threads.
    #[must_use]
    pub fn new(plans: Vec<Plan>, threads: usize) -> Self {
        Self {
            plans,
            threads: threads.max(1),
        }
    }

    /// No plans, on `threads` threads.
    #[must_use]
    pub fn unplanned(threads: usize) -> Self {
        Self::new(Vec::new(), threads)
    }
}

/// One share of a search split across threads: share `index` of `count`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Share {
    /// Which share, from 0.
    pub index: usize,
    /// How many shares there are, at least 1.
    pub count: usize,
}

impl Share {
    /// All the work, in one share.
    pub const WHOLE: Self = Self { index: 0, count: 1 };

    /// This share's part of `0..length`: the shares split it into consecutive ranges, each but
    /// the last a multiple of 64 long.
    #[must_use]
    pub fn range(self, length: usize) -> Range<usize> {
        let count = self.count.max(1) as u64;
        let bound = |share: u64| {
            if share >= count {
                length
            } else {
                ((length as u64 * share / count) & !63) as usize
            }
        };
        bound(self.index as u64)..bound(self.index as u64 + 1)
    }
}

/// When to stop collecting candidates: never, or at a deadline.
///
/// A search looks at it between runs of work (see [`Search::collect`]): past the deadline it
/// collects no more, and the matches it has are merged, cut by time, and returned. The merging,
/// and what the caller does with the result, come after the deadline, not within it.
#[derive(Debug, Clone, Copy)]
pub struct Stop {
    deadline: Option<Instant>,
    /// Where the time is read: [`Instant::now`], or in the crate's own tests a clock they drive.
    now: fn() -> Instant,
}

impl PartialEq for Stop {
    fn eq(&self, other: &Self) -> bool {
        self.deadline == other.deadline
    }
}

impl Eq for Stop {}

impl Default for Stop {
    fn default() -> Self {
        Self::never()
    }
}

impl Stop {
    /// Never stop early.
    #[must_use]
    pub const fn never() -> Self {
        Self::at_on(None, Instant::now)
    }

    /// Stop at `deadline`.
    #[must_use]
    pub const fn at(deadline: Instant) -> Self {
        Self::at_on(Some(deadline), Instant::now)
    }

    /// Stop `budget` after now, read from `now`; never, for no budget or one too long to add to
    /// the clock.
    pub(crate) fn after(budget: Option<Duration>, now: fn() -> Instant) -> Self {
        Self::at_on(budget.and_then(|budget| now().checked_add(budget)), now)
    }

    /// Stop at `deadline`, if any, reading the time from `now`.
    pub(crate) const fn at_on(deadline: Option<Instant>, now: fn() -> Instant) -> Self {
        Self { deadline, now }
    }

    /// Whether the deadline has passed. Reads the clock only when there is one.
    #[must_use]
    pub fn reached(&self) -> bool {
        self.deadline.is_some_and(|deadline| (self.now)() >= deadline)
    }

    /// Whether there is a deadline at all.
    #[must_use]
    pub const fn is_set(&self) -> bool {
        self.deadline.is_some()
    }
}

/// Reads the clock for a deadline after every [`EVERY`](Self::EVERY) units of work, a unit being
/// a record compared or a posting read, and a key probed counting as [`KEY`](Self::KEY). A search
/// notices its deadline within about a thousand records' work, however that work is split
/// between queries, tiles and keys, and reads the clock no more than once a thousand records.
pub(crate) struct Clock<'a> {
    stop: &'a Stop,
    spent: usize,
}

impl<'a> Clock<'a> {
    /// The work between two reads of the clock.
    pub(crate) const EVERY: usize = 1024;
    /// What probing one key counts as: a hash lookup, worth many postings.
    pub(crate) const KEY: usize = 64;

    pub(crate) const fn new(stop: &'a Stop) -> Self {
        Self { stop, spent: 0 }
    }

    /// Count `work` units, and say whether the deadline has passed if it is time to look.
    pub(crate) fn spend(&mut self, work: usize) -> bool {
        if !self.stop.is_set() {
            return false;
        }
        self.spent += work;
        if self.spent < Self::EVERY {
            return false;
        }
        self.spent = 0;
        self.stop.reached()
    }
}

/// The hits one share collected for one query, held within a bound.
///
/// A variant pushes each record within the radius onto [`hits`](Self::hits) and calls
/// [`trim`](Self::trim) after every run of pushes: after each [`TRIM_RUN`] records a scan
/// compares, or each record an index reads. `trim` costs a comparison until the list passes its
/// bound, and then brings it back under:
///
/// - with a limit or a size budget of `k` (see [`Options`]), it keeps the `k` nearest by distance
///   and then position, drops the rest, and notes that it dropped some. The crate's variants push
///   at most [`TRIM_RUN`] hits between two trims and grow the list no further than that needs, so
///   a list never holds more than [`max_hits`]`(k)`, `2k + 5,119` hits, its capacity included,
///   however many records match;
/// - with records left out (all-zero values, or those [`search_batch_excluding`] names), it drops
///   them first, so they don't count against the bound;
/// - for [`neighbour_table`](crate::neighbour_table), it adds the hits to a count by distance and
///   empties the list, so the list never holds more than [`max_hits`]`(0)` hits.
///
/// A list with no bound keeps every hit, and `trim` does nothing. A variant that never calls
/// `trim` still returns the right result: the bound is applied when the search finishes. It only
/// loses the bound on memory. A variant of your own that pushes more than [`TRIM_RUN`] hits
/// between two trims holds more, and a trim gives back the capacity grown past [`max_hits`].
#[derive(Clone)]
pub struct HitList<'a> {
    /// Records within the radius, by position, in no particular order.
    pub hits: Vec<Hit>,
    /// The candidates the query cost: records whose distance was computed, or index entries read.
    pub candidates: u64,
    /// Trim when `hits` reaches this length; `usize::MAX` when there is no bound.
    trim_at: usize,
    /// The hits a bounded list keeps when it trims.
    keep: Option<usize>,
    /// Whether trimming has dropped a hit that was within the radius and not left out.
    dropped: bool,
    /// Whether the record at a position is to be left out of the results.
    exclude: Option<&'a (dyn Fn(u32) -> bool + Sync)>,
    /// For a histogram: the count of hits at each distance, and a position not to count.
    histogram: Option<(Vec<u64>, Option<u32>)>,
    /// The plan chosen for the query, if the variant plans.
    plan: Option<Plan>,
}

/// How far past twice the hits it keeps a list may grow before [`HitList::trim`] brings it back.
const SLACK: usize = 4096;

/// The most records a variant of this crate compares for one query between two calls of
/// [`HitList::trim`], and so the most hits it pushes between them: a scan cuts each tile into runs
/// of this many. Small beside a tile, so a dense tile can't swell a list, and large enough that the
/// calls cost nothing beside the comparisons.
pub const TRIM_RUN: usize = 1024;

/// The most hits a list that keeps the nearest `keep` holds at any moment, its capacity included,
/// when the variant filling it pushes at most [`TRIM_RUN`] hits between trims, as every variant of
/// this crate does: `2 × keep + 4,096`, the length at which it trims, plus one run less one. A list
/// that counts a histogram holds at most `max_hits(0)`.
///
/// ```
/// assert_eq!(legit_hamming::max_hits(1), 5_121);
/// ```
#[must_use]
pub const fn max_hits(keep: usize) -> usize {
    keep.saturating_mul(2)
        .saturating_add(SLACK)
        .saturating_add(TRIM_RUN - 1)
}

impl<'a> HitList<'a> {
    /// A list that keeps every hit.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            hits: Vec::new(),
            candidates: 0,
            trim_at: usize::MAX,
            keep: None,
            dropped: false,
            exclude: None,
            histogram: None,
            plan: None,
        }
    }

    /// The plan [`Search::plan`] chose for this list's query, if the variant plans and the list
    /// came from [`search`], [`search_batch`] or [`neighbour_table`](crate::neighbour_table).
    #[must_use]
    pub const fn plan(&self) -> Option<Plan> {
        self.plan
    }

    /// The list, carrying `plan`.
    pub(crate) const fn with_plan(mut self, plan: Option<Plan>) -> Self {
        self.plan = plan;
        self
    }

    /// A list that keeps the `keep` nearest hits, if `keep` is given, and leaves out the records
    /// for which `exclude` is true, if it is given.
    pub(crate) fn bounded(keep: Option<usize>, exclude: Option<&'a (dyn Fn(u32) -> bool + Sync)>) -> Self {
        let trim_at = match (keep, exclude) {
            (Some(keep), _) => keep.saturating_mul(2).saturating_add(SLACK),
            (None, Some(_)) => SLACK,
            (None, None) => usize::MAX,
        };
        Self {
            trim_at,
            keep,
            exclude,
            ..Self::new()
        }
    }

    /// A list that counts its hits by distance, up to `max_distance`, instead of keeping them,
    /// and doesn't count the record at `skip`.
    pub(crate) fn histogram(max_distance: u32, skip: Option<u32>) -> Self {
        Self {
            trim_at: SLACK,
            histogram: Some((vec![0; max_distance as usize + 1], skip)),
            ..Self::new()
        }
    }

    /// Bring the list back within its bound, if it has passed it. Call it after every run of
    /// pushes onto [`hits`](Self::hits).
    #[inline]
    pub fn trim(&mut self) {
        if self.hits.len() >= self.trim_at {
            self.compact();
        }
    }

    /// Whether the list has a bound its hits are held to: a limit or size budget, or a histogram.
    const fn is_bounded(&self) -> bool {
        self.keep.is_some() || self.histogram.is_some()
    }

    /// The most hits the list holds, its capacity included: [`max_hits`] of what it keeps, or
    /// `usize::MAX` when it has no bound.
    fn most(&self) -> usize {
        if self.is_bounded() {
            max_hits(self.keep.unwrap_or(0))
        } else {
            usize::MAX
        }
    }

    /// Make room for `run` more hits, at most [`TRIM_RUN`]: call it before a run of pushes. A
    /// bounded list grows by doubling, as a `Vec` does, but never past [`max_hits`], under which a
    /// list shorter than its trimming length always has room for a run.
    #[inline]
    pub(crate) fn prepare(&mut self, run: usize) {
        let need = self.hits.len().saturating_add(run);
        let capacity = self.hits.capacity();
        if need <= capacity {
            return;
        }
        let grown = need.max(capacity.saturating_mul(2)).max(64).min(self.most()).max(need);
        self.hits.reserve_exact(grown - self.hits.len());
    }

    /// Push one hit and trim: for a variant that finds its hits one at a time.
    #[inline]
    pub(crate) fn push(&mut self, hit: Hit) {
        self.prepare(1);
        self.hits.push(hit);
        self.trim();
    }

    fn compact(&mut self) {
        if let Some((counts, skip)) = &mut self.histogram {
            for hit in self.hits.drain(..) {
                if Some(hit.position) != *skip
                    && let Some(count) = counts.get_mut(hit.distance as usize)
                {
                    *count += 1;
                }
            }
            return;
        }
        if let Some(exclude) = self.exclude {
            self.hits.retain(|hit| !exclude(hit.position));
        }
        if let Some(keep) = self.keep
            && self.hits.len() > keep
        {
            if keep > 0 {
                self.hits
                    .select_nth_unstable_by_key(keep - 1, |hit| (hit.distance, hit.position));
            }
            self.hits.truncate(keep);
            self.dropped = true;
        }
        // With nothing kept beyond the excluded records, grow the threshold so a list that keeps
        // everything is not re-scanned after every run.
        if self.keep.is_none() {
            self.trim_at = self.hits.len().saturating_mul(2).max(SLACK);
        }
        // A variant that pushed more than a run between trims gives back what it grew past the
        // bound...
        if self.hits.capacity() > self.most() {
            self.hits.shrink_to(self.most());
        }
    }

    /// Add another share's list for the same query to this one. A bounded list is brought down to
    /// what it keeps on both sides first, so the two together stay within its bound.
    fn absorb(&mut self, mut other: Self) {
        self.candidates += other.candidates;
        if self.is_bounded() {
            self.compact();
            other.compact();
        }
        self.dropped |= other.dropped;
        if let (Some((counts, _)), Some((other_counts, _))) = (&mut self.histogram, &other.histogram) {
            for (count, other) in counts.iter_mut().zip(other_counts) {
                *count += other;
            }
        }
        if self.hits.is_empty() {
            self.hits = other.hits;
        } else {
            self.prepare(other.hits.len());
            self.hits.extend(other.hits);
        }
        self.trim();
    }

    /// The counts by distance of a histogram list, with every hit still held counted.
    pub(crate) fn into_counts(mut self) -> Vec<u64> {
        self.compact();
        self.histogram.map(|(counts, _)| counts).unwrap_or_default()
    }
}

impl Default for HitList<'_> {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for HitList<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HitList")
            .field("hits", &self.hits.len())
            .field("candidates", &self.candidates)
            .field("keep", &self.keep)
            .field("dropped", &self.dropped)
            .field("histogram", &self.histogram.as_ref().map(|(counts, _)| counts))
            .field("plan", &self.plan)
            .finish_non_exhaustive()
    }
}

/// The memory a variant takes, in bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Memory {
    /// The records, ids and values, held in memory. A variant that shares its records with others
    /// counts them in full.
    pub records: usize,
    /// The index built over the records, beyond the records themselves.
    pub index: usize,
    /// Files mapped into memory: the operating system pages them in as a search reads them.
    pub mapped: usize,
}

/// How to run a search.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Options {
    /// Every record within this Hamming distance of the query is a match.
    pub radius: u32,
    /// Return only the nearest `limit` matches by distance. `None` returns all.
    pub limit: Option<usize>,
    /// A size budget: hold at most this many matches per query, the nearest by distance. It bounds
    /// the memory a search holds as well as the result: at most [`max_hits`] of it, about twice
    /// this many, hits a query and thread.
    pub max_matches: Option<usize>,
    /// A search budget: the search stops collecting candidates once this much time has passed,
    /// and keeps only the matches at distance 0 it found, the only ones proven nearest (see
    /// [`Found::cut_by`]); the result follows as soon as what was collected is merged. The clock
    /// is read between runs of about a thousand records' work, so collecting stops within one run
    /// of the deadline; merging, sorting and building the result come after it. A budget too long
    /// to add to the clock is no budget.
    pub time_budget: Option<Duration>,
    /// Threads to split the search across; 0 counts as 1. A variant that plans may use fewer for
    /// a call it expects to be short: see [`Search::plan`].
    pub threads: usize,
    /// Leave records whose value is all zeros out of the results.
    pub exclude_zero: bool,
}

impl Options {
    /// Every match within `radius`, on one thread, with no budget.
    #[must_use]
    pub const fn new(radius: u32) -> Self {
        Self {
            radius,
            limit: None,
            max_matches: None,
            time_budget: None,
            threads: 1,
            exclude_zero: false,
        }
    }

    /// Return only the nearest `limit` matches.
    #[must_use]
    pub const fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Hold at most `max_matches` matches per query.
    #[must_use]
    pub const fn max_matches(mut self, max_matches: usize) -> Self {
        self.max_matches = Some(max_matches);
        self
    }

    /// Stop after `budget`.
    #[must_use]
    pub const fn time_budget(mut self, budget: Duration) -> Self {
        self.time_budget = Some(budget);
        self
    }

    /// Split the search across `threads` threads.
    #[must_use]
    pub const fn threads(mut self, threads: usize) -> Self {
        self.threads = threads;
        self
    }

    /// Leave all-zero values out of the results.
    #[must_use]
    pub const fn exclude_zero(mut self, exclude: bool) -> Self {
        self.exclude_zero = exclude;
        self
    }
}

/// A stored record within the radius of a query.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Match<V> {
    /// The record's position in the set searched, from 0. Positions rise with ids.
    pub position: u32,
    /// The record's id, if the set's records carry ids.
    pub id: Option<u64>,
    /// The record's value.
    pub value: V,
    /// How many bits differ from the query.
    pub distance: u32,
}

/// What cut a result short.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Cut {
    /// The caller's [`Options::limit`].
    Limit,
    /// The time budget, [`Options::time_budget`].
    Time,
    /// The size budget, [`Options::max_matches`].
    Size,
}

impl Cut {
    /// The name the service contract uses: `limit`, `time` or `size`.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Limit => "limit",
            Self::Time => "time",
            Self::Size => "size",
        }
    }
}

/// The result of one query.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Found<V> {
    /// The matches, by distance and then by id (or position, for a set without ids).
    pub matches: Vec<Match<V>>,
    /// What cut the list short, or `None` if it is every match within the radius.
    ///
    /// Whatever cut it, the list holds the nearest matches: every record nearer than the farthest
    /// one returned is returned. A limit or a size budget keeps the nearest that many. A time
    /// budget stops collecting before the search has reached every record, and any record it
    /// didn't reach could be nearer than a match it found, so it returns only the matches at
    /// distance 0, which nothing is nearer than, and none if it found none.
    pub cut_by: Option<Cut>,
    /// The candidates the query cost: records whose distance was computed, or index entries read.
    pub candidates: u64,
    /// The plan the query ran with, for a variant that plans: [`Planned`](crate::Planned), or a
    /// [`MultiIndex`](crate::MultiIndex), which says when it scanned. `None` for a variant with
    /// one way to answer.
    pub plan: Option<Plan>,
}

impl<V> Found<V> {
    /// Whether the list is every match within the radius.
    #[must_use]
    pub const fn is_complete(&self) -> bool {
        self.cut_by.is_none()
    }
}

/// Search for one query.
///
/// # Panics
///
/// Panics if the variant panics on one of the threads.
pub fn search<V: Value>(index: &(impl Search<V> + ?Sized), query: V, options: &Options) -> Found<V> {
    search_batch(index, &[query], options)
        .pop()
        .expect("one result a query")
}

/// Search for many queries in one call: a scan reads each part of the set once for all of them.
/// The results are in the order of the queries.
///
/// # Panics
///
/// Panics if the variant panics on one of the threads.
pub fn search_batch<V: Value>(index: &(impl Search<V> + ?Sized), queries: &[V], options: &Options) -> Vec<Found<V>> {
    search_batch_with(index, queries, options, None)
}

/// [`search_batch`], leaving out every record at a position for which `exclude` is true, as if
/// the set didn't hold it.
///
/// The records are left out where the hits are kept, before any limit or size budget trims a
/// list, so a query cut by `limit` still returns the nearest `limit` records that aren't left
/// out, and says it was cut only when more than that many are within the radius. It's what a set
/// that masks some of its records needs, such as a snapshot under a table of later changes:
/// filtering the result afterwards would return fewer than `limit` matches when more exist.
/// `exclude` is called for records within the radius only, from several threads at once.
///
/// ```
/// use std::sync::Arc;
///
/// use legit_hamming::{Options, Planned, Records, search_batch_excluding};
///
/// let records = Records::from_records([(1, 0b0001u64), (2, 0b0011), (3, 0b0111)])?;
/// let index = Planned::new(Arc::new(records), 64 << 20, 1);
/// // The nearest record is position 0, left out: the limit of 1 keeps the next nearest...
/// let found = search_batch_excluding(&index, &[0b0001], &Options::new(4).limit(1), &|position| position == 0);
/// assert_eq!(found[0].matches[0].id, Some(2));
/// assert!(!found[0].is_complete());
/// # Ok::<(), legit_hamming::Error>(())
/// ```
///
/// # Panics
///
/// Panics if the variant or `exclude` panics on one of the threads.
pub fn search_batch_excluding<V: Value>(
    index: &(impl Search<V> + ?Sized),
    queries: &[V],
    options: &Options,
    exclude: &(dyn Fn(u32) -> bool + Sync),
) -> Vec<Found<V>> {
    search_batch_with(index, queries, options, Some(exclude))
}

fn search_batch_with<V: Value>(
    index: &(impl Search<V> + ?Sized),
    queries: &[V],
    options: &Options,
    excluded: Option<&(dyn Fn(u32) -> bool + Sync)>,
) -> Vec<Found<V>> {
    let stop = Stop::after(options.time_budget, Instant::now);
    search_batch_until(index, queries, options, excluded, &stop)
}

/// [`search_batch_excluding`], or with no `excluded` [`search_batch`], collecting until `stop`
/// rather than within [`Options::time_budget`], which it doesn't read.
pub(crate) fn search_batch_until<V: Value>(
    index: &(impl Search<V> + ?Sized),
    queries: &[V],
    options: &Options,
    excluded: Option<&(dyn Fn(u32) -> bool + Sync)>,
    stop: &Stop,
) -> Vec<Found<V>> {
    let keep = match (options.limit, options.max_matches) {
        (Some(limit), Some(max)) => Some(limit.min(max)),
        (limit, max) => limit.or(max),
    };
    let left_out = |position: u32| {
        (options.exclude_zero && index.value(position as usize).is_zero())
            || excluded.is_some_and(|excluded| excluded(position))
    };
    let exclude: Option<&(dyn Fn(u32) -> bool + Sync)> =
        (options.exclude_zero || excluded.is_some()).then_some(&left_out);
    let planning = index.plan(queries, options.radius, options.threads.max(1), stop);
    let plans = &planning.plans;
    let (lists, stopped) = collect_all(index, queries, options.radius, planning.threads, stop, |query| {
        HitList::bounded(keep, exclude).with_plan(plans.get(query).copied())
    });
    lists
        .into_iter()
        .map(|list| finish(index, list, options, exclude, stopped))
        .collect()
}

/// Run `collect` over every share, on as many threads, into the lists `list` makes for each query
/// by its index, and gather each query's shares into one list.
pub(crate) fn collect_all<'a, V: Value>(
    index: &(impl Search<V> + ?Sized),
    queries: &[V],
    radius: u32,
    threads: usize,
    stop: &Stop,
    list: impl Fn(usize) -> HitList<'a> + Sync,
) -> (Vec<HitList<'a>>, bool) {
    let threads = threads.max(1);
    let mut lists: Vec<HitList<'a>> = (0..queries.len()).map(&list).collect();
    if threads == 1 {
        let stopped = index.collect(queries, radius, Share::WHOLE, stop, &mut lists);
        return (lists, stopped);
    }
    let mut stopped = false;
    thread::scope(|scope| {
        let workers: Vec<_> = (0..threads)
            .map(|share| {
                let list = &list;
                scope.spawn(move || {
                    let mut part: Vec<HitList<'a>> = (0..queries.len()).map(list).collect();
                    let share = Share {
                        index: share,
                        count: threads,
                    };
                    let stopped = index.collect(queries, radius, share, stop, &mut part);
                    (part, stopped)
                })
            })
            .collect();
        for worker in workers {
            let (part, share_stopped) = worker.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic));
            stopped |= share_stopped;
            for (list, part) in lists.iter_mut().zip(part) {
                list.absorb(part);
            }
        }
    });
    (lists, stopped)
}

fn finish<V: Value>(
    index: &(impl Search<V> + ?Sized),
    list: HitList<'_>,
    options: &Options,
    exclude: Option<&(dyn Fn(u32) -> bool + Sync)>,
    stopped: bool,
) -> Found<V> {
    let dropped = list.dropped;
    let mut hits = list.hits;
    // A list trims, and so leaves out, only once it passes its bound: the rest go here...
    if let Some(exclude) = exclude {
        hits.retain(|hit| !exclude(hit.position));
    }
    let key = |hit: &Hit| (hit.distance, hit.position);
    let mut cut_by = None;
    if stopped {
        // The search didn't reach every record, so any of them may be nearer than a match it
        // found, except a match at distance 0: nothing is nearer. Those are all that are proven.
        hits.retain(|hit| hit.distance == 0);
        cut_by = Some(Cut::Time);
    }
    let keep = match (options.limit, options.max_matches) {
        (Some(limit), Some(max)) if max < limit => Some((max, Cut::Size)),
        (Some(limit), _) => Some((limit, Cut::Limit)),
        (None, Some(max)) => Some((max, Cut::Size)),
        (None, None) => None,
    };
    if let Some((keep, cut)) = keep
        && (dropped || hits.len() > keep)
    {
        if keep > 0 && hits.len() > keep {
            hits.select_nth_unstable_by_key(keep - 1, key);
        }
        hits.truncate(keep);
        cut_by.get_or_insert(cut);
    }
    hits.sort_unstable_by_key(key);
    let matches = hits
        .into_iter()
        .map(|hit| {
            let position = hit.position as usize;
            Match {
                position: hit.position,
                id: index.id(position),
                value: index.value(position),
                distance: hit.distance,
            }
        })
        .collect();
    Found {
        matches,
        cut_by,
        candidates: list.candidates,
        plan: list.plan,
    }
}

/// A clock for the crate's tests that moves on a millisecond each time it is read, on the thread
/// reading it: a search on one thread reads it at the same points every run, so a test can place
/// its deadline between any two of them.
#[cfg(test)]
pub(crate) mod ticking {
    use std::cell::Cell;
    use std::sync::OnceLock;
    use std::time::{Duration, Instant};

    thread_local! {
        static READS: Cell<u64> = const { Cell::new(0) };
    }

    /// The time: a millisecond on from the last read on this thread.
    pub(crate) fn now() -> Instant {
        static START: OnceLock<Instant> = OnceLock::new();
        let reads = READS.with(|reads| {
            reads.set(reads.get() + 1);
            reads.get()
        });
        *START.get_or_init(Instant::now) + Duration::from_millis(reads)
    }

    /// Start this thread's clock again.
    pub(crate) fn reset() {
        READS.with(|reads| reads.set(0));
    }
}