From 1e61b3b270c8d6545b9ccc2e736f47e01246da70 Mon Sep 17 00:00:00 2001 From: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:47:56 +0200 Subject: [PATCH] perf(search): search large files in context mode and non-UTF-8 encodings without reading them whole (#5254) Project search read a non-UTF-8 file whole and decoded it as one String, and in the comments/strings modes read every file whole to find its comments, even ones far above what the parser takes. Non-UTF-8 files now stream through an incremental decoder (ide_vfs::decode_stream: a detection pass with the same result as decode_text, then 64 KiB chunks), and files too large for the parser are not read for comments at all. Results, binary detection, the match limit and cancellation are unchanged. Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> --- crates/ide-host/src/ops/search.rs | 9 +- crates/ide-search/src/engine.rs | 89 ++++-- crates/ide-search/src/lib.rs | 20 +- crates/ide-search/tests/bounded_memory.rs | 159 ++++++++++ crates/ide-search/tests/search.rs | 3 +- crates/ide-search/tests/streaming.rs | 200 ++++++++++++ crates/ide-vfs/src/decode_stream.rs | 366 ++++++++++++++++++++++ crates/ide-vfs/src/encoding.rs | 2 +- crates/ide-vfs/src/lib.rs | 2 + 9 files changed, 818 insertions(+), 32 deletions(-) create mode 100644 crates/ide-search/tests/bounded_memory.rs create mode 100644 crates/ide-search/tests/streaming.rs create mode 100644 crates/ide-vfs/src/decode_stream.rs diff --git a/crates/ide-host/src/ops/search.rs b/crates/ide-host/src/ops/search.rs index c340b19d2..db9d93368 100644 --- a/crates/ide-host/src/ops/search.rs +++ b/crates/ide-host/src/ops/search.rs @@ -111,7 +111,7 @@ pub(crate) fn search_project( }; let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text); let defaults = project.documents.file_defaults(); - let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path)); + let fallback = |path: &Path| defaults.fallback_for(path).map(str::to_owned); let mut total = SearchSummary::default(); for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) { let mut remaining = query.clone(); @@ -139,7 +139,7 @@ pub(crate) fn search_project( &remaining, Some(&filter), Some(&literals), - ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), decode: &decode }, + ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), fallback: &fallback }, cancel, &|mut file| { if let Some(prefix) = &prefix { @@ -188,6 +188,11 @@ pub(crate) fn rebase_masks(masks: &[String], prefix: &str) -> Vec { #[cfg(test)] mod tests { + #[test] + fn search_leaves_unread_the_texts_the_parser_does_not_take() { + assert_eq!(ide_search::MAX_LITERALS_TEXT_BYTES, ide_language::MAX_PARSE_BYTES); + } + #[test] fn masks_follow_the_root_they_search() { let masks = vec![".wt/a/src/**, src/**".into(), "*.rs".into(), "!.wt/a/out/**".into(), "**/build/**".into()]; diff --git a/crates/ide-search/src/engine.rs b/crates/ide-search/src/engine.rs index 948a46e11..70b6b2d83 100644 --- a/crates/ide-search/src/engine.rs +++ b/crates/ide-search/src/engine.rs @@ -24,6 +24,11 @@ const CANCEL_CHECK_LINES: u32 = 256; /// How many matches a file keeps before claiming them from the shared budget: each file /// searched in parallel holds about this many unclaimed matches at most, not up to the whole budget. const CLAIM_BATCH: u32 = 64; +/// Bytes at the start of a text that the searcher checks for binary content up front. +const BINARY_HEAD_LEN: usize = 64 * 1024; +/// Files longer than this hold no text the parser takes, whatever their encoding (UTF-16 halves +/// the bytes of ASCII text, nothing else comes close): their comments and strings are not looked for. +const MAX_LITERALS_FILE_BYTES: u64 = 2 * crate::MAX_LITERALS_TEXT_BYTES as u64; pub(crate) struct Request<'a> { pub root: &'a Path, @@ -63,9 +68,11 @@ impl Control<'_> { /// Also polls the cancellation token (which takes a lock). fn should_stop(&self) -> bool { - if self.stopped() { - return true; - } + self.stopped() || self.cancel_requested() + } + + /// Polls the cancellation token only: a search stopped by its match limit is not cancelled. + fn cancel_requested(&self) -> bool { if self.cancel.is_cancelled() { self.cancelled.store(true, Relaxed); self.stop.store(true, Relaxed); @@ -302,22 +309,37 @@ impl Ctx<'_> { { return; } - // The search context needs the whole text to find comments and string literals. + // The search context needs the whole text to find comments and string literals. A file + // whose text is past the longest the parser takes has none, so it is not read for them. let in_context = match self.literals { - Some(literals) => { + Some(literals) => 'context: { let text = match (self.text.overlay)(path) { Some(text) => text, - None => match std::fs::read(path) { - Ok(bytes) => match String::from_utf8(bytes) { - Ok(text) => text, - // Binary content has nothing to classify. - Err(e) => match (self.text.decode)(path, e.as_bytes()) { - Some(text) => text, - None => return, + None => { + match std::fs::metadata(path) { + Ok(meta) if meta.len() > MAX_LITERALS_FILE_BYTES => { + if self.context.needs_literals() { + return; + } + break 'context None; + } + Ok(_) => {} + Err(_) => return, + } + match std::fs::read(path) { + Ok(bytes) => match String::from_utf8(bytes) { + Ok(text) => text, + // Binary content has nothing to classify. + Err(e) => { + match ide_vfs::decode_text(e.as_bytes(), (self.text.fallback)(path).as_deref()) { + Some(text) => text, + None => return, + } + } }, - }, - Err(_) => return, - }, + Err(_) => return, + } + } }; let ranges = literals(path, &text); if ranges.is_none() && self.context.needs_literals() { @@ -354,7 +376,8 @@ impl Ctx<'_> { } /// Streams the file's bytes; a file that turns out not to be UTF-8 (GBK, - /// UTF-16 …) is searched again in the text `decode` gives it. + /// UTF-16 …) is searched again in its text decoded as the editor opens it, + /// which is decoded as it is read. fn search_disk<'s>( &'s self, path: &Path, @@ -362,7 +385,7 @@ impl Ctx<'_> { searcher: &mut Searcher, sink: &mut FileSink<'s>, ) -> io::Result<()> { - let mut reader = Utf8Probe::new(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl }); + let mut reader = Utf8Probe::new(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl, hard: true }); let result = searcher.search_reader(matcher, &mut reader, &mut *sink); // NUL bytes in the head of UTF-16 text stop the byte search; later ones mark binary. let decode = if sink.binary { @@ -374,14 +397,29 @@ impl Ctx<'_> { if !decode || (self.ctl.stopped() && sink.claimed == 0) { return result; } - let Some(text) = (self.text.decode)(path, &std::fs::read(path)?) else { + // Only cancellation ends the reading: a search that hit the match limit still fills its claim. + let open = || Ok(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl, hard: false }); + let Some(text) = ide_vfs::decode_stream(open, (self.text.fallback)(path).as_deref())? else { sink.binary = true; return Ok(()); }; + let mut text = text; + // Text held whole gets the searcher's binary check only on its first 64 KiB and on the + // lines that match; this keeps that for the text read piece by piece. + let mut head = Vec::with_capacity(BINARY_HEAD_LEN); + (&mut text).take(BINARY_HEAD_LEN as u64).read_to_end(&mut head)?; + if head.contains(&0) { + sink.binary = true; + return Ok(()); + } let claimed = sink.claimed; *sink = FileSink::new(matcher, &self.ctl, None); sink.claimed = claimed; - searcher.search_slice(matcher, text.as_bytes(), sink) + sink.binary_in_matches = true; + searcher.set_binary_detection(BinaryDetection::none()); + let result = searcher.search_reader(matcher, io::Cursor::new(head).chain(text), sink); + searcher.set_binary_detection(BinaryDetection::quit(0)); + result } } @@ -404,6 +442,8 @@ struct FileSink<'a> { /// file is searched again under the claim of its byte search. claimed: u32, binary: bool, + /// A NUL byte in a matching line marks the file binary (the searcher's own check is off). + binary_in_matches: bool, ticks: u32, /// Scratch buffers reused across lines. found: Vec<(usize, usize)>, @@ -425,6 +465,7 @@ impl<'a> FileSink<'a> { count: 0, claimed: 0, binary: false, + binary_in_matches: false, ticks: 0, found: Vec::new(), ranges: Vec::new(), @@ -467,6 +508,10 @@ impl Sink for FileSink<'_> { type Error = io::Error; fn matched(&mut self, _searcher: &Searcher, m: &SinkMatch<'_>) -> Result { + if self.binary_in_matches && memchr::memchr(0, m.bytes()).is_some() { + self.binary = true; + return Ok(false); + } self.ticks += 1; let stop = self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop()); // Unless cancelled, a decoded file still fills the claim its byte search took. @@ -534,15 +579,17 @@ impl Sink for FileSink<'_> { } } -/// Aborts disk reads once the search is stopped or cancelled. +/// Aborts disk reads once the search is cancelled, or with `hard` once it is stopped. struct StopReader<'a, R> { inner: R, ctl: &'a Control<'a>, + hard: bool, } impl Read for StopReader<'_, R> { fn read(&mut self, buf: &mut [u8]) -> io::Result { - if self.ctl.should_stop() { + let stop = if self.hard { self.ctl.should_stop() } else { self.ctl.cancel_requested() }; + if stop { return Err(io::Error::other("search stopped")); } self.inner.read(buf) diff --git a/crates/ide-search/src/lib.rs b/crates/ide-search/src/lib.rs index b00939400..4e126fcb6 100644 --- a/crates/ide-search/src/lib.rs +++ b/crates/ide-search/src/lib.rs @@ -112,8 +112,14 @@ impl SearchContext { } } +/// The longest file text, in bytes, that is searched for comments and string literals: the +/// parser's limit (`ide_language::MAX_PARSE_BYTES`), above which a [`Literals`] finds none. +/// The search leaves a longer text unread by it. +pub const MAX_LITERALS_TEXT_BYTES: usize = 16 * 1024 * 1024; + /// Comments and string literals of a file's text (sorted, non-overlapping), -/// or `None` when its language has no syntax tree. +/// or `None` when its language has no syntax tree or the text is longer than +/// [`MAX_LITERALS_TEXT_BYTES`]. pub type Literals<'a> = &'a (dyn Fn(&Path, &str) -> Option> + Sync); #[derive(Clone, Debug, Serialize, Deserialize, Type)] @@ -198,21 +204,23 @@ pub struct SearchSummary { /// Text of unsaved open documents takes precedence over disk content. pub type Overlay<'a> = &'a (dyn Fn(&Path) -> Option + Sync); -/// Text of a file whose bytes are not UTF-8 (GBK, UTF-16 …); `None` for binary content. -pub type Decode<'a> = &'a (dyn Fn(&Path, &[u8]) -> Option + Sync); +/// The encoding to read a file with when it is not UTF-8 and the encoding detected for it is not +/// trusted to be right (GBK, UTF-16 …): its label, or `None` to go by what is detected. +pub type FallbackEncoding<'a> = &'a (dyn Fn(&Path) -> Option + Sync); /// Where a search reads file text from: the open document when `overlay` has -/// it, else the file on disk, decoded by `decode` when it is not UTF-8. +/// it, else the file on disk, decoded as the editor opens it when it is not UTF-8 +/// (`fallback` picks the encoding that [`ide_vfs::decode_text`] takes). #[derive(Clone, Copy)] pub struct TextSource<'a> { pub overlay: Overlay<'a>, - pub decode: Decode<'a>, + pub fallback: FallbackEncoding<'a>, } impl<'a> TextSource<'a> { /// Non-UTF-8 files decode as detected, without a configured fallback encoding. pub fn detected(overlay: Overlay<'a>) -> Self { - Self { overlay, decode: &|_, bytes| ide_vfs::decode_text(bytes, None) } + Self { overlay, fallback: &|_| None } } } diff --git a/crates/ide-search/tests/bounded_memory.rs b/crates/ide-search/tests/bounded_memory.rs new file mode 100644 index 000000000..239aca419 --- /dev/null +++ b/crates/ide-search/tests/bounded_memory.rs @@ -0,0 +1,159 @@ +//! Searching a big file holds a bounded amount of it in memory, whatever its encoding and the +//! search context. Allocations of the whole process are counted, so this is one test with +//! sequential scenarios. + +use ide_core::CancellationToken; +use ide_search::{ + FileMatches, Literals, SearchContext, SearchQuery, SearchScope, SearchSummary, TextSource, search_in_context, +}; +use std::alloc::{GlobalAlloc, Layout, System}; +use std::path::Path; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + +struct Counting; + +static LIVE: AtomicUsize = AtomicUsize::new(0); +static PEAK: AtomicUsize = AtomicUsize::new(0); + +fn grow(by: usize) { + let live = LIVE.fetch_add(by, Relaxed) + by; + PEAK.fetch_max(live, Relaxed); +} + +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + grow(layout.size()); + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + grow(layout.size()); + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + LIVE.fetch_sub(layout.size(), Relaxed); + unsafe { System.dealloc(ptr, layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + if new_size >= layout.size() { + grow(new_size - layout.size()); + } else { + LIVE.fetch_sub(layout.size() - new_size, Relaxed); + } + unsafe { System.realloc(ptr, layout, new_size) } + } +} + +#[global_allocator] +static ALLOC: Counting = Counting; + +const MIB: usize = 1024 * 1024; +/// What a search may hold at once: a few buffers of the reader and the decoder. The files are +/// 16 to 40 MiB, so a search that reads one whole (or decodes it whole) is far over. +const BOUND: usize = 4 * MIB; + +fn query(context: SearchContext) -> SearchQuery { + SearchQuery { + pattern: "needle".into(), + is_regex: false, + case_sensitive: true, + whole_word: false, + include: vec![], + exclude: vec![], + scope: SearchScope::Project, + max_matches: 1_000_000, + context, + include_excluded: false, + } +} + +/// Runs a search and returns its result with the most memory it held over what was live before. +fn measured( + root: &Path, + context: SearchContext, + literals: Option>, +) -> (Vec, SearchSummary, usize) { + let out = Mutex::new(Vec::new()); + let before = LIVE.load(Relaxed); + PEAK.store(before, Relaxed); + let summary = search_in_context( + root, + &query(context), + None, + literals, + TextSource::detected(&|_| None), + &CancellationToken::new(), + &|f| out.lock().unwrap().push(f), + ) + .unwrap(); + let held = PEAK.load(Relaxed).saturating_sub(before); + // The results are in `out` and count against the search; they are small. + (out.into_inner().unwrap(), summary, held) +} + +fn write_repeated(path: &Path, bom: &[u8], block: &[u8], size: usize) { + use std::io::Write; + let mut file = std::io::BufWriter::new(std::fs::File::create(path).unwrap()); + file.write_all(bom).unwrap(); + for _ in 0..size / block.len() + 1 { + file.write_all(block).unwrap(); + } +} + +fn utf16le(text: &str) -> Vec { + text.encode_utf16().flat_map(u16::to_le_bytes).collect() +} + +#[test] +fn searching_a_big_file_holds_a_bounded_part_of_it() { + let block = "2026-11-22 13:00:01 INFO caf\u{e9} \u{4e2d}\u{6587} request ok\n".repeat(50) + + "2026-11-22 13:00:02 ERROR needle marker found\n"; + let latin_text = block.replace(['\u{4e2d}', '\u{6587}'], "x"); + let (latin1, _, _) = encoding_rs::WINDOWS_1252.encode(&latin_text); + let (gbk, _, _) = encoding_rs::GBK.encode(&block); + let parsed = Mutex::new(Vec::new()); + let literals = |path: &Path, _: &str| { + parsed.lock().unwrap().push(path.file_name().unwrap().to_string_lossy().into_owned()); + None + }; + + let dir = tempfile::tempdir().unwrap(); + let mut expected = Vec::new(); + for (name, bom, bytes, size) in [ + ("latin1.log", &b""[..], &latin1[..], 16 * MIB), + ("gbk.log", &b""[..], &gbk[..], 16 * MIB), + ("utf16.log", &[0xFF, 0xFE][..], &utf16le(&block)[..], 24 * MIB), + ("utf8.log", &b""[..], block.as_bytes(), 40 * MIB), + ] { + let one = tempfile::tempdir_in(dir.path()).unwrap(); + write_repeated(&one.path().join(name), bom, bytes, size); + // Plain search: the byte search, then the decoded search of a non-UTF-8 file. + let (files, summary, held) = measured(one.path(), SearchContext::Any, None); + assert_eq!(files.len(), 1, "{name}"); + assert!(summary.matches > 100, "{name}"); + assert!(held < BOUND, "{name}: plain search held {} MiB", held / MIB); + expected.push((name, summary.matches, one)); + } + + // Searching with a context reads a file whole only to find its comments and strings, and + // past the parser's limit it has none: the file is searched as it is read. + for (name, matches, one) in &expected { + for context in [SearchContext::ExceptComments, SearchContext::ExceptCommentsAndStringLiterals] { + let (files, summary, held) = measured(one.path(), context, Some(&literals)); + if *name == "utf8.log" { + assert_eq!(summary.matches, *matches, "{name} {context:?}"); + assert_eq!(files.len(), 1); + assert!(held < BOUND, "{name}: {context:?} held {} MiB", held / MIB); + } + } + } + let (_, only_in, held) = measured(expected[3].2.path(), SearchContext::InComments, Some(&literals)); + assert_eq!(only_in.matches, 0, "a file without comments has no match in them"); + assert!(held < BOUND, "held {} MiB", held / MIB); + let parsed = parsed.into_inner().unwrap(); + assert!(parsed.iter().any(|name| name == "gbk.log"), "files within the limit are still analysed"); + assert!(!parsed.iter().any(|name| name == "utf8.log"), "a 40 MiB text is never handed to the parser"); +} diff --git a/crates/ide-search/tests/search.rs b/crates/ide-search/tests/search.rs index 2631642c6..0d7c046d3 100644 --- a/crates/ide-search/tests/search.rs +++ b/crates/ide-search/tests/search.rs @@ -890,8 +890,7 @@ fn non_utf8_files_use_the_given_decoder() { // Text too short to detect reliably decodes with the configured encoding. let p = project(&[("a.txt", &gbk("中文\n"))]); let out = Mutex::new(Vec::new()); - let decode = |_: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, Some("gbk")); - let source = TextSource { overlay: &|_| None, decode: &decode }; + let source = TextSource { overlay: &|_| None, fallback: &|_| Some("gbk".into()) }; ide_search::search_in_context(p.path(), &query("中文"), None, None, source, &CancellationToken::new(), &|f| { out.lock().unwrap().push(f) }) diff --git a/crates/ide-search/tests/streaming.rs b/crates/ide-search/tests/streaming.rs new file mode 100644 index 000000000..295e4873a --- /dev/null +++ b/crates/ide-search/tests/streaming.rs @@ -0,0 +1,200 @@ +//! Files that are not UTF-8 are decoded while they are searched. Searching the text decoded whole +//! (what an unsaved editor buffer of the file is) is the reference: the matches must be the same. + +use ide_core::CancellationToken; +use ide_search::{FileMatches, SearchQuery, SearchScope, SearchSummary, TextSource, search_in_context}; +use std::path::Path; +use std::sync::Mutex; + +fn query(pattern: &str, is_regex: bool) -> SearchQuery { + SearchQuery { + pattern: pattern.into(), + is_regex, + case_sensitive: false, + whole_word: false, + include: vec![], + exclude: vec![], + scope: SearchScope::Project, + max_matches: 1_000_000, + context: Default::default(), + include_excluded: false, + } +} + +fn run(root: &Path, q: &SearchQuery, source: TextSource<'_>) -> (Vec, SearchSummary) { + let out = Mutex::new(Vec::new()); + let summary = + search_in_context(root, q, None, None, source, &CancellationToken::new(), &|f| out.lock().unwrap().push(f)) + .unwrap(); + let mut files = out.into_inner().unwrap(); + files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path)); + (files, summary) +} + +/// The matches of every file in `root`, read from disk and from its whole decoded text. +fn both_ways(root: &Path, q: &SearchQuery, fallback: Option<&str>) -> (String, String) { + let streamed = run(root, q, TextSource { overlay: &|_| None, fallback: &|_| fallback.map(str::to_owned) }); + let whole = run( + root, + q, + TextSource { + overlay: &|path| ide_vfs::decode_text(&std::fs::read(path).unwrap(), fallback), + fallback: &|_| None, + }, + ); + let show = |(files, summary): (Vec, SearchSummary)| { + format!("{:#?}\nmatches {} limit {}", files, summary.matches, summary.limit_hit) + }; + (show(streamed), show(whole)) +} + +fn first_difference(a: &str, b: &str) -> String { + let (a, b): (Vec<_>, Vec<_>) = (a.lines().collect(), b.lines().collect()); + let at = a.iter().zip(&b).take_while(|(x, y)| x == y).count(); + format!( + "line {at}:\nstreamed {:?}\nwhole {:?}", + &a[at.saturating_sub(3)..a.len().min(at + 3)], + &b[at.saturating_sub(3)..b.len().min(at + 3)] + ) +} + +fn utf16(text: &str, bom: bool, big: bool) -> Vec { + let mut bytes = if bom { vec![if big { 0xFE } else { 0xFF }, if big { 0xFF } else { 0xFE }] } else { Vec::new() }; + for unit in text.encode_utf16() { + bytes.extend(if big { unit.to_be_bytes() } else { unit.to_le_bytes() }); + } + bytes +} + +/// Lines of mixed width: ASCII, accents, CJK, astral characters (surrogate pairs), CRLF. +fn lines(count: usize) -> String { + let mut text = String::new(); + for i in 0..count { + match i % 6 { + 0 => text.push_str(&format!("{i} needle in plain ascii\n")), + 1 => text.push_str(&format!("{i} caf\u{e9} needle cr\u{e8}me\n")), + 2 => text.push_str(&format!("{i} \u{4e2d}\u{6587} needle \u{6d4b}\u{8bd5}\n")), + 3 => text.push_str(&format!("{i} \u{1f600} needle \u{1f4a9}\n")), + 4 => text.push_str(&format!("{i} crlf needle\r\n")), + _ => text.push_str(&format!("{i} nothing here\n")), + } + } + text +} + +fn write(dir: &Path, name: &str, bytes: &[u8]) { + std::fs::write(dir.join(name), bytes).unwrap(); +} + +#[test] +fn decoded_files_give_the_matches_of_their_whole_text() { + let wide = lines(12_000); + let gbk_text = wide.replace(['\u{1f600}', '\u{1f4a9}', '\u{e9}', '\u{e8}'], ""); + let latin_text = wide.replace(|c: char| c as u32 > 0xff, ""); + let dir = tempfile::tempdir().unwrap(); + // (BOM-less UTF-16 is not searched in decoded text, and not covered here: only the byte search sees it.) + // Each file is well past the sizes the decoder reads at a time (64 KiB). + assert!(wide.len() > 250_000); + write(dir.path(), "utf16le_bom.txt", &utf16(&wide, true, false)); + write(dir.path(), "utf16be_bom.txt", &utf16(&wide, true, true)); + write(dir.path(), "gbk.txt", &encoding_rs::GBK.encode(&gbk_text).0); + write(dir.path(), "latin1.txt", &encoding_rs::WINDOWS_1252.encode(&latin_text).0); + write(dir.path(), "utf8.txt", wide.as_bytes()); + + let queries = [ + query("needle", false), + query("caf\u{e9}", false), + query("\u{1f600}", false), + query("\u{4e2d}\u{6587} needle", false), + query(r"\d+ \S+ needle", true), + query(r"needle\r?$", true), + // A multi-line pattern reads the whole text, however it arrives. + query("needle in plain ascii\n1 caf", false), + SearchQuery { case_sensitive: true, whole_word: true, ..query("needle", false) }, + ]; + for q in &queries { + for fallback in [None, Some("gbk"), Some("windows-1252")] { + let (streamed, whole) = both_ways(dir.path(), q, fallback); + assert!( + streamed == whole, + "{:?} fallback {fallback:?}\n{}", + q.pattern, + first_difference(&streamed, &whole) + ); + assert!(streamed.len() > 100, "{:?} found nothing", q.pattern); + } + } + // The match limit keeps the first matches of a file, and files take their share in any order: + // one file at a time. + for name in ["utf16le_bom.txt", "utf16be_bom.txt", "gbk.txt", "latin1.txt"] { + for max_matches in [7, 64, 65, 5_000] { + let q = SearchQuery { max_matches, include: vec![name.into()], ..query("needle", false) }; + let (streamed, whole) = both_ways(dir.path(), &q, None); + assert!(streamed == whole, "{name} limit {max_matches}\n{}", first_difference(&streamed, &whole)); + assert!(streamed.contains(&format!("matches {max_matches} limit true")), "{name} {max_matches}"); + } + } +} + +#[test] +fn decoded_files_keep_their_multibyte_characters_across_every_read_boundary() { + // A character sits on each of the 64 KiB read boundaries, at all alignments. + let dir = tempfile::tempdir().unwrap(); + for pad in 0..8usize { + let mut gbk = "x".repeat(64 * 1024 - 5 + pad); + let mut utf16_text = gbk.clone(); + for i in 0..40 { + gbk.push_str("\u{4e2d}\u{6587}"); + utf16_text.push_str(if i % 2 == 0 { "\u{1f600}" } else { "\u{4e2d}" }); + gbk.push_str(&"y".repeat(i % 3)); + utf16_text.push_str(&"y".repeat(i % 3)); + } + gbk.push_str("yy needle\n"); + utf16_text.push_str("yy needle\n"); + write(dir.path(), &format!("gbk{pad}.txt"), &encoding_rs::GBK.encode(&gbk).0); + write(dir.path(), &format!("utf16_{pad}.txt"), &utf16(&utf16_text, true, pad % 2 == 0)); + write( + dir.path(), + &format!("latin{pad}.txt"), + &[gbk.as_bytes()[..64 * 1024 - 7 + pad].to_vec(), b"\xe9\xe8 needle\n".to_vec()].concat(), + ); + } + for pattern in ["needle", "y+ needle", "\u{4e2d}\u{6587}"] { + let q = query(pattern, pattern.contains('+')); + let (streamed, whole) = both_ways(dir.path(), &q, None); + assert!(streamed == whole, "{pattern}\n{}", first_difference(&streamed, &whole)); + assert!(streamed.len() > 100, "{pattern} found nothing"); + } +} + +#[test] +fn nul_characters_in_decoded_text_mark_it_binary_as_in_the_whole_text() { + // Text held whole is binary when a NUL is in its first 64 KiB or in a line that matches, + // which is not the same as a NUL anywhere. + let text = lines(20_000); + let with_nul = |at: &str| text.replacen(at, &format!("\0{at}"), 1); + let cases = [ + ("early", with_nul("5 nothing here"), false), + ("late in a line that does not match", with_nul("19997 nothing here"), true), + ("late in a line that matches", with_nul("19998 needle"), false), + ]; + for (name, text, found) in cases { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "a.txt", &utf16(&text, true, false)); + let (streamed, whole) = both_ways(dir.path(), &query("needle", false), None); + assert!(streamed == whole, "{name}\n{}", first_difference(&streamed, &whole)); + assert_eq!(streamed.contains("a.txt"), found, "{name}"); + } +} + +#[test] +fn a_file_is_decoded_when_its_search_reaches_the_byte_that_is_not_utf8() { + // Valid UTF-8 up to the last line: the whole file is read as the detected Windows-1252. + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "late.txt", &[lines(1500).as_bytes(), b"caf\xe9 needle\n"].concat()); + for q in [query("needle", false), query("caf", false)] { + let (streamed, whole) = both_ways(dir.path(), &q, None); + assert!(streamed == whole, "{}", first_difference(&streamed, &whole)); + assert!(streamed.contains("café"), "decoded as Windows-1252"); + } +} diff --git a/crates/ide-vfs/src/decode_stream.rs b/crates/ide-vfs/src/decode_stream.rs new file mode 100644 index 000000000..fe4f93137 --- /dev/null +++ b/crates/ide-vfs/src/decode_stream.rs @@ -0,0 +1,366 @@ +//! [`decode_text`](crate::decode_text) for files too large to hold: the same +//! decisions, taken while reading a chunk at a time. + +use crate::encoding::{SNIFF_LEN, sniff_utf16}; +use encoding_rs::{Decoder, Encoding, UTF_8, UTF_16BE, UTF_16LE}; +use std::io::{self, Read}; + +/// Raw bytes read per step; a step holds this plus its UTF-8 expansion (at most 3x). +const CHUNK: usize = 64 * 1024; + +/// The text of a file as UTF-8 bytes, decoded as it is read. +pub struct DecodedReader { + reader: R, + decoder: Decoder, + raw: Vec, + /// Decoded bytes of the last step; `out[pos..len]` is unread. + out: Vec, + pos: usize, + len: usize, + done: bool, +} + +/// Decodes the file `open` reads like [`decode_text`](crate::decode_text) does (BOM, UTF-8 and +/// UTF-16 as detected, other text as `fallback` or else the detected encoding) without holding +/// it: `None` for binary content, else a reader of the text as UTF-8. +/// +/// Deciding the encoding of text that is neither BOM-marked nor UTF-8 needs a pass over the whole +/// file before the decoding pass, so `open` gives a fresh reader of the file up to twice. +pub fn decode_stream( + open: impl FnMut() -> io::Result, + fallback: Option<&str>, +) -> io::Result>> { + decode_stream_in(open, fallback, CHUNK) +} + +fn decode_stream_in( + mut open: impl FnMut() -> io::Result, + fallback: Option<&str>, + chunk: usize, +) -> io::Result>> { + let Some((detected, bom_len, has_bom)) = detect(&mut open, chunk)? else { return Ok(None) }; + let fallback = fallback.and_then(|label| Encoding::for_label(label.trim().as_bytes())); + let encoding = match fallback { + Some(enc) + if !has_bom && enc != detected && detected != UTF_8 && detected != UTF_16LE && detected != UTF_16BE => + { + enc + } + _ => detected, + }; + let mut reader = open()?; + io::copy(&mut (&mut reader).take(bom_len as u64), &mut io::sink())?; + let decoder = encoding.new_decoder_without_bom_handling(); + let out = vec![0; decoder.max_utf8_buffer_length(chunk).unwrap_or(chunk * 3)]; + Ok(Some(DecodedReader { reader, decoder, raw: vec![0; chunk], out, pos: 0, len: 0, done: false })) +} + +/// The encoding [`decode`](crate::encoding::decode) finds for the file, its BOM length and +/// whether it has a BOM; `None` for binary content. +fn detect( + open: &mut impl FnMut() -> io::Result, + chunk: usize, +) -> io::Result> { + let mut reader = open()?; + let mut head = vec![0; SNIFF_LEN]; + let n = read_full(&mut reader, &mut head)?; + head.truncate(n); + if let Some((enc, bom_len)) = Encoding::for_bom(&head) { + return Ok(Some((enc, bom_len, true))); + } + if head.contains(&0) { + return Ok(sniff_utf16(&head).map(|enc| (enc, 0, false))); + } + let mut detector = chardetng::EncodingDetector::new(); + let mut utf8 = Utf8Check::default(); + detector.feed(&head, false); + utf8.feed(&head); + if n == SNIFF_LEN { + let mut buf = vec![0; chunk]; + loop { + let n = read_retry(&mut reader, &mut buf)?; + if n == 0 { + break; + } + detector.feed(&buf[..n], false); + utf8.feed(&buf[..n]); + } + } + detector.feed(&[], true); + let encoding = if utf8.is_valid() { UTF_8 } else { detector.guess(None, true) }; + Ok(Some((encoding, 0, false))) +} + +/// Reads until `buf` is full or the reader ends. +fn read_full(reader: &mut impl Read, buf: &mut [u8]) -> io::Result { + let mut filled = 0; + while filled < buf.len() { + match read_retry(reader, &mut buf[filled..])? { + 0 => break, + n => filled += n, + } + } + Ok(filled) +} + +fn read_retry(reader: &mut impl Read, buf: &mut [u8]) -> io::Result { + loop { + match reader.read(buf) { + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + result => return result, + } + } +} + +/// Checks that bytes fed in pieces form valid UTF-8, as `std::str::from_utf8` does for the whole. +#[derive(Default)] +struct Utf8Check { + /// The start of a character cut by the end of the previous piece. + tail: Vec, + invalid: bool, +} + +impl Utf8Check { + fn feed(&mut self, mut bytes: &[u8]) { + if self.invalid { + return; + } + while !self.tail.is_empty() && !bytes.is_empty() { + self.tail.push(bytes[0]); + bytes = &bytes[1..]; + match std::str::from_utf8(&self.tail) { + Ok(_) => self.tail.clear(), + Err(e) if e.error_len().is_none() => {} + Err(_) => { + self.invalid = true; + return; + } + } + } + if !self.tail.is_empty() { + return; + } + match std::str::from_utf8(bytes) { + Ok(_) => {} + Err(e) if e.error_len().is_none() => self.tail.extend_from_slice(&bytes[e.valid_up_to()..]), + Err(_) => self.invalid = true, + } + } + + /// Whether everything fed so far was UTF-8 (a truncated final character is not). + fn is_valid(&self) -> bool { + !self.invalid && self.tail.is_empty() + } +} + +impl Read for DecodedReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + while self.pos == self.len { + if self.done { + return Ok(0); + } + let n = read_retry(&mut self.reader, &mut self.raw)?; + let last = n == 0; + let needed = self.decoder.max_utf8_buffer_length(n).unwrap_or(n * 3 + 16); + if self.out.len() < needed { + self.out.resize(needed, 0); + } + // Malformed input becomes U+FFFD, as in `decode_without_bom_handling`. + let (_, _, written, _) = self.decoder.decode_to_utf8(&self.raw[..n], &mut self.out, last); + self.pos = 0; + self.len = written; + self.done = last; + } + let n = buf.len().min(self.len - self.pos); + buf[..n].copy_from_slice(&self.out[self.pos..self.pos + n]); + self.pos += n; + Ok(n) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::decode_text; + + /// Hands out at most `step` bytes per read, so chunk edges fall everywhere. + struct Trickle<'a> { + bytes: &'a [u8], + step: usize, + } + + impl Read for Trickle<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let n = buf.len().min(self.step).min(self.bytes.len()); + buf[..n].copy_from_slice(&self.bytes[..n]); + self.bytes = &self.bytes[n..]; + Ok(n) + } + } + + fn streamed(bytes: &[u8], fallback: Option<&str>, chunk: usize, step: usize) -> Option> { + let reader = decode_stream_in(|| Ok(Trickle { bytes, step }), fallback, chunk).unwrap()?; + let mut out = Vec::new(); + let mut reader = reader; + // Small reads too: the consumer's buffer is not the chunk either. + let mut buf = [0; 7]; + loop { + let n = reader.read(&mut buf).unwrap(); + if n == 0 { + return Some(out); + } + out.extend_from_slice(&buf[..n]); + } + } + + fn utf16(text: &str, bom: bool, big: bool) -> Vec { + let mut bytes = + if bom { vec![if big { 0xFE } else { 0xFF }, if big { 0xFF } else { 0xFE }] } else { Vec::new() }; + for unit in text.encode_utf16() { + bytes.extend(if big { unit.to_be_bytes() } else { unit.to_le_bytes() }); + } + bytes + } + + /// Text with multi-byte characters and surrogate pairs at every alignment. + fn sample(len: usize) -> String { + let mut text = String::new(); + let pieces = [ + "ascii line\n", + "caf\u{e9} cr\u{e8}me\n", + "\u{4e2d}\u{6587}\u{6d4b}\u{8bd5}\n", + "\u{1f600}\u{1f4a9} x\n", + "\u{20ac}5\r\n", + ]; + let mut i = 0; + while text.len() < len { + text.push_str(pieces[i * 7 % pieces.len()]); + i += 1; + } + text + } + + fn inputs() -> Vec<(String, Vec)> { + let text = sample(1500); + let mut inputs = vec![ + ("utf8".to_string(), text.clone().into_bytes()), + ("utf8 bom".to_string(), [&[0xEF, 0xBB, 0xBF][..], text.as_bytes()].concat()), + ("utf16le bom".to_string(), utf16(&text, true, false)), + ("utf16be bom".to_string(), utf16(&text, true, true)), + ("utf16le".to_string(), utf16(&sample(1500).replace(|c: char| !c.is_ascii(), "e"), false, false)), + ("utf16be".to_string(), utf16(&sample(1500).replace(|c: char| !c.is_ascii(), "e"), false, true)), + ( + "gbk".to_string(), + encoding_rs::GBK + .encode(&sample(1500).replace(['\u{1f600}', '\u{1f4a9}', '\u{20ac}'], "")) + .0 + .into_owned(), + ), + ( + "latin1".to_string(), + encoding_rs::WINDOWS_1252 + .encode(&sample(1500).replace(|c: char| c as u32 > 0xff && c != '\u{20ac}', "")) + .0 + .into_owned(), + ), + ("empty".to_string(), Vec::new()), + ("binary".to_string(), b"\x7FELF\x02\x01\x01\x00\x00\x00 and text".repeat(100)), + ("late nul".to_string(), [&b"abc caf\xe9 ".repeat(1200)[..], b"\0 tail"].concat()), + ("truncated utf8".to_string(), text.as_bytes()[..text.len() - 1].to_vec()), + ("truncated utf16".to_string(), utf16(&text, true, false)[..utf16(&text, true, false).len() - 1].to_vec()), + ( + "lone surrogate".to_string(), + [&[0xFF, 0xFE][..], &[0x3D, 0xD8, b'a', 0][..], &utf16(&text, false, false)[..]].concat(), + ), + ("invalid in the middle".to_string(), [text.as_bytes(), b"\xff\xfe\xc3", text.as_bytes()].concat()), + ( + "shift jis".to_string(), + encoding_rs::SHIFT_JIS + .encode( + "\u{3053}\u{3093}\u{306b}\u{3061}\u{306f}\u{4e16}\u{754c}\u{ff76}\u{ff85}\n" + .repeat(200) + .as_str(), + ) + .0 + .into_owned(), + ), + ]; + // The evidence for the encoding comes long after the sniffed head. + let chinese = "\u{4e2d}\u{6587}\u{6d4b}\u{8bd5}\u{4e00}\u{6bb5}\u{6587}\u{672c}\n".repeat(300); + let gbk = encoding_rs::GBK.encode(&chinese).0.into_owned(); + let head = "plain ascii line\n".repeat(1500); + inputs.push(("gbk after a long ascii head".to_string(), [head.as_bytes(), &gbk].concat())); + // Characters at every alignment against the sniffing head and the chunks. + for pad in 0..5 { + let mut bytes = "x".repeat(SNIFF_LEN - 3 + pad).into_bytes(); + bytes.extend("\u{4e2d}\u{1f600}\u{e9}".as_bytes()); + inputs.push((format!("utf8 at the head edge {pad}"), bytes)); + let mut bytes = "y".repeat(SNIFF_LEN - 2 + pad).into_bytes(); + bytes.extend([0xE9, b'z', 0xFF, b'e']); + inputs.push((format!("latin1 at the head edge {pad}"), bytes)); + } + inputs + } + + #[test] + fn streamed_text_equals_the_whole_file_decode() { + for (name, bytes) in inputs() { + for fallback in [None, Some("gbk"), Some("windows-1252"), Some("utf-16le"), Some("nonsense")] { + let expected = decode_text(&bytes, fallback).map(String::into_bytes); + for chunk in [1, 2, 3, 4, 5, 16, 255, 4096, CHUNK] { + for step in [1, 3, 8192, usize::MAX] { + assert_eq!( + streamed(&bytes, fallback, chunk, step), + expected, + "{name}, fallback {fallback:?}, chunk {chunk}, step {step}" + ); + } + } + } + } + } + + #[test] + fn utf8_check_matches_from_utf8_for_any_split() { + let samples: [&[u8]; 6] = [ + "a\u{e9}\u{4e2d}\u{1f600}z".as_bytes(), + b"ab\xe4\xb8", + b"\xe4\xb8a", + b"\xf0\x9f\x98", + b"ok\xc3(", + b"\xed\xa0\x80", + ]; + for bytes in samples { + for first in 0..=bytes.len() { + for second in first..=bytes.len() { + let mut check = Utf8Check::default(); + check.feed(&bytes[..first]); + check.feed(&bytes[first..second]); + check.feed(&bytes[second..]); + assert_eq!(check.is_valid(), std::str::from_utf8(bytes).is_ok(), "{bytes:?} {first} {second}"); + } + } + } + } + + #[test] + fn reads_at_most_a_bounded_number_of_bytes_per_step() { + // A reader that fails if asked for more than one chunk shows nothing is read whole. + struct Capped<'a>(&'a [u8]); + impl Read for Capped<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + assert!(buf.len() <= SNIFF_LEN.max(1024), "asked for {} bytes", buf.len()); + let n = buf.len().min(self.0.len()); + buf[..n].copy_from_slice(&self.0[..n]); + self.0 = &self.0[n..]; + Ok(n) + } + } + let bytes = encoding_rs::WINDOWS_1252.encode(&"caf\u{e9}\n".repeat(50_000)).0.into_owned(); + let mut reader = decode_stream_in(|| Ok(Capped(&bytes)), None, 1024).unwrap().unwrap(); + let mut text = String::new(); + reader.read_to_string(&mut text).unwrap(); + assert_eq!(text, "caf\u{e9}\n".repeat(50_000)); + assert!(reader.out.len() <= 4 * 1024 + 16 && reader.raw.len() == 1024); + } +} diff --git a/crates/ide-vfs/src/encoding.rs b/crates/ide-vfs/src/encoding.rs index 24484c5ea..158579bf4 100644 --- a/crates/ide-vfs/src/encoding.rs +++ b/crates/ide-vfs/src/encoding.rs @@ -103,7 +103,7 @@ pub fn save_properties_text(path: &Path, text: &str) -> IdeResult { } /// Detects BOM-less UTF-16 from the distribution of NUL bytes in mostly-ASCII text. -fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> { +pub(crate) fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> { if sample.len() < 4 { return None; } diff --git a/crates/ide-vfs/src/lib.rs b/crates/ide-vfs/src/lib.rs index 61eea7e2b..d4a67d8e1 100644 --- a/crates/ide-vfs/src/lib.rs +++ b/crates/ide-vfs/src/lib.rs @@ -3,6 +3,7 @@ mod archive; mod bytes; mod compare; +mod decode_stream; mod encoding; mod ops; mod private; @@ -30,6 +31,7 @@ pub use compare::{ DirectoryCompareEntry, DirectoryCompareMode, DirectoryCompareProgress, DirectoryCompareStatus, DirectorySyncAction, DirectorySyncFailure, DirectorySyncOperation, DirectorySyncProgress, compare_directories, copy_merge, }; +pub use decode_stream::{DecodedReader, decode_stream}; use encoding::SNIFF_LEN; pub use encoding::{ LARGE_FILE_THRESHOLD, MAX_OPEN_SIZE, READ_ONLY_THRESHOLD, decode_properties_escapes, encode,