Skip to main content

legit_hamming/
scan.rs

1//! The scans: the reference, and the flat scan on any code path.
2
3use std::ops::Range;
4use std::sync::Arc;
5
6use crate::cpu::Isa;
7use crate::error::Result;
8use crate::kernel::{self, Hit};
9use crate::records::Records;
10use crate::search::{Clock, HitList, Memory, Search, Share, Stop, TRIM_RUN};
11use crate::value::Value;
12
13/// How many records a scan reads for every query before moving on, and how often it looks at the
14/// clock. 16,384 values are 128 KiB of one column, so a tile of 256-bit values stays in a core's
15/// level-2 cache while every query of a batch reads it...
16pub(crate) const TILE: usize = 16_384;
17
18/// The reference: the plainest possible scan, which every other variant is checked against.
19///
20/// It compares every record with every query using [`Value::distance`], one record at a time, with
21/// no tiling, no unrolling and no instruction set beyond the build target's.
22#[derive(Debug, Clone)]
23pub struct Reference<V> {
24    records: Arc<Records<V>>,
25}
26
27impl<V: Value> Reference<V> {
28    /// The reference over `records`.
29    #[must_use]
30    pub const fn new(records: Arc<Records<V>>) -> Self {
31        Self { records }
32    }
33}
34
35impl<V: Value> Search<V> for Reference<V> {
36    fn variant(&self) -> String {
37        "reference".to_owned()
38    }
39
40    fn len(&self) -> usize {
41        self.records.len()
42    }
43
44    fn has_ids(&self) -> bool {
45        self.records.has_ids()
46    }
47
48    fn id(&self, position: usize) -> Option<u64> {
49        self.records.id(position)
50    }
51
52    fn value(&self, position: usize) -> V {
53        self.records.value(position)
54    }
55
56    fn memory(&self) -> Memory {
57        Memory {
58            records: self.records.heap_bytes(),
59            ..Memory::default()
60        }
61    }
62
63    fn collect(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool {
64        let range = share.range(self.records.len());
65        for (query, list) in queries.iter().zip(out.iter_mut()) {
66            if stop.reached() {
67                return true;
68            }
69            for position in range.clone() {
70                let distance = self.records.value(position).distance(query);
71                if distance <= radius {
72                    list.push(Hit {
73                        position: position as u32,
74                        distance,
75                    });
76                }
77            }
78            list.candidates += range.len() as u64;
79        }
80        false
81    }
82}
83
84/// A flat scan of every record, on a chosen code path.
85///
86/// It reads the value columns in tiles of 16,384 records, running every query of a batch over a
87/// tile before moving to the next, so a batch reads the set from memory once. It needs nothing but
88/// the records: no index, no extra memory.
89#[derive(Debug, Clone)]
90pub struct Scan<V> {
91    records: Arc<Records<V>>,
92    isa: Isa,
93}
94
95impl<V: Value> Scan<V> {
96    /// A scan over `records` on the fastest path this CPU has for their width,
97    /// [`Isa::best_for`].
98    #[must_use]
99    pub fn new(records: Arc<Records<V>>) -> Self {
100        Self {
101            records,
102            isa: Isa::best_for::<V>(),
103        }
104    }
105
106    /// A scan over `records` on the path `isa`.
107    ///
108    /// # Errors
109    ///
110    /// [`Error::IsaUnavailable`](crate::Error::IsaUnavailable) if this CPU can't run it.
111    pub fn with_isa(records: Arc<Records<V>>, isa: Isa) -> Result<Self> {
112        Ok(Self {
113            records,
114            isa: isa.require()?,
115        })
116    }
117
118    /// The path the scan runs on.
119    #[must_use]
120    pub const fn isa(&self) -> Isa {
121        self.isa
122    }
123}
124
125impl<V: Value> Search<V> for Scan<V> {
126    fn variant(&self) -> String {
127        format!("scan/{}", self.isa)
128    }
129
130    fn len(&self) -> usize {
131        self.records.len()
132    }
133
134    fn has_ids(&self) -> bool {
135        self.records.has_ids()
136    }
137
138    fn id(&self, position: usize) -> Option<u64> {
139        self.records.id(position)
140    }
141
142    fn value(&self, position: usize) -> V {
143        self.records.value(position)
144    }
145
146    fn memory(&self) -> Memory {
147        Memory {
148            records: self.records.heap_bytes(),
149            ..Memory::default()
150        }
151    }
152
153    fn collect(&self, queries: &[V], radius: u32, share: Share, stop: &Stop, out: &mut [HitList<'_>]) -> bool {
154        scan_tiles(
155            self.isa,
156            &self.records,
157            share.range(self.records.len()),
158            0,
159            queries,
160            radius,
161            stop,
162            out,
163        )
164    }
165}
166
167/// Scan `range` of `records` tile by tile, every query on each tile, numbering positions from
168/// `offset`. Returns whether `stop` cut it short.
169#[expect(
170    clippy::too_many_arguments,
171    reason = "the set, the part of it, the queries and the output"
172)]
173pub(crate) fn scan_tiles<V: Value>(
174    isa: Isa,
175    records: &Records<V>,
176    range: Range<usize>,
177    offset: usize,
178    queries: &[V],
179    radius: u32,
180    stop: &Stop,
181    out: &mut [HitList<'_>],
182) -> bool {
183    let mut clock = Clock::new(stop);
184    let mut start = range.start;
185    while start < range.end {
186        let end = (start + TILE).min(range.end);
187        for (query, list) in queries.iter().zip(out.iter_mut()) {
188            // Checked by work done, not once a tile: a tile run for a whole batch of queries is a
189            // long time.
190            if clock.spend(end - start) {
191                return true;
192            }
193            // In runs, each trimmed, so a dense tile can't swell the list past its bound...
194            let mut at = start;
195            while at < end {
196                let to = (at + TRIM_RUN).min(end);
197                list.prepare(to - at);
198                scan_run(isa, records, at..to, offset, query, radius, &mut list.hits);
199                list.trim();
200                at = to;
201            }
202            list.candidates += (end - start) as u64;
203        }
204        start = end;
205    }
206    false
207}
208
209/// Scan one run of records for one query.
210pub(crate) fn scan_run<V: Value>(
211    isa: Isa,
212    records: &Records<V>,
213    range: Range<usize>,
214    offset: usize,
215    query: &V,
216    radius: u32,
217    out: &mut Vec<Hit>,
218) {
219    let base = (offset + range.start) as u32;
220    if V::WORDS == 1 {
221        kernel::scan64(isa, &records.column(0)[range], query.word(0), radius, base, out);
222    } else {
223        let columns = [0, 1, 2, 3].map(|word| &records.column(word)[range.clone()]);
224        let query = [0, 1, 2, 3].map(|word| query.word(word));
225        kernel::scan256(isa, columns, query, radius, base, out);
226    }
227}