Skip to content

Commit 0d3761c

Browse files
committed
Optimize fs::write
Write then truncate instead of truncate then write.
1 parent 32c8a9f commit 0d3761c

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

library/std/src/fs.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,14 @@ pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
346346
#[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
347347
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
348348
fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
349-
File::create(path)?.write_all(contents)
349+
// As an optimization we don't truncate.
350+
// Instead we overwrite the existing content and then set the file length
351+
// to the number of written bytes (whether or not writing succeeds).
352+
let mut f = OpenOptions::new().write(true).create(true).open(path)?;
353+
let r = f.write_all(contents);
354+
let r2 = f.stream_position().and_then(|pos| f.set_len(pos));
355+
// Return the most pertinent error, if any.
356+
if r.is_err() { r } else { r2 }
350357
}
351358
inner(path.as_ref(), contents.as_ref())
352359
}

0 commit comments

Comments
 (0)