Skip to content

Commit df5c880

Browse files
Auto merge of #145848 - Kobzol:optimize-file-read, r=<try>
Slightly optimize reading of source files
2 parents ee361e8 + 66f96d6 commit df5c880

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

compiler/rustc_span/src/source_map.rs

Lines changed: 7 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,17 @@ 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::with_capacity(size);
129+
file.read_to_string(&mut contents)
125130
}
126131

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

0 commit comments

Comments
 (0)