Skip to content

Commit ace9a74

Browse files
committed
Auto merge of rust-lang#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.
2 parents d327d65 + 3145c06 commit ace9a74

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

compiler/rustc_span/src/source_map.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
//! within the `SourceMap`, which upon request can be converted to line and column
1010
//! information, source code snippets, etc.
1111
12+
use std::fs::File;
1213
use std::io::{self, BorrowedBuf, Read};
1314
use std::{fs, path};
1415

@@ -115,13 +116,18 @@ impl FileLoader for RealFileLoader {
115116
}
116117

117118
fn read_file(&self, path: &Path) -> io::Result<String> {
118-
if path.metadata().is_ok_and(|metadata| metadata.len() > SourceFile::MAX_FILE_SIZE.into()) {
119+
let mut file = File::open(path)?;
120+
let size = file.metadata().map(|metadata| metadata.len()).ok().unwrap_or(0);
121+
122+
if size > SourceFile::MAX_FILE_SIZE.into() {
119123
return Err(io::Error::other(format!(
120124
"text files larger than {} bytes are unsupported",
121125
SourceFile::MAX_FILE_SIZE
122126
)));
123127
}
124-
fs::read_to_string(path)
128+
let mut contents = String::new();
129+
file.read_to_string(&mut contents)?;
130+
Ok(contents)
125131
}
126132

127133
fn read_binary_file(&self, path: &Path) -> io::Result<Arc<[u8]>> {

0 commit comments

Comments
 (0)