Skip to content

Commit 2f62265

Browse files
committed
use top level fs functions where appropriate
This commit replaces many usages of `File::open` and reading or writing with `fs::read_to_string`, `fs::read` and `fs::write`. This reduces code complexity, and will improve performance for most reads, since the functions allocate the buffer to be the size of the file. I believe that this commit will not impact behavior in any way, so some matches will check the error kind in case the file was not valid UTF-8. Some of these cases may not actually care about the error.
1 parent 1c3236a commit 2f62265

File tree

26 files changed

+137
-235
lines changed

26 files changed

+137
-235
lines changed

src/bootstrap/compile.rs

+9-10
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
1919
use std::borrow::Cow;
2020
use std::env;
21-
use std::fs::{self, File};
21+
use std::fs;
2222
use std::io::BufReader;
2323
use std::io::prelude::*;
2424
use std::path::{Path, PathBuf};
@@ -707,7 +707,7 @@ impl Step for CodegenBackend {
707707
}
708708
let stamp = codegen_backend_stamp(builder, compiler, target, backend);
709709
let codegen_backend = codegen_backend.to_str().unwrap();
710-
t!(t!(File::create(&stamp)).write_all(codegen_backend.as_bytes()));
710+
t!(fs::write(&stamp, &codegen_backend));
711711
}
712712
}
713713

