From 294d5654557b1799a82647dd4605e3abdf87ea4e Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Sun, 15 Nov 2026 14:45:45 -0500 Subject: [PATCH] perf: scan patch bytes directly for search Search read every source line through its own reader and zeroed a 64 KiB buffer twice per line, so a search ran at about 80 MB/s: 9 s to the first match on the 711 MB Linux v6.0...v7.0 patch. Files without revealed context are now scanned in spool order with memchr::memmem through one reusable 1 MiB window. A raw occurrence counts only when it lies inside one source record, so signs, headers, paths and markers still never match. Files whose unified rows do not follow record order, and files with revealed context, keep the per-line path. The per-line path no longer zeroes its buffer for each line. Results are pinned by new tests that compare every search with a brute-force oracle over the frozen source order. --- CHANGELOG.md | 3 + src/engine/tests.rs | 1 + src/engine/tests/search_semantics.rs | 368 +++++++++++++++++++++++++++ src/projection.rs | 18 ++ src/reading.rs | 1 + src/reading/literal.rs | 33 +-- src/reading/literal/tests.rs | 6 +- src/reading/scan.rs | 194 ++++++++++++++ src/reading/search.rs | 245 ++++++++++++++---- src/source_spans.rs | 22 +- src/storage.rs | 6 +- src/storage/reader.rs | 110 ++++++++ src/view/reading.rs | 5 + 13 files changed, 932 insertions(+), 80 deletions(-) create mode 100644 src/engine/tests/search_semantics.rs create mode 100644 src/reading/scan.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b31b51..0482e7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,9 @@ All notable changes to `diffs-rs` are recorded here. The forked crates in renamed or copied) and show `+N` in the addition color and `−N` in the deletion color, as Hunk does. Folder totals use the same count colors. `theme::Colors` gains `modified` and `renamed`, which breaks code that builds `Colors` by hand. +- Search scans the patch bytes directly instead of reading each source line on its own. On + the 711 MB Linux v6.0…v7.0 patch the first match and a wrapping F3 take about 60 ms + instead of 3–9 s. Results do not change. ## 0.1.0 - 2026-10-27 diff --git a/src/engine/tests.rs b/src/engine/tests.rs index eed9efb..7749f4d 100644 --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -9,6 +9,7 @@ use crate::{ mod domain; mod search; mod search_delivery; +mod search_semantics; mod selection; fn checked_review(prefix: &[u8]) -> (Engine, tempfile::TempDir, Vec>) { diff --git a/src/engine/tests/search_semantics.rs b/src/engine/tests/search_semantics.rs new file mode 100644 index 0000000..7faa4ab --- /dev/null +++ b/src/engine/tests/search_semantics.rs @@ -0,0 +1,368 @@ +//! Pins literal search results against an independent brute-force oracle. +//! The oracle reads every searchable source line through the frozen order and lists each +//! occurrence, so a faster scan cannot change which match, offset, or wrap state is reported. + +use std::io::Read; + +use super::{search::review, *}; +use crate::{ + input::{Cancellation, Cancelled}, + reading::{ + domain::Domain, + literal::Direction, + search::{Hit, Position}, + }, + view::LineId, +}; + +type Expected = (Position, LineId, std::ops::Range); + +fn line_bytes(domain: &Domain, file: usize, source: LineId) -> Vec { + let file = &domain.files[file]; + match source { + LineId::Patch(id) => file.order.file.bytes(id).unwrap(), + LineId::Context { new, .. } => { + let mut bytes = Vec::new(); + file.context + .as_ref() + .unwrap() + .uncached_lines() + .line(new.get(), 0) + .unwrap() + .read_to_end(&mut bytes) + .unwrap(); + bytes + } + } +} + +/// Every occurrence in frozen unified order, overlapping ones included. +fn occurrences(domain: &Domain, query: &str) -> Vec { + let needle = query.as_bytes(); + let mut hits = Vec::new(); + for (file_id, file) in domain.files.iter().enumerate() { + for row in 0..file.order.len() { + let Some(source) = file.order.source(row) else { + continue; + }; + let bytes = line_bytes(domain, file_id, source); + for start in 0..bytes.len() { + if bytes[start..].starts_with(needle) { + let start = start as u64; + hits.push(( + Position { + file: file_id, + row, + byte: start, + }, + source, + start..start + needle.len() as u64, + )); + } + } + } + } + hits +} + +fn expected(hits: &[Expected], origin: Position, direction: Direction) -> Option<(Expected, bool)> { + match direction { + Direction::Forward => hits + .iter() + .find(|hit| hit.0 >= origin) + .map(|hit| (hit.clone(), false)) + .or_else(|| hits.first().map(|hit| (hit.clone(), true))), + Direction::Backward => hits + .iter() + .rev() + .find(|hit| hit.0 < origin) + .map(|hit| (hit.clone(), false)) + .or_else(|| hits.last().map(|hit| (hit.clone(), true))), + } +} + +fn actual(hit: Option) -> Option<(Expected, bool)> { + hit.map(|hit| ((hit.position, hit.source, hit.bytes), hit.wrapped)) +} + +/// Origins at every `hit_stride`-th match, one byte after it, the rows around it, both ends, +/// and every row of every `stride`-th file. +fn origins(domain: &Domain, hits: &[Expected], stride: usize, hit_stride: usize) -> Vec { + let mut origins = vec![ + Position::default(), + Position { + file: domain.files.len(), + ..Position::default() + }, + ]; + for (file_id, file) in domain.files.iter().enumerate().step_by(stride) { + for row in 0..=file.order.len() { + origins.push(Position { + file: file_id, + row, + byte: 0, + }); + } + } + for (position, _, bytes) in hits.iter().step_by(hit_stride) { + origins.push(*position); + origins.push(Position { + byte: bytes.start + 1, + ..*position + }); + for row in [position.row.saturating_sub(1), position.row + 1] { + origins.push(Position { + row, + byte: 0, + ..*position + }); + } + } + origins.sort(); + origins.dedup(); + origins +} + +fn assert_matches_oracle(domain: &Domain, query: &str) -> usize { + assert_matches_oracle_from(domain, query, 1, 1) +} + +fn assert_matches_oracle_from( + domain: &Domain, + query: &str, + stride: usize, + hit_stride: usize, +) -> usize { + let hits = occurrences(domain, query); + for origin in origins(domain, &hits, stride, hit_stride) { + for direction in [Direction::Forward, Direction::Backward] { + let found = domain + .find(query, origin, direction, &|| Ok(())) + .unwrap_or_else(|error| panic!("{query:?} from {origin:?}: {error:#}")); + assert_eq!( + actual(found), + expected(&hits, origin, direction), + "{query:?} {direction:?} from {origin:?}" + ); + } + } + hits.len() +} + +const STRUCTURE: &[u8] = b"diff --git a/needle_path.c b/needle_path.c +index 1111111..2222222 100644 +--- a/needle_path.c ++++ b/needle_path.c +@@ -1,6 +1,6 @@ needle_function(void) + context needle +-removed needle Needle ++added needle + needleneedle +-a needle ++b needle +-c needle ++d needle + tail +diff --git a/needle.bin b/needle.bin +new file mode 100644 +index 0000000..3333333 +Binary files /dev/null and b/needle.bin differ +diff --git a/old needle b/new needle +similarity index 100% +rename from old needle +rename to new needle +diff --git a/signs b/signs +--- a/signs ++++ b/signs +@@ -10,4 +10,4 @@ needle + x +-+needle +++-needle + y needle\r +-z +\\ No newline at end of file ++z needle +\\ No newline at end of file +"; + +#[test] +fn search_semantics_match_the_oracle_for_structure_signs_case_and_order() { + let (mut engine, _directory) = review(STRUCTURE); + let domain = engine.search_domain().unwrap(); + // Context, both sides of a change, interleaved changes, and overlapping hits. + assert_eq!(assert_matches_oracle(&domain, "needle"), 13); + // Case-sensitive: one capitalised occurrence only. + assert_eq!(assert_matches_oracle(&domain, "Needle"), 1); + // Signs are not source text: these only match the source that begins with them. + assert_eq!(assert_matches_oracle(&domain, "+needle"), 1); + assert_eq!(assert_matches_oracle(&domain, "-needle"), 1); + assert_eq!(assert_matches_oracle(&domain, " context"), 0); + assert_eq!(assert_matches_oracle(&domain, "context"), 1); + // Headers, paths, hunk function context, binary and rename records, markers: no matches. + for query in [ + "needle_path", + "needle_function", + "diff --git", + "index 1111111", + "@@", + "Binary files", + "rename from", + "similarity", + "No newline", + "\\", + "needle.bin", + "new needle\n", + ] { + if query.contains('\n') { + assert!( + domain + .find(query, Position::default(), Direction::Forward, &|| Ok(())) + .is_err() + ); + continue; + } + assert_eq!(assert_matches_oracle(&domain, query), 0, "{query:?}"); + } + // Overlapping occurrences inside one line, and text that spans a removed sign. + assert_eq!(assert_matches_oracle(&domain, "needleneedle"), 1); + assert_eq!(assert_matches_oracle(&domain, "eneed"), 1); + assert_eq!(assert_matches_oracle(&domain, "e"), 46); + assert_eq!(assert_matches_oracle(&domain, "z"), 2); + assert_eq!(assert_matches_oracle(&domain, "y needle"), 1); + // Unified order lists a replacement block's removed lines before its added lines. + // Source records keep their line ending; queries cannot contain one. + let hits = occurrences(&domain, "needle"); + let lines: Vec<_> = hits + .iter() + .map(|(position, source, _)| { + String::from_utf8(line_bytes(&domain, position.file, *source)).unwrap() + }) + .collect(); + assert_eq!( + lines, + [ + "context needle\n", + "removed needle Needle\n", + "added needle\n", + "needleneedle\n", + "needleneedle\n", + "a needle\n", + "c needle\n", + "b needle\n", + "d needle\n", + "+needle\n", + "+-needle\n", + "y needle\r\n", + "z needle", + ] + ); + assert_eq!( + hits.iter().map(|hit| hit.0.file).collect::>(), + [0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3] + ); + engine.close().unwrap(); +} + +/// Many small files, a few hits, long lines across read-window boundaries. +fn large_patch() -> (Vec, String) { + let query = "zq_needle_\u{65e5}"; + let mut patch = Vec::new(); + let mut state = 0x2545_f491_u32; + let mut next = move || { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + state + }; + for file in 0..2500 { + patch.extend_from_slice( + format!("diff --git a/f{file} b/f{file}\n--- a/f{file}\n+++ b/f{file}\n").as_bytes(), + ); + let lines = 1 + next() as usize % 6; + patch.extend_from_slice(format!("@@ -1,{lines} +1,{lines} @@ {query}\n").as_bytes()); + for line in 0..lines { + let mut text = format!("{file} {line} filler text"); + match next() % 400 { + 0 => text.push_str(query), + 1 => text.insert_str(0, query), + 2 => text = format!("{query}{query}"), + _ => {} + } + match next() % 3 { + 0 => patch.extend_from_slice(format!(" {text}\n").as_bytes()), + _ => patch.extend_from_slice(format!("-{text}\n+{text} new\n").as_bytes()), + } + } + if file % 500 == 250 { + // Long lines whose hits straddle 64 KiB and 1 MiB read boundaries. + let mut long = vec![b'.'; 3 * 1024 * 1024 + 17]; + for boundary in [64 * 1024, 1024 * 1024, 2 * 1024 * 1024, 3 * 1024 * 1024] { + let at = boundary - 5 - file % 7; + long[at..at + query.len()].copy_from_slice(query.as_bytes()); + } + patch.extend_from_slice(b"@@ -100 +100 @@\n-"); + patch.extend_from_slice(&long); + patch.extend_from_slice(b"\n+"); + patch.extend_from_slice(&long[..long.len() - 9]); + patch.push(b'\n'); + // Correct the hunk header counts by adding this as its own hunk. + } + } + (patch, query.to_owned()) +} + +#[test] +fn search_semantics_match_the_oracle_across_many_files_and_long_lines() { + let (patch, query) = large_patch(); + let (mut engine, _directory) = review(&patch); + let domain = engine.search_domain().unwrap(); + assert_eq!(domain.files.len(), 2500); + let hits = assert_matches_oracle_from(&domain, &query, 97, 1); + assert!(hits > 40, "{hits}"); + assert_eq!(assert_matches_oracle_from(&domain, "absent text", 97, 1), 0); + // Common text: the first hit is near, but the scan must still honour order and bounds. + assert_matches_oracle_from(&domain, "filler text new", 499, 211); + engine.close().unwrap(); +} + +#[test] +fn search_semantics_include_exposed_context_in_order() { + let (mut engine, _directory, pairs) = checked_review(b"needle one needle\n"); + install(&mut engine, &pairs); + { + let app = engine.app.as_mut().unwrap(); + app.view.expand(&app.doc, 0, 0).unwrap(); + } + let domain = engine.search_domain().unwrap(); + assert!(domain.files[0].order.has_context()); + assert_eq!(assert_matches_oracle(&domain, "needle"), 2); + assert_eq!(assert_matches_oracle(&domain, "e"), 13); + engine.close().unwrap(); +} + +#[test] +fn search_without_a_match_or_after_cancellation_reports_none_or_cancelled() { + let (patch, _) = large_patch(); + let (mut engine, _directory) = review(&patch); + let domain = engine.search_domain().unwrap(); + for direction in [Direction::Forward, Direction::Backward] { + assert!( + domain + .find("absent text", Position::default(), direction, &|| Ok(())) + .unwrap() + .is_none() + ); + let cancel = Cancellation::default(); + let checks = std::cell::Cell::new(0); + let result = domain.find("absent text", Position::default(), direction, &|| { + checks.set(checks.get() + 1); + if checks.get() == 5 { + cancel.stop(); + } + cancel.check() + }); + assert!(result.unwrap_err().is::()); + assert_eq!(checks.get(), 5); + } + engine.close().unwrap(); +} diff --git a/src/projection.rs b/src/projection.rs index e2fa9e1..e5aa352 100644 --- a/src/projection.rs +++ b/src/projection.rs @@ -215,6 +215,24 @@ impl Projection { self.display_row(self.logical_source_row(id, split), split) } + /// Whether unified rows list source records in record order. A patch that interleaves + /// removed and added lines inside one change block lists them out of order. + pub(crate) fn unified_follows_source(&self) -> bool { + (0..self.tables.block_count()).all(|n| { + let BlockKind::Replacement(r) = self.tables.block(n).kind else { + return true; + }; + let r = self.tables.replacement(r); + if r.old_start == r.new_start || r.new_start == r.end { + return true; + } + // Runs are disjoint and each side lists its runs in record order. + let last_old = self.tables.run(self.tables.side_run(r.new_start - 1)); + let first_new = self.tables.run(self.tables.side_run(r.new_start)); + last_old.start < first_new.start + }) + } + pub(crate) fn hunk_row(&self, index: usize, split: bool) -> usize { self.hunks[index][usize::from(split)] } diff --git a/src/reading.rs b/src/reading.rs index 5d1d047..d19ad2a 100644 --- a/src/reading.rs +++ b/src/reading.rs @@ -19,6 +19,7 @@ use crate::{ pub(crate) mod domain; pub(crate) mod literal; +mod scan; pub(crate) mod search; mod search_read; pub use literal::Direction as SearchDirection; diff --git a/src/reading/literal.rs b/src/reading/literal.rs index d4d6e72..55680ca 100644 --- a/src/reading/literal.rs +++ b/src/reading/literal.rs @@ -16,9 +16,10 @@ pub enum Direction { } pub(crate) struct Literal<'a> { - forward: Finder<'a>, - backward: FinderRev<'a>, - buffer: Vec, + pub(super) forward: Finder<'a>, + pub(super) backward: FinderRev<'a>, + /// Read scratch, zeroed once: per-record searches must not clear it again. + buffer: Box<[u8]>, } pub(crate) fn validate(query: &str) -> Result<()> { @@ -40,10 +41,14 @@ impl<'a> Literal<'a> { Ok(Self { forward: Finder::new(query.as_bytes()), backward: FinderRev::new(query.as_bytes()), - buffer: Vec::with_capacity(CHUNK + query.len() - 1), + buffer: vec![0; CHUNK + query.len() - 1].into_boxed_slice(), }) } + pub(super) fn len(&self) -> usize { + self.forward.needle().len() + } + /// The reader begins at `starts.start` within one original source record. /// Bounds restrict match starts, not ends; overlapping matches remain eligible. /// Backward search scans forward and retains only the latest eligible match. @@ -56,31 +61,29 @@ impl<'a> Literal<'a> { ) -> Result>> { ensure!(starts.start <= starts.end, "Invalid search byte range"); check()?; - self.buffer.clear(); if starts.is_empty() { return Ok(None); } let needle = self.forward.needle().len(); let mut base = starts.start; + let mut retained = 0; let mut found = None; loop { check()?; - let retained = self.buffer.len(); - self.buffer.resize(retained + CHUNK, 0); let count = loop { - match input.read(&mut self.buffer[retained..]) { + match input.read(&mut self.buffer[retained..retained + CHUNK]) { Err(error) if error.kind() == io::ErrorKind::Interrupted => check()?, result => break result?, } }; - self.buffer.truncate(retained + count); + let filled = retained + count; check()?; if count == 0 { return Ok(found); } - if self.buffer.len() >= needle { + if filled >= needle { let complete = base - .checked_add((self.buffer.len() - needle + 1) as u64) + .checked_add((filled - needle + 1) as u64) .context("Search byte offset overflow")?; let eligible = complete.min(starts.end); if eligible > base { @@ -105,10 +108,10 @@ impl<'a> Literal<'a> { return Ok(found); } } - let keep = self.buffer.len().min(needle - 1); - let consumed = self.buffer.len() - keep; - self.buffer.copy_within(consumed.., 0); - self.buffer.truncate(keep); + let keep = filled.min(needle - 1); + let consumed = filled - keep; + self.buffer.copy_within(consumed..filled, 0); + retained = keep; base = base .checked_add(consumed as u64) .context("Search byte offset overflow")?; diff --git a/src/reading/literal/tests.rs b/src/reading/literal/tests.rs index 0122766..3595f9e 100644 --- a/src/reading/literal/tests.rs +++ b/src/reading/literal/tests.rs @@ -90,7 +90,7 @@ fn unicode_queries_cross_chunk_boundaries_without_sanitizing_source_offsets() { expected(&text, &query, starts.clone(), direction), "{starts:?} {direction:?}" ); - assert!(literal.buffer.capacity() < CHUNK + QUERY_BYTES); + assert!(literal.buffer.len() < CHUNK + QUERY_BYTES); } } } @@ -147,7 +147,7 @@ fn no_match_scan_remains_cancellable_and_the_buffer_is_reused() { .unwrap_err(); assert!(error.is::()); assert!(file.stream_position().unwrap() <= CHUNK as u64); - let capacity = literal.buffer.capacity(); + let capacity = literal.buffer.len(); file.rewind().unwrap(); assert_eq!( literal @@ -155,5 +155,5 @@ fn no_match_scan_remains_cancellable_and_the_buffer_is_reused() { .unwrap(), None ); - assert_eq!(literal.buffer.capacity(), capacity); + assert_eq!(literal.buffer.len(), capacity); } diff --git a/src/reading/scan.rs b/src/reading/scan.rs new file mode 100644 index 0000000..246aa53 --- /dev/null +++ b/src/reading/scan.rs @@ -0,0 +1,194 @@ +//! Raw patch-byte scanning for literal search. +//! +//! A file's patch source records lie in the spool in record order, separated by signs, +//! hunk headers, and markers. A raw occurrence counts only when it lies entirely inside one +//! record's source bytes, so headers, paths, signs, and markers never match. + +use anyhow::Result; + +use super::literal::Literal; +use crate::storage::{FileIndex, PatchScan, SpanWindow}; + +/// Cancellation granularity for raw scans. +const SLICE: usize = 16 * 1024; + +#[derive(Clone, Copy)] +struct Line { + id: usize, + start: u64, + end: u64, +} + +impl Line { + fn read(spans: &mut SpanWindow, file: &FileIndex, id: usize) -> Result { + let (start, len) = spans.get(file, id)?; + Ok(Self { + id, + start, + end: start + len as u64, + }) + } + + fn contains(&self, hit: u64, needle: usize) -> bool { + self.start <= hit && hit + needle as u64 <= self.end + } +} + +/// The spool offset just past a file's last patch source record. +pub(super) fn file_end(spans: &mut SpanWindow, file: &FileIndex) -> Result { + Ok(Line::read(spans, file, file.source_end() - 1)?.end) +} + +/// The first record from `line` onward whose end lies after `hit`, by galloping search. +fn seek_forward( + spans: &mut SpanWindow, + file: &FileIndex, + line: Line, + hit: u64, +) -> Result> { + if line.end > hit { + return Ok(Some(line)); + } + let last = file.source_end() - 1; + // Invariant: `below` ends at or before `hit`; `above` ends after it. + let mut below = line.id; + let mut step = 1; + let mut above = loop { + if below == last { + return Ok(None); + } + let probe = below.saturating_add(step).min(last); + if Line::read(spans, file, probe)?.end > hit { + break probe; + } + below = probe; + step *= 2; + }; + while above - below > 1 { + let middle = below + (above - below) / 2; + if Line::read(spans, file, middle)?.end > hit { + above = middle; + } else { + below = middle; + } + } + Line::read(spans, file, above).map(Some) +} + +/// The last record from `line` backward whose start is at or before `hit`. +fn seek_backward( + spans: &mut SpanWindow, + file: &FileIndex, + line: Line, + hit: u64, +) -> Result> { + if line.start <= hit { + return Ok(Some(line)); + } + let first = file.source_base; + // Invariant: `below` starts at or before `hit`; `above` starts after it. + let mut above = line.id; + let mut step = 1; + let mut below = loop { + if above == first { + return Ok(None); + } + let probe = above.saturating_sub(step).max(first); + if Line::read(spans, file, probe)?.start <= hit { + break probe; + } + above = probe; + step *= 2; + }; + while above - below > 1 { + let middle = below + (above - below) / 2; + if Line::read(spans, file, middle)?.start <= hit { + below = middle; + } else { + above = middle; + } + } + Line::read(spans, file, below).map(Some) +} + +/// The first occurrence inside one source record that starts in `begin..limit`. +/// `line` is the record that holds `begin`, or the first record after it. +/// Returns the record and the occurrence's byte offset within it. +pub(super) fn first( + scan: &mut PatchScan, + literal: &Literal<'_>, + file: &FileIndex, + line: usize, + begin: u64, + limit: u64, + check: &impl Fn() -> Result<()>, +) -> Result> { + let PatchScan { bytes, spans } = scan; + let needle = literal.len(); + let end = file_end(spans, file)?.min(limit.saturating_add(needle as u64 - 1)); + let mut line = Line::read(spans, file, line)?; + let mut position = begin; + while position + needle as u64 <= end { + check()?; + let window = bytes.after(&file.spool, position, end, needle)?; + let window = &window[..window.len().min(SLICE + needle - 1)]; + let mut from = 0; + while let Some(index) = literal.forward.find(&window[from..]) { + let hit = position + (from + index) as u64; + let Some(next) = seek_forward(spans, file, line, hit)? else { + return Ok(None); + }; + line = next; + if line.contains(hit, needle) { + return Ok(Some((line.id, hit - line.start))); + } + from += index + 1; + } + position += (window.len() - needle + 1) as u64; + } + Ok(None) +} + +/// The last occurrence inside one source record that starts in `floor..limit`. +pub(super) fn last( + scan: &mut PatchScan, + literal: &Literal<'_>, + file: &FileIndex, + floor: u64, + limit: u64, + check: &impl Fn() -> Result<()>, +) -> Result> { + let PatchScan { bytes, spans } = scan; + let needle = literal.len(); + let mut line = Line::read(spans, file, file.source_end() - 1)?; + let mut end = line.end.min(limit.saturating_add(needle as u64 - 1)); + let mut hits = Vec::new(); + while end >= floor + needle as u64 { + check()?; + let (start, window) = bytes.before(&file.spool, floor, end, needle)?; + let skip = window.len().saturating_sub(SLICE + needle - 1); + let (start, window) = (start + skip as u64, &window[skip..]); + // memchr's reverse searcher has no vector prefilter, so collect this slice's + // occurrences forward and validate them from the end. + hits.clear(); + let mut from = 0; + while let Some(index) = literal.forward.find(&window[from..]) { + hits.push(start + (from + index) as u64); + from += index + 1; + } + for &hit in hits.iter().rev() { + let Some(previous) = seek_backward(spans, file, line, hit)? else { + return Ok(None); + }; + line = previous; + if line.contains(hit, needle) { + return Ok(Some((line.id, hit - line.start))); + } + } + if start == floor { + break; + } + end = start + needle as u64 - 1; + } + Ok(None) +} diff --git a/src/reading/search.rs b/src/reading/search.rs index d7ba227..a48df96 100644 --- a/src/reading/search.rs +++ b/src/reading/search.rs @@ -3,10 +3,11 @@ use std::ops::Range; use anyhow::{Context, Result, ensure}; use super::{ - domain::Domain, + domain::{Domain, SourceFile}, literal::{Direction, Literal}, + scan, }; -use crate::{engine::ReviewId, view::LineId}; +use crate::{engine::ReviewId, storage::PatchScan, view::LineId}; /// A boundary in frozen unified order. Byte offsets refer to original source. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] @@ -74,8 +75,9 @@ impl Domain { Direction::Forward => [(origin..end, false), (Position::default()..origin, true)], Direction::Backward => [(Position::default()..origin, false), (origin..end, true)], }; + let mut patch = PatchScan::default(); for (range, wrapped) in segments { - if let Some(mut hit) = self.scan(&mut literal, range, direction, &check)? { + if let Some(mut hit) = self.scan(&mut literal, &mut patch, range, direction, &check)? { check()?; hit.wrapped = wrapped; return Ok(Some(hit)); @@ -88,72 +90,203 @@ impl Domain { fn scan( &self, literal: &mut Literal<'_>, + patch: &mut PatchScan, range: Range, direction: Direction, check: &impl Fn() -> Result<()>, ) -> Result> { - if range.is_empty() { + if range.is_empty() || self.files.is_empty() { return Ok(None); } - let mut found = None; - for (file_id, file) in self.files.iter().enumerate().skip(range.start.file) { - if file_id > range.end.file { - break; + let files = range.start.file..=range.end.file.min(self.files.len() - 1); + let mut visit = |file| { + check()?; + self.scan_file(literal, patch, file, &range, direction, check) + }; + match direction { + Direction::Forward => { + for file in files { + if let Some(hit) = visit(file)? { + return Ok(Some(hit)); + } + } + } + Direction::Backward => { + for file in files.rev() { + if let Some(hit) = visit(file)? { + return Ok(Some(hit)); + } + } } + } + Ok(None) + } + + /// The first (forward) or last (backward) hit in `range` within one file. + fn scan_file( + &self, + literal: &mut Literal<'_>, + patch: &mut PatchScan, + file_id: usize, + range: &Range, + direction: Direction, + check: &impl Fn() -> Result<()>, + ) -> Result> { + let file = &self.files[file_id]; + let first = if file_id == range.start.file { + range.start.row + } else { + 0 + }; + let last = if file_id == range.end.file { + range + .end + .row + .saturating_add(usize::from(range.end.byte != 0)) + .min(file.order.len()) + } else { + file.order.len() + }; + if first >= last { + return Ok(None); + } + if !file.order.is_projection() { + // Revealed context comes from another store: read records one by one. + return self.scan_rows(literal, file_id, first..last, range, direction, check); + } + let index = &file.order.file; + if index.source_end() == index.source_base { + return Ok(None); + } + // Row bounds become spool bounds only when rows follow record order. Check that + // once per bounded file; other files check it only when they contain a hit. + let bounded = file_id == range.start.file || file_id == range.end.file; + let mut ordered = None; + if bounded && !*ordered.insert(index.unified_follows_source()) { + return self.scan_rows(literal, file_id, first..last, range, direction, check); + } + let (line, begin) = if file_id == range.start.file { + match self.spool_bound(patch, file, range.start.row, range.start.byte)? { + Some(bound) => bound, + None => return Ok(None), + } + } else { + let id = index.source_base; + (id, patch.spans.get(index, id)?.0) + }; + let limit = match (file_id == range.end.file) + .then(|| self.spool_bound(patch, file, range.end.row, range.end.byte)) + .transpose()? + .flatten() + { + Some((_, limit)) => limit, + None => scan::file_end(&mut patch.spans, index)?, + }; + if begin >= limit { + return Ok(None); + } + let found = match direction { + Direction::Forward => scan::first(patch, literal, index, line, begin, limit, check)?, + Direction::Backward => scan::last(patch, literal, index, begin, limit, check)?, + }; + let Some((id, byte)) = found else { + return Ok(None); + }; + if !ordered.unwrap_or_else(|| index.unified_follows_source()) { + // Interleaved changes: the first record in the spool may not be the first row. + return self.scan_rows(literal, file_id, first..last, range, direction, check); + } + let source = LineId::Patch(id); + let position = Position { + file: file_id, + row: file + .order + .row_for_source(source) + .context("Search hit is outside the frozen source order")?, + byte, + }; + ensure!( + range.contains(&position), + "Search hit lies outside its scan range" + ); + Ok(Some(Hit { + review: self.review, + position, + source, + bytes: byte..byte + literal.len() as u64, + wrapped: false, + })) + } + + /// The first patch record at or after `row`, and the spool offset of `byte` in `row`. + /// Only meaningful for rows that follow record order. + fn spool_bound( + &self, + patch: &mut PatchScan, + file: &SourceFile, + row: usize, + byte: u64, + ) -> Result> { + for candidate in row..file.order.len() { + if let Some(LineId::Patch(id)) = file.order.source(candidate) { + let offset = patch.spans.get(&file.order.file, id)?.0; + let byte = if candidate == row { byte } else { 0 }; + return Ok(Some((id, offset + byte))); + } + } + Ok(None) + } + + /// Reads each source record of `rows` in order. + fn scan_rows( + &self, + literal: &mut Literal<'_>, + file_id: usize, + rows: Range, + range: &Range, + direction: Direction, + check: &impl Fn() -> Result<()>, + ) -> Result> { + let file = &self.files[file_id]; + let mut found = None; + let mut patch = file.order.file.uncached_lines(); + let mut context = file.context.as_ref().map(|source| source.uncached_lines()); + for row in rows { check()?; - let first = if file_id == range.start.file { - range.start.row + let Some(source) = file.order.source(row) else { + continue; + }; + let start = if file_id == range.start.file && row == range.start.row { + range.start.byte } else { 0 }; - let last = if file_id == range.end.file { - range - .end - .row - .saturating_add(usize::from(range.end.byte != 0)) - .min(file.order.len()) + let end = if file_id == range.end.file && row == range.end.row { + range.end.byte } else { - file.order.len() + u64::MAX }; - let mut patch = file.order.file.uncached_lines(); - let mut context = file.context.as_ref().map(|source| source.uncached_lines()); - for row in first..last { - check()?; - let Some(source) = file.order.source(row) else { - continue; - }; - let start = if file_id == range.start.file && row == range.start.row { - range.start.byte - } else { - 0 - }; - let end = if file_id == range.end.file && row == range.end.row { - range.end.byte - } else { - u64::MAX - }; - let input = match source { - LineId::Patch(id) => patch.line(id, start)?, - LineId::Context { new, .. } => context - .as_mut() - .context("Expanded search context has no source")? - .line(new.get(), start)?, - }; - if let Some(bytes) = literal.find(input, start..end, direction, check)? { - found = Some(Hit { - review: self.review, - position: Position { - file: file_id, - row, - byte: bytes.start, - }, - source, - bytes, - wrapped: false, - }); - if direction == Direction::Forward { - return Ok(found); - } + let input = match source { + LineId::Patch(id) => patch.line(id, start)?, + LineId::Context { new, .. } => context + .as_mut() + .context("Expanded search context has no source")? + .line(new.get(), start)?, + }; + if let Some(bytes) = literal.find(input, start..end, direction, check)? { + found = Some(Hit { + review: self.review, + position: Position { + file: file_id, + row, + byte: bytes.start, + }, + source, + bytes, + wrapped: false, + }); + if direction == Direction::Forward { + return Ok(found); } } } diff --git a/src/source_spans.rs b/src/source_spans.rs index 0d79991..975550a 100644 --- a/src/source_spans.rs +++ b/src/source_spans.rs @@ -206,15 +206,27 @@ pub(crate) struct SpanReader<'a> { impl SpanReader<'_> { pub(crate) fn get(&mut self, n: usize) -> Result<(u64, usize)> { + self.source.get_with(&mut self.input, n) + } +} + +impl SourceSpans { + /// The store that holds this index. Files from one input share it. + pub(crate) fn index(&self) -> &Arc { + &self.index + } + + /// Reads one span through caller-owned scratch over [`Self::index`]. + pub(crate) fn get_with(&self, input: &mut ReadWindow, n: usize) -> Result<(u64, usize)> { let mut read = || { - ensure!(n < self.source.count, "Source line is outside the index"); - let width = self.source.encoding.width(); - let start = self.source.start + n as u64 * width as u64; + ensure!(n < self.count, "Source line is outside the index"); + let width = self.encoding.width(); + let start = self.start + n as u64 * width as u64; let mut bytes = [0; 12]; - self.input + input .range(start..start + width as u64)? .read_exact(&mut bytes[..width])?; - self.source.decode(&bytes) + self.decode(&bytes) }; read().context(ReadFailure) } diff --git a/src/storage.rs b/src/storage.rs index a642d07..00b8231 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -19,7 +19,7 @@ mod bytes; pub(crate) use bytes::private_tempfile; pub use bytes::{ByteStore, SourceRef, StoreReader, StoreWriter}; mod reader; -pub(crate) use reader::ReadWindow; +pub(crate) use reader::{PatchScan, ReadWindow, SpanWindow}; #[cfg(test)] pub(crate) mod tests; @@ -74,6 +74,10 @@ impl FileIndex { pub(crate) fn hunk_row(&self, index: usize, split: bool) -> usize { self.projection.hunk_row(index, split) } + /// Whether unified rows list this file's source records in record, and so spool, order. + pub(crate) fn unified_follows_source(&self) -> bool { + self.projection.unified_follows_source() + } pub fn source_end(&self) -> usize { self.source_base + self.source.len() } diff --git a/src/storage/reader.rs b/src/storage/reader.rs index 9258b16..c78f4ca 100644 --- a/src/storage/reader.rs +++ b/src/storage/reader.rs @@ -107,6 +107,116 @@ impl PatchReader<'_> { } } +const SCAN_CHUNK: usize = 1024 * 1024; + +/// Job-local scratch for scanning patch bytes of many files in spool order. +/// Like [`ReadWindow`], reads bypass the shared page cache. +#[derive(Default)] +pub(crate) struct PatchScan { + pub(crate) bytes: SpoolWindow, + pub(crate) spans: SpanWindow, +} + +/// One reusable window of spool bytes. Adjacent files usually share a window. +#[derive(Default)] +pub(crate) struct SpoolWindow { + store: Option>, + buffer: Vec, + start: u64, + len: usize, +} + +/// Reusable scratch for source spans of files that share one index store. +#[derive(Default)] +pub(crate) struct SpanWindow(Option<(Arc, ReadWindow)>); + +impl SpanWindow { + /// The spool offset and length of one patch source record. + pub(crate) fn get(&mut self, file: &FileIndex, id: usize) -> Result<(u64, usize)> { + file.source_id(id)?; + let index = file.source.index(); + let current = self.0.as_ref().is_some_and(|(store, window)| { + Arc::ptr_eq(store, index) && window.bounds.end == index.len() + }); + if !current { + self.0 = Some((index.clone(), ReadWindow::new(index.clone()))); + } + let (_, window) = self.0.as_mut().expect("The span window was just installed"); + file.source.get_with(window, id - file.source_base) + } +} + +impl SpoolWindow { + fn holds(&self, store: &Arc, range: Range) -> bool { + self.store + .as_ref() + .is_some_and(|current| Arc::ptr_eq(current, store)) + && self.start <= range.start + && range.end <= self.start + self.len as u64 + } + + fn fill(&mut self, store: &Arc, start: u64, len: usize) -> Result<()> { + self.len = 0; + if self.buffer.len() < len { + self.buffer = vec![0; SCAN_CHUNK.max(len)]; + } + self.store = Some(store.clone()); + store + .reader(start, len as u64)? + .read_exact(&mut self.buffer[..len])?; + self.start = start; + self.len = len; + Ok(()) + } + + /// Bytes from `position` toward `end`, at least `min` of them unless `end` comes first. + pub(crate) fn after( + &mut self, + store: &Arc, + position: u64, + end: u64, + min: usize, + ) -> Result<&[u8]> { + ensure!( + position <= end && end <= store.len(), + "Invalid source byte range" + ); + let needed = (end - position).min(min as u64); + if !self.holds(store, position..position + needed) { + let len = (store.len() - position).min(SCAN_CHUNK as u64) as usize; + self.fill(store, position, len.max(needed as usize))?; + } + let from = (position - self.start) as usize; + let to = (end.min(self.start + self.len as u64) - self.start) as usize; + Ok(&self.buffer[from..to]) + } + + /// Bytes that end at `end` and begin no earlier than `floor`, with their start offset. + /// At least `min` bytes are returned unless `floor` comes first. + pub(crate) fn before( + &mut self, + store: &Arc, + floor: u64, + end: u64, + min: usize, + ) -> Result<(u64, &[u8])> { + ensure!( + floor <= end && end <= store.len(), + "Invalid source byte range" + ); + let needed = (end - floor).min(min as u64); + if !self.holds(store, end - needed..end) { + let len = end.min(SCAN_CHUNK as u64).max(needed); + self.fill(store, end - len, len as usize)?; + } + let start = floor.max(self.start); + Ok(( + start, + &self.buffer[(start - self.start) as usize..(end - self.start) as usize], + )) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/view/reading.rs b/src/view/reading.rs index 8947b77..1116f53 100644 --- a/src/view/reading.rs +++ b/src/view/reading.rs @@ -112,6 +112,11 @@ impl SourceOrder { self.len } + /// Whether these rows are the file's own unified projection, without revealed context. + pub(crate) fn is_projection(&self) -> bool { + self.segments.is_none() && !self.split + } + pub(crate) fn has_context(&self) -> bool { self.segments.as_ref().is_some_and(|segments| { segments