about summary refs log tree commit diff
path: root/compiler
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2025-08-26 04:19:21 +0000
committerbors <bors@rust-lang.org>2025-08-26 04:19:21 +0000
commitace9a74442aec13c75532d34e15d97428056866d (patch)
tree21c90884cc6c5e4e9dd2d5441a083f0e5dc1a5f3 /compiler
parentd327d651e2583eb601978179f2ca9808f5e243bb (diff)
parent3145c0643153e688b8e080a0c5eb328d11011bdb (diff)
downloadrust-ace9a74442aec13c75532d34e15d97428056866d.tar.gz
rust-ace9a74442aec13c75532d34e15d97428056866d.zip
Auto merge of #145848 - Kobzol:optimize-file-read, r=the8472
Slightly optimize reading of source files

Discussed on Zulip (https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/rustc.20uses.20silly.20amount.20of.20syscalls.20for.20file.20IO/with/536015625.

Do not open/close each source file twice when reading it. We still stat it twice though.
Diffstat (limited to 'compiler')
-rw-r--r--compiler/rustc_span/src/source_map.rs10
1 files changed, 8 insertions, 2 deletions
diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs
index 8270de1e917..166842e374b 100644
--- a/compiler/rustc_span/src/source_map.rs
+++ b/compiler/rustc_span/src/source_map.rs
@@ -9,6 +9,7 @@
 //! within the `SourceMap`, which upon request can be converted to line and column
 //! information, source code snippets, etc.
 
+use std::fs::File;
 use std::io::{self, BorrowedBuf, Read};
 use std::{fs, path};
 
@@ -115,13 +116,18 @@ impl FileLoader for RealFileLoader {
     }
 
     fn read_file(&self, path: &Path) -> io::Result<String> {
-        if path.metadata().is_ok_and(|metadata| metadata.len() > SourceFile::MAX_FILE_SIZE.into()) {
+        let mut file = File::open(path)?;
+        let size = file.metadata().map(|metadata| metadata.len()).ok().unwrap_or(0);
+
+        if size > SourceFile::MAX_FILE_SIZE.into() {
             return Err(io::Error::other(format!(
                 "text files larger than {} bytes are unsupported",
                 SourceFile::MAX_FILE_SIZE
             )));
         }
-        fs::read_to_string(path)
+        let mut contents = String::new();
+        file.read_to_string(&mut contents)?;
+        Ok(contents)
     }
 
     fn read_binary_file(&self, path: &Path) -> io::Result<Arc<[u8]>> {