Skip to main content

zsync_rs/
matcher.rs

1//! Finding target blocks in local data, and tracking which are known.
2//!
3//! [`BlockMatcher`] indexes the target's block checksums and then tests every
4//! byte offset of the data it is given. The rolling checksum slides along one
5//! byte at a time, a bit filter and a hash table reject most offsets without
6//! a lookup, and MD4 confirms what survives. With
7//! [`HashLengths::seq_matches`] of 2, a match that does not continue the
8//! previous one counts only when the block after it matches too, which keeps
9//! short rolling checksums from producing false matches. On a machine with
10//! more than one core, inputs of 32 MiB and more are split across threads.
11
12use crate::checksum::calc_md4;
13use crate::control::{ControlFile, HashLengths};
14use crate::rsum::{Rsum, calc_rsum_block};
15
16/// Why matching failed.
17#[derive(Debug, thiserror::Error)]
18pub enum MatchError {
19    /// An I/O error. Not currently returned by this crate.
20    #[error("IO error: {0}")]
21    Io(#[from] std::io::Error),
22}
23
24const HASH_EMPTY: u32 = u32::MAX;
25const BITHASH_BITS: u32 = 3;
26
27#[derive(Debug, Clone, Copy)]
28struct TargetBlock {
29    rsum: Rsum,
30    checksum: [u8; 16],
31}
32
33/// Read-only scan state shared across threads.
34struct ScanState<'a> {
35    targets: &'a [TargetBlock],
36    hash_table: &'a [u32],
37    hash_next: &'a [u32],
38    bithash: &'a [u8],
39    blocksize: usize,
40    blockshift: u8,
41    seq_matches: usize,
42    checksum_bytes: usize,
43    rsum_a_mask: u16,
44    hash_func_shift: u32,
45    hash_mask: u32,
46    bithash_mask: u32,
47}
48
49impl ScanState<'_> {
50    #[inline(always)]
51    fn calc_hash_rolling(&self, r0: &Rsum, r1: &Rsum) -> u32 {
52        let mut h = r0.b as u32;
53        if self.seq_matches > 1 {
54            h ^= (r1.b as u32) << self.hash_func_shift;
55        } else {
56            h ^= ((r0.a & self.rsum_a_mask) as u32) << self.hash_func_shift;
57        }
58        h
59    }
60
61    #[inline(always)]
62    fn rsum_match(&self, target: &Rsum, rolling: &Rsum) -> bool {
63        target.a == (rolling.a & self.rsum_a_mask) && target.b == rolling.b
64    }
65
66    /// Scan a chunk of data for matching blocks. Pure read-only, no mutations.
67    /// `base_offset` is the absolute byte offset of `data[0]` within the source file.
68    /// Returns vec of (target_block_id, absolute_source_offset).
69    fn scan_chunk(&self, data: &[u8], base_offset: usize) -> Vec<(usize, usize)> {
70        let blocksize = self.blocksize;
71        let blockshift = self.blockshift;
72        let seq_matches = self.seq_matches;
73        let checksum_bytes = self.checksum_bytes;
74        let context = blocksize * seq_matches;
75        let mut matched_blocks = Vec::new();
76
77        if data.len() < context {
78            return matched_blocks;
79        }
80
81        let x_limit = data.len() - context;
82        let mut x = 0usize;
83        let mut next_match_id: Option<usize> = None;
84
85        let mut r0 = calc_rsum_block(&data[0..blocksize]);
86        let mut r1 = if seq_matches > 1 {
87            calc_rsum_block(&data[blocksize..blocksize * 2])
88        } else {
89            Rsum { a: 0, b: 0 }
90        };
91
92        while x < x_limit {
93            let mut blocks_matched = 0usize;
94
95            if let Some(hint_id) = next_match_id.take()
96                && seq_matches > 1
97                && hint_id < self.targets.len()
98            {
99                let target = &self.targets[hint_id];
100                if self.rsum_match(&target.rsum, &r0) {
101                    let checksum = calc_md4(&data[x..x + blocksize]);
102                    if checksum[..checksum_bytes] == target.checksum[..checksum_bytes] {
103                        matched_blocks.push((hint_id, base_offset + x));
104                        blocks_matched = 1;
105                        if hint_id + 1 < self.targets.len() {
106                            next_match_id = Some(hint_id + 1);
107                        }
108                    }
109                }
110            }
111
112            while blocks_matched == 0 && x < x_limit {
113                let hash = self.calc_hash_rolling(&r0, &r1);
114
115                let bh = (hash & self.bithash_mask) as usize;
116                if self.bithash[bh >> 3] & (1 << (bh & 7)) != 0 {
117                    let mut block_idx = self.hash_table[(hash & self.hash_mask) as usize];
118
119                    while block_idx != HASH_EMPTY {
120                        let block_id = block_idx as usize;
121                        block_idx = self.hash_next[block_id];
122
123                        let target = &self.targets[block_id];
124                        if !self.rsum_match(&target.rsum, &r0) {
125                            continue;
126                        }
127
128                        if seq_matches > 1 && block_id + 1 < self.targets.len() {
129                            let next_target = &self.targets[block_id + 1];
130                            if !self.rsum_match(&next_target.rsum, &r1) {
131                                continue;
132                            }
133
134                            let checksum = calc_md4(&data[x..x + blocksize]);
135                            if checksum[..checksum_bytes] != target.checksum[..checksum_bytes] {
136                                continue;
137                            }
138
139                            let next_checksum = calc_md4(&data[x + blocksize..x + blocksize * 2]);
140                            if next_checksum[..checksum_bytes]
141                                == next_target.checksum[..checksum_bytes]
142                            {
143                                matched_blocks.push((block_id, base_offset + x));
144                                matched_blocks.push((block_id + 1, base_offset + x + blocksize));
145                                blocks_matched = seq_matches;
146
147                                if block_id + 2 < self.targets.len() {
148                                    next_match_id = Some(block_id + 2);
149                                }
150                                break;
151                            }
152                        } else {
153                            let checksum = calc_md4(&data[x..x + blocksize]);
154                            if checksum[..checksum_bytes] == target.checksum[..checksum_bytes] {
155                                matched_blocks.push((block_id, base_offset + x));
156                                blocks_matched = 1;
157                                break;
158                            }
159                        }
160                    }
161                }
162
163                if blocks_matched == 0 {
164                    let oc = data[x];
165                    let nc = data[x + blocksize];
166                    r0.a = r0.a.wrapping_add(u16::from(nc)).wrapping_sub(u16::from(oc));
167                    r0.b =
168                        r0.b.wrapping_add(r0.a)
169                            .wrapping_sub(u16::from(oc) << blockshift);
170
171                    if seq_matches > 1 {
172                        let nc2 = data[x + blocksize * 2];
173                        r1.a =
174                            r1.a.wrapping_add(u16::from(nc2))
175                                .wrapping_sub(u16::from(nc));
176                        r1.b =
177                            r1.b.wrapping_add(r1.a)
178                                .wrapping_sub(u16::from(nc) << blockshift);
179                    }
180
181                    x += 1;
182                }
183            }
184
185            if blocks_matched > 0 {
186                x += blocksize * blocks_matched;
187
188                if x >= x_limit {
189                    // Can't calculate rsums for remaining data
190                } else {
191                    if seq_matches > 1 && blocks_matched == 1 {
192                        r0 = r1;
193                    } else {
194                        r0 = calc_rsum_block(&data[x..x + blocksize]);
195                    }
196                    if seq_matches > 1 {
197                        r1 = calc_rsum_block(&data[x + blocksize..x + blocksize * 2]);
198                    }
199                }
200            }
201        }
202
203        matched_blocks
204    }
205}
206
207/// The index of a target's blocks and the record of which are known.
208///
209/// Every block starts unknown. A block becomes known when a scan finds it in
210/// local data or when downloaded data verifies against its checksum, and the
211/// blocks still unknown are what remains to download.
212pub struct BlockMatcher {
213    blocksize: usize,
214    blockshift: u8,
215    hash_lengths: HashLengths,
216    rsum_a_mask: u16,
217    hash_func_shift: u32,
218    targets: Vec<TargetBlock>,
219    known_blocks: Vec<bool>,
220    hash_table: Vec<u32>,
221    hash_next: Vec<u32>,
222    hash_mask: u32,
223    bithash: Vec<u8>,
224    bithash_mask: u32,
225}
226
227impl BlockMatcher {
228    /// Indexes the block checksums in `control`, with every block unknown.
229    pub fn new(control: &ControlFile) -> Self {
230        let num_blocks = control.block_checksums.len();
231        let seq_matches = control.hash_lengths.seq_matches as u32;
232        let rsum_bytes = control.hash_lengths.rsum_bytes as u32;
233
234        let rsum_a_mask: u16 = match rsum_bytes {
235            0..=2 => 0,
236            3 => 0x00ff,
237            _ => 0xffff,
238        };
239
240        let targets: Vec<TargetBlock> = control
241            .block_checksums
242            .iter()
243            .map(|bc| TargetBlock {
244                rsum: Rsum {
245                    a: bc.rsum.a & rsum_a_mask,
246                    b: bc.rsum.b,
247                },
248                checksum: bc.checksum,
249            })
250            .collect();
251
252        let rsum_bits = rsum_bytes * 8;
253        let avail_bits = if seq_matches > 1 {
254            rsum_bits.min(16) * 2
255        } else {
256            rsum_bits
257        };
258
259        let mut hash_bits = avail_bits;
260        while hash_bits > 5 && (1u32 << (hash_bits - 1)) > num_blocks as u32 {
261            hash_bits -= 1;
262        }
263        let hash_mask = (1u32 << hash_bits) - 1;
264
265        // Safe only because the parser caps a control file at 2^26 blocks,
266        // which holds hash_bits at 27 and this sum at 30. Raising that cap
267        // past 2^28 makes this reach 32, where the shift below overflows:
268        // a panic in debug, and a mask that collapses every bucket to one
269        // in release.
270        let bithash_bits_total = (hash_bits + BITHASH_BITS).min(avail_bits);
271        let bithash_mask = (1u32 << bithash_bits_total) - 1;
272
273        let hash_func_shift = if seq_matches > 1 && avail_bits < 24 {
274            bithash_bits_total.saturating_sub(avail_bits / 2)
275        } else {
276            bithash_bits_total.saturating_sub(avail_bits - 16)
277        };
278
279        let blockshift = control.blocksize.trailing_zeros() as u8;
280
281        let mut matcher = Self {
282            blocksize: control.blocksize,
283            blockshift,
284            hash_lengths: control.hash_lengths,
285            rsum_a_mask,
286            hash_func_shift,
287            targets,
288            known_blocks: vec![false; num_blocks],
289            hash_table: vec![HASH_EMPTY; (hash_mask + 1) as usize],
290            hash_next: vec![HASH_EMPTY; num_blocks],
291            hash_mask,
292            bithash: vec![0u8; ((bithash_mask + 1) >> 3) as usize + 1],
293            bithash_mask,
294        };
295
296        for id in (0..num_blocks).rev() {
297            let h = matcher.calc_hash(id);
298            let bucket = (h & hash_mask) as usize;
299            matcher.hash_next[id] = matcher.hash_table[bucket];
300            matcher.hash_table[bucket] = id as u32;
301            let bh = (h & bithash_mask) as usize;
302            matcher.bithash[bh >> 3] |= 1 << (bh & 7);
303        }
304
305        matcher
306    }
307
308    fn calc_hash(&self, block_id: usize) -> u32 {
309        let mut h = self.targets[block_id].rsum.b as u32;
310        if self.hash_lengths.seq_matches > 1 {
311            let next_b = if block_id + 1 < self.targets.len() {
312                self.targets[block_id + 1].rsum.b as u32
313            } else {
314                0
315            };
316            h ^= next_b << self.hash_func_shift;
317        } else {
318            h ^= (self.targets[block_id].rsum.a as u32) << self.hash_func_shift;
319        }
320        h
321    }
322
323    fn remove_block_from_hash(&mut self, id: usize) {
324        let h = self.calc_hash(id);
325        let bucket = (h & self.hash_mask) as usize;
326
327        let mut prev = HASH_EMPTY;
328        let mut curr = self.hash_table[bucket];
329
330        while curr != HASH_EMPTY {
331            if curr as usize == id {
332                if prev == HASH_EMPTY {
333                    self.hash_table[bucket] = self.hash_next[id];
334                } else {
335                    self.hash_next[prev as usize] = self.hash_next[id];
336                }
337                return;
338            }
339            prev = curr;
340            curr = self.hash_next[curr as usize];
341        }
342    }
343
344    fn scan_state(&self) -> ScanState<'_> {
345        ScanState {
346            targets: &self.targets,
347            hash_table: &self.hash_table,
348            hash_next: &self.hash_next,
349            bithash: &self.bithash,
350            blocksize: self.blocksize,
351            blockshift: self.blockshift,
352            seq_matches: self.hash_lengths.seq_matches as usize,
353            checksum_bytes: self.hash_lengths.checksum_bytes as usize,
354            rsum_a_mask: self.rsum_a_mask,
355            hash_func_shift: self.hash_func_shift,
356            hash_mask: self.hash_mask,
357            bithash_mask: self.bithash_mask,
358        }
359    }
360
361    /// Verifies `data` as consecutive whole blocks starting at block
362    /// `block_start`, marking each one that matches its checksum as known.
363    ///
364    /// A final block shorter than the block size must be padded with zeros
365    /// to a full block, as the checksums were computed that way. Trailing
366    /// bytes short of a block are ignored, as are blocks past the end of the
367    /// target. Verification stops at the first mismatch and returns `false`,
368    /// leaving the blocks before it known.
369    ///
370    /// # Errors
371    ///
372    /// None at present. The `Result` leaves room for one.
373    pub fn submit_blocks(&mut self, data: &[u8], block_start: usize) -> Result<bool, MatchError> {
374        let blocksize = self.blocksize;
375        let checksum_bytes = self.hash_lengths.checksum_bytes as usize;
376        let num_blocks = data.len() / blocksize;
377
378        for i in 0..num_blocks {
379            let block_data = &data[i * blocksize..(i + 1) * blocksize];
380            let block_id = block_start + i;
381
382            if block_id >= self.targets.len() {
383                break;
384            }
385
386            let checksum = calc_md4(block_data);
387            if checksum[..checksum_bytes] == self.targets[block_id].checksum[..checksum_bytes] {
388                self.known_blocks[block_id] = true;
389            } else {
390                return Ok(false);
391            }
392        }
393
394        Ok(true)
395    }
396
397    /// Scans `data` for target blocks at every byte offset and marks the ones
398    /// found as known.
399    ///
400    /// `offset` is where `data` starts in its source, and the returned
401    /// `(block_id, source_offset)` pairs give absolute offsets in that
402    /// source. Offsets are tested only up to `blocksize * seq_matches` bytes
403    /// before the end of `data`, so a caller scanning a file in chunks must
404    /// overlap them by that much and pad the end of the file with zeros.
405    ///
406    /// Each block is reported at most once, at the first offset found. Found
407    /// blocks leave the index, so a later scan does not report them again.
408    pub fn submit_source_data(&mut self, data: &[u8], offset: u64) -> Vec<(usize, usize)> {
409        let context = self.blocksize * self.hash_lengths.seq_matches as usize;
410        if data.len() < context {
411            return Vec::new();
412        }
413
414        let num_threads = std::thread::available_parallelism()
415            .map(|n| n.get())
416            .unwrap_or(1);
417
418        let min_per_thread = 16 * 1024 * 1024; // 16 MB per thread minimum
419        let scannable = data.len() - context;
420
421        let candidates = if num_threads > 1 && scannable >= min_per_thread * 2 {
422            let state = self.scan_state();
423            let actual_threads = num_threads.min(scannable / min_per_thread);
424            let chunk_size = scannable / actual_threads;
425
426            std::thread::scope(|s| {
427                let handles: Vec<_> = (0..actual_threads)
428                    .map(|i| {
429                        let start = i * chunk_size;
430                        let end = if i == actual_threads - 1 {
431                            data.len()
432                        } else {
433                            (i + 1) * chunk_size + context
434                        };
435                        let chunk = &data[start..end];
436                        let state = &state;
437                        let base = offset as usize + start;
438                        s.spawn(move || state.scan_chunk(chunk, base))
439                    })
440                    .collect();
441
442                let mut all: Vec<(usize, usize)> = Vec::new();
443                for h in handles {
444                    all.extend(h.join().unwrap());
445                }
446                all
447            })
448        } else {
449            let state = self.scan_state();
450            state.scan_chunk(data, offset as usize)
451        };
452
453        // Deduplicate: first match per block_id wins
454        let mut seen = vec![false; self.targets.len()];
455        let mut matched_blocks = Vec::new();
456        for (block_id, offset) in candidates {
457            if !seen[block_id] {
458                seen[block_id] = true;
459                self.known_blocks[block_id] = true;
460                self.remove_block_from_hash(block_id);
461                matched_blocks.push((block_id, offset));
462            }
463        }
464
465        matched_blocks
466    }
467
468    /// The runs of blocks still unknown, as half-open `(first, end)` ranges
469    /// in ascending order.
470    pub fn needed_block_ranges(&self) -> Vec<(usize, usize)> {
471        let mut ranges = Vec::new();
472        let mut start: Option<usize> = None;
473
474        for (i, &known) in self.known_blocks.iter().enumerate() {
475            if !known && start.is_none() {
476                start = Some(i);
477            } else if known && start.is_some() {
478                ranges.push((start.unwrap(), i));
479                start = None;
480            }
481        }
482
483        if let Some(s) = start {
484            ranges.push((s, self.known_blocks.len()));
485        }
486
487        ranges
488    }
489
490    /// Whether block `block_id` is known, which is `false` past the end of the
491    /// target.
492    pub fn is_block_known(&self, block_id: usize) -> bool {
493        block_id < self.known_blocks.len() && self.known_blocks[block_id]
494    }
495
496    /// The number of blocks still unknown.
497    pub fn blocks_todo(&self) -> usize {
498        self.known_blocks.iter().filter(|&&k| !k).count()
499    }
500
501    /// Whether every block is known.
502    pub fn is_complete(&self) -> bool {
503        self.known_blocks.iter().all(|&k| k)
504    }
505
506    /// The number of blocks in the target.
507    pub fn total_blocks(&self) -> usize {
508        self.targets.len()
509    }
510}
511
512#[cfg(test)]
513mod tests {
514    use super::*;
515    use crate::control::{BlockChecksum, ControlFile, HashLengths};
516
517    fn make_control(data: &[u8], blocksize: usize) -> ControlFile {
518        let num_blocks = data.len().div_ceil(blocksize);
519        let mut block_checksums = Vec::with_capacity(num_blocks);
520
521        for i in 0..num_blocks {
522            let start = i * blocksize;
523            let end = std::cmp::min(start + blocksize, data.len());
524            let mut block = data[start..end].to_vec();
525            block.resize(blocksize, 0);
526
527            let rsum = calc_rsum_block(&block);
528            let checksum = calc_md4(&block);
529
530            block_checksums.push(BlockChecksum { rsum, checksum });
531        }
532
533        ControlFile {
534            version: "0.6.2".to_string(),
535            filename: Some("test.bin".to_string()),
536            mtime: None,
537            blocksize,
538            length: data.len() as u64,
539            hash_lengths: HashLengths {
540                seq_matches: 1,
541                rsum_bytes: 4,
542                checksum_bytes: 16,
543            },
544            urls: vec!["http://example.com/test.bin".to_string()],
545            sha1: None,
546            block_checksums,
547        }
548    }
549
550    #[test]
551    fn test_matcher_new() {
552        let data = vec![1u8, 2, 3, 4, 5, 6, 7, 8];
553        let control = make_control(&data, 4);
554        let matcher = BlockMatcher::new(&control);
555        assert_eq!(matcher.blocks_todo(), 2);
556    }
557
558    #[test]
559    fn test_submit_source_data() {
560        let data = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
561        let control = make_control(&data, 4);
562        let mut matcher = BlockMatcher::new(&control);
563
564        // Pad with context bytes (blocksize * seq_matches) like submit_source_file does
565        let mut padded = data.clone();
566        padded.resize(data.len() + 4, 0);
567        let got = matcher.submit_source_data(&padded, 0);
568        assert_eq!(got.len(), 3);
569        assert!(matcher.is_complete());
570    }
571
572    #[test]
573    fn test_needed_block_ranges() {
574        let data = vec![1u8, 2, 3, 4, 5, 6, 7, 8];
575        let control = make_control(&data, 4);
576        let matcher = BlockMatcher::new(&control);
577        let ranges = matcher.needed_block_ranges();
578        assert_eq!(ranges, vec![(0, 2)]);
579    }
580}