@@ -796,8 +796,7 @@ fn copy_codegen_backends_to_sysroot(builder: &Builder,
796796

797797
for backend in builder.config.rust_codegen_backends.iter() {
798798
let stamp = codegen_backend_stamp(builder, compiler, target, *backend);
799-
let mut dylib = String::new();
800-
t!(t!(File::open(&stamp)).read_to_string(&mut dylib));
799+
let dylib = t!(fs::read_to_string(&stamp));
801800
let file = Path::new(&dylib);
802801
let filename = file.file_name().unwrap().to_str().unwrap();
803802
// change `librustc_codegen_llvm-xxxxxx.so` to `librustc_codegen_llvm-llvm.so`
@@ -1137,10 +1136,7 @@ pub fn run_cargo(builder: &Builder,
11371136
// contents (the list of files to copy) is different or if any dep's mtime
11381137
// is newer then we rewrite the stamp file.
11391138
deps.sort();
1140-
let mut stamp_contents = Vec::new();
1141-
if let Ok(mut f) = File::open(stamp) {
1142-
t!(f.read_to_end(&mut stamp_contents));
1143-
}
1139+
let stamp_contents = fs::read(stamp);
11441140
let stamp_mtime = mtime(&stamp);
11451141
let mut new_contents = Vec::new();
11461142
let mut max = None;
@@ -1156,7 +1152,10 @@ pub fn run_cargo(builder: &Builder,
11561152
}
11571153
let max = max.unwrap();
11581154
let max_path = max_path.unwrap();
1159-
if stamp_contents == new_contents && max <= stamp_mtime {
1155+
let contents_equal = stamp_contents
1156+
.map(|contents| contents == new_contents)
1157+
.unwrap_or_default();
1158+
if contents_equal && max <= stamp_mtime {
11601159
builder.verbose(&format!("not updating {:?}; contents equal and {:?} <= {:?}",
11611160
stamp, max, stamp_mtime));
11621161
return deps
@@ -1166,7 +1165,7 @@ pub fn run_cargo(builder: &Builder,
11661165
} else {
11671166
builder.verbose(&format!("updating {:?} as deps changed", stamp));
11681167
}
1169-
t!(t!(File::create(stamp)).write_all(&new_contents));
1168+
t!(fs::write(&stamp, &new_contents));
11701169
deps
11711170
}
11721171

src/bootstrap/config.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,7 @@
1515
1616
use std::collections::{HashMap, HashSet};
1717
use std::env;
18-
use std::fs::{self, File};
19-
use std::io::prelude::*;
18+
use std::fs;
2019
use std::path::{Path, PathBuf};
2120
use std::process;
2221
use std::cmp;
@@ -416,9 +415,7 @@ impl Config {
416415
config.run_host_only = !(flags.host.is_empty() && !flags.target.is_empty());
417416

418417
let toml = file.map(|file| {
419-
let mut f = t!(File::open(&file));
420-
let mut contents = String::new();
421-
t!(f.read_to_string(&mut contents));
418+
let contents = t!(fs::read_to_string(&file));
422419
match toml::from_str(&contents) {
423420
Ok(table) => table,
424421
Err(err) => {

src/bootstrap/dist.rs

+6-8
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
//! pieces of `rustup.rs`!
2020
2121
use std::env;
22-
use std::fs::{self, File};
23-
use std::io::{Read, Write};
22+
use std::fs;
23+
use std::io::Write;
2424
use std::path::{PathBuf, Path};
2525
use std::process::{Command, Stdio};
2626

@@ -1511,8 +1511,7 @@ impl Step for Extended {
15111511
}
15121512

15131513
let xform = |p: &Path| {
1514-
let mut contents = String::new();
1515-
t!(t!(File::open(p)).read_to_string(&mut contents));
1514+
let mut contents = t!(fs::read_to_string(p));
15161515
if rls_installer.is_none() {
15171516
contents = filter(&contents, "rls");
15181517
}
@@ -1523,8 +1522,8 @@ impl Step for Extended {
15231522
contents = filter(&contents, "rustfmt");
15241523
}
15251524
let ret = tmp.join(p.file_name().unwrap());
1526-
t!(t!(File::create(&ret)).write_all(contents.as_bytes()));
1527-
return ret
1525+
t!(fs::write(&ret, &contents));
1526+
ret
15281527
};
15291528

15301529
if target.contains("apple-darwin") {
@@ -1869,8 +1868,7 @@ impl Step for HashSign {
18691868
let file = builder.config.dist_gpg_password_file.as_ref().unwrap_or_else(|| {
18701869
panic!("\n\nfailed to specify `dist.gpg-password-file` in `config.toml`\n\n")
18711870
});
1872-
let mut pass = String::new();
1873-
t!(t!(File::open(&file)).read_to_string(&mut pass));
1871+
let pass = t!(fs::read_to_string(&file));
18741872

18751873
let today = output(Command::new("date").arg("+%Y-%m-%d"));
18761874

src/bootstrap/doc.rs

+6-8
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,7 @@
1818
//! `rustdoc`.
1919
2020
use std::collections::HashSet;
21-
use std::fs::{self, File};
22-
use std::io::prelude::*;
21+
use std::fs;
2322
use std::io;
2423
use std::path::{PathBuf, Path};
2524

@@ -379,12 +378,11 @@ impl Step for Standalone {
379378
let version_info = out.join("version_info.html");
380379

381380
if !builder.config.dry_run && !up_to_date(&version_input, &version_info) {
382-
let mut info = String::new();
383-
t!(t!(File::open(&version_input)).read_to_string(&mut info));
384-
let info = info.replace("VERSION", &builder.rust_release())
385-
.replace("SHORT_HASH", builder.rust_info.sha_short().unwrap_or(""))
386-
.replace("STAMP", builder.rust_info.sha().unwrap_or(""));
387-
t!(t!(File::create(&version_info)).write_all(info.as_bytes()));
381+
let info = t!(fs::read_to_string(&version_input))
382+
.replace("VERSION", &builder.rust_release())
383+
.replace("SHORT_HASH", builder.rust_info.sha_short().unwrap_or(""))
384+
.replace("STAMP", builder.rust_info.sha().unwrap_or(""));
385+
t!(fs::write(&version_info, &info));
388386
}
389387

390388
for file in t!(fs::read_dir(builder.src.join("src/doc"))) {

src/bootstrap/lib.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -1067,9 +1067,8 @@ impl Build {
10671067

10681068
/// Returns the `a.b.c` version that the given package is at.
10691069
fn release_num(&self, package: &str) -> String {
1070-
let mut toml = String::new();
10711070
let toml_file_name = self.src.join(&format!("src/tools/{}/Cargo.toml", package));
1072-
t!(t!(File::open(toml_file_name)).read_to_string(&mut toml));
1071+
let toml = t!(fs::read_to_string(&toml_file_name));
10731072
for line in toml.lines() {
10741073
let prefix = "version = \"";
10751074
let suffix = "\"";
@@ -1151,8 +1150,7 @@ impl Build {
11511150
}
11521151

11531152
let mut paths = Vec::new();
1154-
let mut contents = Vec::new();
1155-
t!(t!(File::open(stamp)).read_to_end(&mut contents));
1153+
let contents = t!(fs::read(stamp));
11561154
// This is the method we use for extracting paths from the stamp file passed to us. See
11571155
// run_cargo for more information (in compile.rs).
11581156
for part in contents.split(|b| *b == 0) {

src/bootstrap/native.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
use std::env;
2222
use std::ffi::OsString;
2323
use std::fs::{self, File};
24-
use std::io::{Read, Write};
2524
use std::path::{Path, PathBuf};
2625
use std::process::Command;
2726

@@ -75,8 +74,7 @@ impl Step for Llvm {
7574
}
7675

7776
let rebuild_trigger = builder.src.join("src/rustllvm/llvm-rebuild-trigger");
78-
let mut rebuild_trigger_contents = String::new();
79-
t!(t!(File::open(&rebuild_trigger)).read_to_string(&mut rebuild_trigger_contents));
77+
let rebuild_trigger_contents = t!(fs::read_to_string(&rebuild_trigger));
8078

8179
let (out_dir, llvm_config_ret_dir) = if emscripten {
8280
let dir = builder.emscripten_llvm_out(target);
@@ -93,8 +91,7 @@ impl Step for Llvm {
9391
let build_llvm_config = llvm_config_ret_dir
9492
.join(exe("llvm-config", &*builder.config.build));
9593
if done_stamp.exists() {
96-
let mut done_contents = String::new();
97-
t!(t!(File::open(&done_stamp)).read_to_string(&mut done_contents));
94+
let done_contents = t!(fs::read_to_string(&done_stamp));
9895

9996
// If LLVM was already built previously and contents of the rebuild-trigger file
10097
// didn't change from the previous build, then no action is required.
@@ -261,7 +258,7 @@ impl Step for Llvm {
261258

262259
cfg.build();
263260

264-
t!(t!(File::create(&done_stamp)).write_all(rebuild_trigger_contents.as_bytes()));
261+
t!(fs::write(&done_stamp, &rebuild_trigger_contents));
265262

266263
build_llvm_config
267264
}

src/bootstrap/sanity.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,7 @@
2121
use std::collections::HashMap;
2222
use std::env;
2323
use std::ffi::{OsString, OsStr};
24-
use std::fs::{self, File};
25-
use std::io::Read;
24+
use std::fs;
2625
use std::path::PathBuf;
2726
use std::process::Command;
2827

@@ -235,9 +234,7 @@ $ pacman -R cmake && pacman -S mingw-w64-x86_64-cmake
235234
}
236235

237236
if build.config.channel == "stable" {
238-
let mut stage0 = String::new();
239-
t!(t!(File::open(build.src.join("src/stage0.txt")))
240-
.read_to_string(&mut stage0));
237+
let stage0 = t!(fs::read_to_string(build.src.join("src/stage0.txt")));
241238
if stage0.contains("\ndev:") {
242239
panic!("bootstrapping from a dev compiler in a stable release, but \
243240
should only be bootstrapping from a released compiler!");

src/bootstrap/test.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,7 @@
1616
use std::env;
1717
use std::ffi::OsString;
1818
use std::fmt;
19-
use std::fs::{self, File};
20-
use std::io::Read;
19+
use std::fs;
2120
use std::iter;
2221
use std::path::{Path, PathBuf};
2322
use std::process::Command;
@@ -1427,10 +1426,8 @@ impl Step for ErrorIndex {
14271426
}
14281427

14291428
fn markdown_test(builder: &Builder, compiler: Compiler, markdown: &Path) -> bool {
1430-
match File::open(markdown) {
1431-
Ok(mut file) => {
1432-
let mut contents = String::new();
1433-
t!(file.read_to_string(&mut contents));
1429+
match fs::read_to_string(markdown) {
1430+
Ok(contents) => {
14341431
if !contents.contains("```") {
14351432
return true;
14361433
}

src/libcore/convert.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,8 @@ pub trait Into<T>: Sized {
327327
/// An example usage for error handling:
328328
///
329329
/// ```
330-
/// use std::io::{self, Read};
330+
/// use std::fs;
331+
/// use std::io;
331332
/// use std::num;
332333
///
333334
/// enum CliError {
@@ -348,9 +349,7 @@ pub trait Into<T>: Sized {
348349
/// }
349350
///
350351
/// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
351-
/// let mut file = std::fs::File::open("test")?;
352-
/// let mut contents = String::new();
353-
/// file.read_to_string(&mut contents)?;
352+
/// let mut contents = fs::read_to_string(&file_name)?;
354353
/// let num: i32 = contents.trim().parse()?;
355354
/// Ok(num)
356355
/// }

src/librustc/infer/lexical_region_resolve/graphviz.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,8 @@ use std::borrow::Cow;
3131
use std::collections::hash_map::Entry::Vacant;
3232
use std::collections::btree_map::BTreeMap;
3333
use std::env;
34-
use std::fs::File;
34+
use std::fs;
3535
use std::io;
36-
use std::io::prelude::*;
3736
use std::sync::atomic::{AtomicBool, Ordering};
3837

3938
fn print_help_message() {
@@ -268,5 +267,5 @@ fn dump_region_data_to<'a, 'gcx, 'tcx>(region_rels: &RegionRelations<'a, 'gcx, '
268267
debug!("dump_region_data calling render");
269268
let mut v = Vec::new();
270269
dot::render(&g, &mut v).unwrap();
271-
File::create(path).and_then(|mut f| f.write_all(&v))
270+
fs::write(path, &v)
272271
}

src/librustc_codegen_utils/codegen_backend.rs

+4-9
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@
2222
#![feature(box_syntax)]
2323

2424
use std::any::Any;
25-
use std::io::{self, Write};
26-
use std::fs::File;
25+
use std::io::Write;
26+
use std::fs;
2727
use std::path::Path;
2828
use std::sync::{mpsc, Arc};
2929

@@ -81,11 +81,7 @@ pub struct NoLlvmMetadataLoader;
8181

8282
impl MetadataLoader for NoLlvmMetadataLoader {
8383
fn get_rlib_metadata(&self, _: &Target, filename: &Path) -> Result<MetadataRef, String> {
84-
let mut file = File::open(filename)
85-
.map_err(|e| format!("metadata file open err: {:?}", e))?;
86-
87-
let mut buf = Vec::new();
88-
io::copy(&mut file, &mut buf).unwrap();
84+
let buf = fs::read(filename).map_err(|e| format!("metadata file open err: {:?}", e))?;
8985
let buf: OwningRef<Vec<u8>, [u8]> = OwningRef::new(buf);
9086
Ok(rustc_erase_owner!(buf.map_owner_box()))
9187
}
@@ -209,8 +205,7 @@ impl CodegenBackend for MetadataOnlyCodegenBackend {
209205
} else {
210206
&ongoing_codegen.metadata.raw_data
211207
};
212-
let mut file = File::create(&output_name).unwrap();
213-
file.write_all(metadata).unwrap();
208+
fs::write(&output_name, metadata).unwrap();
214209
}
215210

216211
sess.abort_if_errors();

src/librustdoc/html/render.rs

+4-12
Original file line numberDiff line numberDiff line change
@@ -778,10 +778,7 @@ fn write_shared(
778778
let mut themes: FxHashSet<String> = FxHashSet::default();
779779

780780
for entry in &cx.shared.themes {
781-
let mut content = Vec::with_capacity(100000);
782-
783-
let mut f = try_err!(File::open(&entry), &entry);
784-
try_err!(f.read_to_end(&mut content), &entry);
781+
let content = try_err!(fs::read(&entry), &entry);
785782
let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
786783
let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
787784
write(cx.dst.join(format!("{}{}.{}", theme, cx.shared.resource_suffix, extension)),
@@ -881,10 +878,7 @@ themePicker.onblur = handleThemeButtonsBlur;
881878
if !options.enable_minification {
882879
try_err!(fs::copy(css, out), css);
883880
} else {
884-
let mut f = try_err!(File::open(css), css);
885-
let mut buffer = String::with_capacity(1000);
886-
887-
try_err!(f.read_to_string(&mut buffer), css);
881+
let buffer = try_err!(fs::read_to_string(css), css);
888882
write_minify(out, &buffer, options.enable_minification)?;
889883
}
890884
}
@@ -2102,8 +2096,7 @@ impl Context {
21022096
if !buf.is_empty() {
21032097
try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
21042098
let joint_dst = this.dst.join("index.html");
2105-
let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
2106-
try_err!(dst.write_all(&buf), &joint_dst);
2099+
try_err!(fs::write(&joint_dst, buf), &joint_dst);
21072100
}
21082101

21092102
let m = match item.inner {
@@ -2137,8 +2130,7 @@ impl Context {
21372130
let file_name = &item_path(item_type, name);
21382131
try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
21392132
let joint_dst = self.dst.join(file_name);
2140-
let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
2141-
try_err!(dst.write_all(&buf), &joint_dst);
2133+
try_err!(fs::write(&joint_dst, buf), &joint_dst);
21422134

21432135
if !self.render_redirect_pages {
21442136
all.append(full_path(self, &item), &item_type);

src/librustdoc/theme.rs

+3-7
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,8 @@
99
// except according to those terms.
1010

1111
use rustc_data_structures::fx::FxHashSet;
12-
use std::fs::File;
12+
use std::fs;
1313
use std::hash::{Hash, Hasher};
14-
use std::io::Read;
1514
use std::path::Path;
1615

1716
use errors::Handler;
@@ -278,12 +277,9 @@ pub fn get_differences(against: &CssPath, other: &CssPath, v: &mut Vec<String>)
278277
pub fn test_theme_against<P: AsRef<Path>>(f: &P, against: &CssPath, diag: &Handler)
279278
-> (bool, Vec<String>)
280279
{
281-
let mut file = try_something!(File::open(f), diag, (false, Vec::new()));
282-
let mut data = Vec::with_capacity(1000);
283-
284-
try_something!(file.read_to_end(&mut data), diag, (false, Vec::new()));
280+
let data = try_something!(fs::read(f), diag, (false, vec![]));
285281
let paths = load_css_paths(&data);
286-
let mut ret = Vec::new();
282+
let mut ret = vec![];
287283
get_differences(against, &paths, &mut ret);
288284
(true, ret)
289285
}

0 commit comments

Comments
 (0)