PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M2: Bound literal text search with prefix matching (#1725)
Sir Clangington III.2048a18e53e3
diff --git a/crates/render/examples/search_bench.rs b/crates/render/examples/search_bench.rsnew file mode 100644index 000000000..f65d959c5--- /dev/null+++ b/crates/render/examples/search_bench.rs@@ -0,0 +1,29 @@+//! Synthetic search microbenchmark, including normalization and glyph-range mapping.+//! Run with `cargo run -p pdfcraft-render --example search_bench --locked` on both revisions+//! with the same toolchain/profile. Timings are diagnostic, never a CI deadline.+use pdfcraft_render::{PageText, TextGlyph};+use std::{hint::black_box, time::Instant};++fn main() {+ for (name, text, query) in [+ ("repeated prefix", "a".repeat(131072), format!("{}b", "a".repeat(4095))),+ ("ordinary", "The quick brown fox jumps over the lazy dog. ".repeat(3000), "brown fox".into()),+ ("unicode", "İSTANBUL κόσμος Straße العربية 日本語 ".repeat(3000), "istanbul".into()),+ ] {+ let glyphs: Vec<_> =+ text.chars().map(|c| TextGlyph { text: c.to_string(), rect: [0.0; 4], quad: [[0.0; 2]; 4], direction: [1.0, 0.0] }).collect();+ let n = glyphs.len();+ let page = PageText { glyphs, line_of: vec![0; n], space_before: vec![false; n] };+ black_box(page.find(&query));+ let mut times = Vec::new();+ for _ in 0..7 {+ let start = Instant::now();+ black_box(page.find(black_box(&query)));+ times.push(start.elapsed().as_secs_f64() * 1000.0);+ }+ times.sort_by(f64::total_cmp);+ if let Some(median) = times.get(3) {+ println!("{name}: median {median:.3} ms (7 runs, {n} glyphs)");+ }+ }+}diff --git a/crates/render/src/text.rs b/crates/render/src/text.rsindex c513d5249..92b6be98e 100644--- a/crates/render/src/text.rs+++ b/crates/render/src/text.rs@@ -16,6 +16,8 @@ use hayro::hayro_interpret::{use kurbo::{Affine, BezPath, Rect, Shape};use std::collections::HashMap;+mod search;+/// One glyph on the page.#[derive(Clone, Debug, PartialEq)]pub struct TextGlyph {@@ -102,47 +104,7 @@ impl PageText {/// Search with Acrobat's find options, returning at most `limit` glyph ranges.pub fn find_opts_limited(&self, needle: &str, case_sensitive: bool, whole_words: bool, limit: usize) -> Vec<std::ops::Range<usize>> {- if limit == 0 {- return Vec::new();- }- let fold = |s: &str| if case_sensitive { s.to_string() } else { fold_case(s) };- let needle: Vec<char> = fold(needle).split_whitespace().collect::<Vec<_>>().join(" ").chars().collect();- if needle.is_empty() {- return Vec::new();- }- // Flatten to chars with the glyph index each char came from.- let mut chars: Vec<(char, usize)> = Vec::new();- for (i, g) in self.glyphs.iter().enumerate() {- if i > 0 && (self.space_before[i] || self.line_of[i] != self.line_of[i - 1]) && chars.last().is_some_and(|c| c.0 != ' ') {- chars.push((' ', i));- }- for c in fold(&g.text).chars() {- let c = if c.is_whitespace() { ' ' } else { c };- // The query collapses a run of whitespace to one space, so collapse the page too.- if c == ' ' && chars.last().is_some_and(|k| k.0 == ' ') {- continue;- }- chars.push((c, i));- }- }- let word = |k: Option<&(char, usize)>| k.is_some_and(|c| c.0.is_alphanumeric());- let mut out = Vec::new();- let mut i = 0;- while i + needle.len() <= chars.len() {- let bounded = !whole_words || (!word(i.checked_sub(1).and_then(|p| chars.get(p))) && !word(chars.get(i + needle.len())));- if bounded && chars[i..i + needle.len()].iter().map(|c| c.0).eq(needle.iter().copied()) {- let start = chars[i].1;- let end = chars[i + needle.len() - 1].1 + 1;- out.push(start..end);- if out.len() == limit {- break;- }- i += needle.len();- } else {- i += 1;- }- }- out+ search::find(self, needle, case_sensitive, whole_words, limit)}/// Glyph ranges of the matches a character matcher finds in the page text (words and linesdiff --git a/crates/render/src/text/search.rs b/crates/render/src/text/search.rsnew file mode 100644index 000000000..c68660dbe--- /dev/null+++ b/crates/render/src/text/search.rs@@ -0,0 +1,77 @@+//! Literal search in normalized page text, retaining the original glyph owners.+use super::{PageText, fold_case};+use std::ops::Range;++pub(super) fn find(page: &PageText, query: &str, sensitive: bool, whole_words: bool, limit: usize) -> Vec<Range<usize>> {+ if limit == 0 {+ return Vec::new();+ }+ let fold = |s: &str| if sensitive { s.to_owned() } else { fold_case(s) };+ let needle: Vec<char> = fold(query).split_whitespace().collect::<Vec<_>>().join(" ").chars().collect();+ if needle.is_empty() {+ return Vec::new();+ }+ let mut chars: Vec<(char, usize)> = Vec::new();+ for (i, glyph) in page.glyphs.iter().enumerate() {+ let line_break = i.checked_sub(1).and_then(|previous| page.line_of.get(previous)).zip(page.line_of.get(i)).is_some_and(|(a, b)| a != b);+ let gap = page.space_before.get(i).copied().unwrap_or(false) || line_break;+ if i > 0 && gap && chars.last().is_some_and(|c| c.0 != ' ') {+ chars.push((' ', i));+ }+ for c in fold(&glyph.text).chars() {+ let c = if c.is_whitespace() { ' ' } else { c };+ if c != ' ' || chars.last().is_none_or(|last| last.0 != ' ') {+ chars.push((c, i));+ }+ }+ }+ if needle.len() > chars.len() {+ return Vec::new();+ }+ // KMP reuses a matched prefix instead of comparing a long query again at every position.+ // The table is bounded by the page's already materialized character count.+ let mut prefix = vec![0; needle.len()];+ let mut matched = 0;+ for (i, &c) in needle.iter().enumerate().skip(1) {+ matched = advance(&needle, &prefix, matched, c);+ if let Some(slot) = prefix.get_mut(i) {+ *slot = matched;+ }+ }+ matched = 0;+ let word = |i: Option<usize>| i.and_then(|i| chars.get(i)).is_some_and(|c| c.0.is_alphanumeric());+ let mut hits = Vec::new();+ for (i, &(c, owner)) in chars.iter().enumerate() {+ matched = advance(&needle, &prefix, matched, c);+ if matched != needle.len() {+ continue;+ }+ let end = i.saturating_add(1);+ let start = end.saturating_sub(needle.len());+ let bounded = !whole_words || (!word(start.checked_sub(1)) && !word(Some(end)));+ if bounded {+ if let Some((_, first)) = chars.get(start)+ && let Some(last) = owner.checked_add(1)+ {+ hits.push(*first..last);+ if hits.len() == limit {+ break;+ }+ }+ // Only accepted hits consume their full span: literal search is non-overlapping.+ matched = 0;+ } else {+ // A word-boundary rejection must still allow an overlapping later candidate.+ matched = prefix.last().copied().unwrap_or_default();+ }+ }+ hits+}++/// Extend a prefix, falling back through strictly shorter proper prefixes on a mismatch.+fn advance(needle: &[char], prefix: &[usize], mut matched: usize, c: char) -> usize {+ while matched > 0 && needle.get(matched) != Some(&c) {+ matched = prefix.get(matched - 1).copied().unwrap_or_default();+ }+ if needle.get(matched) == Some(&c) { matched.saturating_add(1) } else { 0 }+}diff --git a/crates/render/tests/search.rs b/crates/render/tests/search.rsnew file mode 100644index 000000000..44fbe4935--- /dev/null+++ b/crates/render/tests/search.rs@@ -0,0 +1,112 @@+use pdfcraft_render::{PageText, TextGlyph, text::fold_case};+use std::ops::Range;++fn page(parts: &[&str]) -> PageText {+ PageText {+ glyphs: parts.iter().map(|text| TextGlyph { text: (*text).into(), rect: [0.0; 4], quad: [[0.0; 2]; 4], direction: [1.0, 0.0] }).collect(),+ line_of: vec![0; parts.len()],+ space_before: vec![false; parts.len()],+ }+}++// The original straightforward search is an independent oracle for valid page metadata.+fn reference(page: &PageText, query: &str, sensitive: bool, whole: bool, limit: usize) -> Vec<Range<usize>> {+ let fold = |s: &str| if sensitive { s.to_owned() } else { fold_case(s) };+ let needle: Vec<char> = fold(query).split_whitespace().collect::<Vec<_>>().join(" ").chars().collect();+ if needle.is_empty() || limit == 0 {+ return Vec::new();+ }+ let mut chars = Vec::new();+ for (i, glyph) in page.glyphs.iter().enumerate() {+ if i > 0 && (page.space_before[i] || page.line_of[i] != page.line_of[i - 1]) && chars.last().is_some_and(|&(c, _)| c != ' ') {+ chars.push((' ', i));+ }+ for c in fold(&glyph.text).chars() {+ let c = if c.is_whitespace() { ' ' } else { c };+ if c != ' ' || chars.last().is_none_or(|&(last, _)| last != ' ') {+ chars.push((c, i));+ }+ }+ }+ let word = |i: Option<usize>| i.and_then(|i| chars.get(i)).is_some_and(|&(c, _)| c.is_alphanumeric());+ let mut hits = Vec::new();+ let mut start = 0;+ while start + needle.len() <= chars.len() {+ let end = start + needle.len();+ if (!whole || (!word(start.checked_sub(1)) && !word(Some(end)))) && chars[start..end].iter().map(|&(c, _)| c).eq(needle.iter().copied()) {+ hits.push(chars[start].1..chars[end - 1].1 + 1);+ if hits.len() == limit {+ break;+ }+ start = end;+ } else {+ start += 1;+ }+ }+ hits+}++#[test]+fn search_tolerates_missing_layout_metadata() {+ let mut text = page(&["a", "b", "c"]);+ text.line_of.clear();+ text.space_before.clear();+ assert_eq!(text.find("abc"), vec![0..3]);+ text.space_before = vec![false, true];+ assert_eq!(text.find("a bc"), vec![0..3]);+ text.line_of = vec![0, 1];+ assert_eq!(text.find("a bc"), vec![0..3]);+}++#[test]+fn whole_word_rejection_keeps_overlapping_candidates() {+ let text = page(&["xaa-aa-aa"]);+ assert_eq!(text.find_opts("aa-aa", true, true), vec![0..1]);+ // Accepted matches still do not overlap, even within one multi-character glyph.+ assert_eq!(page(&["aaaaa"]).find("aaa"), vec![0..1]);+ assert_eq!(page(&["aaaaa"]).find("aa"), vec![0..1, 0..1]);+}++#[test]+fn search_matches_reference_for_unicode_gaps_limits_and_word_boundaries() {+ let alphabet = ["a", "b", " ", "-", "İ", "ı", "ς", "Σ", "\t", "\n", "ffi", "", "界", "e\u{301}", "العربية"];+ let mut seed = 1234567u64;+ let mut next = || {+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);+ (seed >> 32) as usize+ };+ for case in 0..2000 {+ let parts: Vec<_> = (0..10 + case % 70).map(|_| alphabet[next() % alphabet.len()]).collect();+ let query = if case % 2 == 0 {+ parts.iter().skip(case % 8).take(1 + case % 9).copied().collect::<String>()+ } else {+ (0..1 + case % 9).map(|_| alphabet[next() % alphabet.len()]).collect::<String>()+ };+ let mut text = page(&parts);+ for i in 1..parts.len() {+ text.space_before[i] = next() % 11 == 0;+ text.line_of[i] = text.line_of[i - 1] + u32::from(next() % 17 == 0);+ }+ for sensitive in [false, true] {+ for whole in [false, true] {+ for limit in [0, 1, 2, usize::MAX] {+ assert_eq!(+ text.find_opts_limited(&query, sensitive, whole, limit),+ reference(&text, &query, sensitive, whole, limit),+ "case {case}: {query:?}, sensitive={sensitive}, whole={whole}, limit={limit}"+ );+ }+ }+ }+ }+}++#[test]+fn long_repeated_prefix_search_preserves_the_last_match_and_limit() {+ let mut parts = vec!["a"; 131072];+ parts.push("b");+ let text = page(&parts);+ let query = format!("{}b", "a".repeat(4095));+ assert_eq!(text.find_opts_limited(&query, false, false, 1), vec![126977..131073]);+ assert!(text.find(&format!("{}c", "a".repeat(4095))).is_empty());+}