Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit cb6102f

Browse files
authoredDec 5, 2018
Rollup merge of rust-lang#56258 - euclio:fs-read-write, r=Mark-Simulacrum
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.
2 parents ec16058 + d809d21 commit cb6102f

File tree

26 files changed

+130
-231
lines changed

26 files changed

+130
-231
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

@@ -1510,8 +1510,7 @@ impl Step for Extended {
15101510
}
15111511

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

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

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

‎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

+5-10
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,12 +81,8 @@ 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();
89-
let buf: OwningRef<Vec<u8>, [u8]> = OwningRef::new(buf).into();
84+
let buf = fs::read(filename).map_err(|e| format!("metadata file open err: {:?}", e))?;
85+
let buf: OwningRef<Vec<u8>, [u8]> = OwningRef::new(buf);
9086
return Ok(rustc_erase_owner!(buf.map_owner_box()));
9187
}
9288

@@ -212,8 +208,7 @@ impl CodegenBackend for MetadataOnlyCodegenBackend {
212208
} else {
213209
&ongoing_codegen.metadata.raw_data
214210
};
215-
let mut file = File::create(&output_name).unwrap();
216-
file.write_all(metadata).unwrap();
211+
fs::write(&output_name, metadata).unwrap();
217212
}
218213

219214
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)),
@@ -879,10 +876,7 @@ themePicker.onblur = handleThemeButtonsBlur;
879876
if !options.enable_minification {
880877
try_err!(fs::copy(css, out), css);
881878
} else {
882-
let mut f = try_err!(File::open(css), css);
883-
let mut buffer = String::with_capacity(1000);
884-
885-
try_err!(f.read_to_string(&mut buffer), css);
879+
let buffer = try_err!(fs::read_to_string(css), css);
886880
write_minify(out, &buffer, options.enable_minification)?;
887881
}
888882
}
@@ -2100,8 +2094,7 @@ impl Context {
21002094
if !buf.is_empty() {
21012095
try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
21022096
let joint_dst = this.dst.join("index.html");
2103-
let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
2104-
try_err!(dst.write_all(&buf), &joint_dst);
2097+
try_err!(fs::write(&joint_dst, buf), &joint_dst);
21052098
}
21062099

21072100
let m = match item.inner {
@@ -2135,8 +2128,7 @@ impl Context {
21352128
let file_name = &item_path(item_type, name);
21362129
try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
21372130
let joint_dst = self.dst.join(file_name);
2138-
let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
2139-
try_err!(dst.write_all(&buf), &joint_dst);
2131+
try_err!(fs::write(&joint_dst, buf), &joint_dst);
21402132

21412133
if !self.render_redirect_pages {
21422134
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
}

‎src/libsyntax/ext/expand.rs

+24-23
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ use tokenstream::{TokenStream, TokenTree};
3434
use visit::{self, Visitor};
3535

3636
use rustc_data_structures::fx::FxHashMap;
37-
use std::fs::File;
38-
use std::io::Read;
37+
use std::fs;
38+
use std::io::ErrorKind;
3939
use std::{iter, mem};
4040
use std::rc::Rc;
4141
use std::path::PathBuf;
@@ -1519,20 +1519,8 @@ impl<'a, 'b> Folder for InvocationCollector<'a, 'b> {
15191519
return noop_fold_attribute(at, self);
15201520
}
15211521

1522-
let mut buf = vec![];
15231522
let filename = self.cx.root_path.join(file.to_string());
1524-
1525-
match File::open(&filename).and_then(|mut f| f.read_to_end(&mut buf)) {
1526-
Ok(..) => {}
1527-
Err(e) => {
1528-
self.cx.span_err(at.span,
1529-
&format!("couldn't read {}: {}",
1530-
filename.display(),
1531-
e));
1532-
}
1533-
}
1534-
1535-
match String::from_utf8(buf) {
1523+
match fs::read_to_string(&filename) {
15361524
Ok(src) => {
15371525
let src_interned = Symbol::intern(&src);
15381526

@@ -1542,21 +1530,34 @@ impl<'a, 'b> Folder for InvocationCollector<'a, 'b> {
15421530

15431531
let include_info = vec![
15441532
dummy_spanned(ast::NestedMetaItemKind::MetaItem(
1545-
attr::mk_name_value_item_str(Ident::from_str("file"),
1546-
dummy_spanned(file)))),
1533+
attr::mk_name_value_item_str(
1534+
Ident::from_str("file"),
1535+
dummy_spanned(file),
1536+
),
1537+
)),
15471538
dummy_spanned(ast::NestedMetaItemKind::MetaItem(
1548-
attr::mk_name_value_item_str(Ident::from_str("contents"),
1549-
dummy_spanned(src_interned)))),
1539+
attr::mk_name_value_item_str(
1540+
Ident::from_str("contents"),
1541+
dummy_spanned(src_interned),
1542+
),
1543+
)),
15501544
];
15511545

15521546
let include_ident = Ident::from_str("include");
15531547
let item = attr::mk_list_item(DUMMY_SP, include_ident, include_info);
15541548
items.push(dummy_spanned(ast::NestedMetaItemKind::MetaItem(item)));
15551549
}
1556-
Err(_) => {
1557-
self.cx.span_err(at.span,
1558-
&format!("{} wasn't a utf-8 file",
1559-
filename.display()));
1550+
Err(ref e) if e.kind() == ErrorKind::InvalidData => {
1551+
self.cx.span_err(
1552+
at.span,
1553+
&format!("{} wasn't a utf-8 file", filename.display()),
1554+
);
1555+
}
1556+
Err(e) => {
1557+
self.cx.span_err(
1558+
at.span,
1559+
&format!("couldn't read {}: {}", filename.display(), e),
1560+
);
15601561
}
15611562
}
15621563
} else {

‎src/libsyntax/ext/source_util.rs

+15-26
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ use smallvec::SmallVec;
2121
use symbol::Symbol;
2222
use tokenstream;
2323

24-
use std::fs::File;
25-
use std::io::prelude::*;
24+
use std::fs;
25+
use std::io::ErrorKind;
2626
use std::path::PathBuf;
2727
use rustc_data_structures::sync::Lrc;
2828

@@ -137,18 +137,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenT
137137
None => return DummyResult::expr(sp)
138138
};
139139
let file = res_rel_file(cx, sp, file);
140-
let mut bytes = Vec::new();
141-
match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) {
142-
Ok(..) => {}
143-
Err(e) => {
144-
cx.span_err(sp,
145-
&format!("couldn't read {}: {}",
146-
file.display(),
147-
e));
148-
return DummyResult::expr(sp);
149-
}
150-
};
151-
match String::from_utf8(bytes) {
140+
match fs::read_to_string(&file) {
152141
Ok(src) => {
153142
let interned_src = Symbol::intern(&src);
154143

@@ -157,11 +146,13 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenT
157146
cx.source_map().new_source_file(file.into(), src);
158147

159148
base::MacEager::expr(cx.expr_str(sp, interned_src))
149+
},
150+
Err(ref e) if e.kind() == ErrorKind::InvalidData => {
151+
cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
152+
DummyResult::expr(sp)
160153
}
161-
Err(_) => {
162-
cx.span_err(sp,
163-
&format!("{} wasn't a utf-8 file",
164-
file.display()));
154+
Err(e) => {
155+
cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
165156
DummyResult::expr(sp)
166157
}
167158
}
@@ -174,20 +165,18 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::Toke
174165
None => return DummyResult::expr(sp)
175166
};
176167
let file = res_rel_file(cx, sp, file);
177-
let mut bytes = Vec::new();
178-
match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) {
179-
Err(e) => {
180-
cx.span_err(sp,
181-
&format!("couldn't read {}: {}", file.display(), e));
182-
DummyResult::expr(sp)
183-
}
184-
Ok(..) => {
168+
match fs::read(&file) {
169+
Ok(bytes) => {
185170
// Add this input file to the code map to make it available as
186171
// dependency information, but don't enter it's contents
187172
cx.source_map().new_source_file(file.into(), String::new());
188173

189174
base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes))))
190175
}
176+
Err(e) => {
177+
cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
178+
DummyResult::expr(sp)
179+
}
191180
}
192181
}
193182

‎src/libsyntax/source_map.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ use std::path::{Path, PathBuf};
3131

3232
use std::env;
3333
use std::fs;
34-
use std::io::{self, Read};
34+
use std::io;
3535
use errors::SourceMapper;
3636

3737
/// Return the span itself if it doesn't come from a macro expansion,
@@ -96,9 +96,7 @@ impl FileLoader for RealFileLoader {
9696
}
9797

9898
fn read_file(&self, path: &Path) -> io::Result<String> {
99-
let mut src = String::new();
100-
fs::File::open(path)?.read_to_string(&mut src)?;
101-
Ok(src)
99+
fs::read_to_string(path)
102100
}
103101
}
104102

‎src/tools/build-manifest/src/main.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -606,7 +606,7 @@ impl Builder {
606606

607607
let filename = path.file_name().unwrap().to_str().unwrap();
608608
let sha256 = self.output.join(format!("{}.sha256", filename));
609-
t!(t!(File::create(&sha256)).write_all(&sha.stdout));
609+
t!(fs::write(&sha256, &sha.stdout));
610610

611611
let stdout = String::from_utf8_lossy(&sha.stdout);
612612
stdout.split_whitespace().next().unwrap().to_string()
@@ -643,7 +643,7 @@ impl Builder {
643643

644644
fn write(&self, contents: &str, channel_name: &str, suffix: &str) {
645645
let dst = self.output.join(format!("channel-rust-{}{}", channel_name, suffix));
646-
t!(t!(File::create(&dst)).write_all(contents.as_bytes()));
646+
t!(fs::write(&dst, contents));
647647
self.hash(&dst);
648648
self.sign(&dst);
649649
}

‎src/tools/cargotest/main.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
use std::env;
1212
use std::process::Command;
1313
use std::path::{Path, PathBuf};
14-
use std::fs::File;
15-
use std::io::Write;
14+
use std::fs;
1615

1716
struct Test {
1817
repo: &'static str,
@@ -91,10 +90,7 @@ fn test_repo(cargo: &Path, out_dir: &Path, test: &Test) {
9190
println!("testing {}", test.repo);
9291
let dir = clone_repo(test, out_dir);
9392
if let Some(lockfile) = test.lock {
94-
File::create(&dir.join("Cargo.lock"))
95-
.expect("")
96-
.write_all(lockfile.as_bytes())
97-
.expect("");
93+
fs::write(&dir.join("Cargo.lock"), lockfile).unwrap();
9894
}
9995
if !run_cargo_test(cargo, &dir, test.packages) {
10096
panic!("tests failed for {}", test.repo);

‎src/tools/compiletest/src/main.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ use getopts::Options;
3838
use std::env;
3939
use std::ffi::OsString;
4040
use std::fs;
41-
use std::io::{self, Read};
41+
use std::io::{self, ErrorKind};
4242
use std::path::{Path, PathBuf};
4343
use std::process::Command;
4444
use test::ColorConfig;
@@ -686,13 +686,11 @@ fn up_to_date(
686686
) -> bool {
687687
let stamp_name = stamp(config, testpaths, revision);
688688
// Check hash.
689-
let mut f = match fs::File::open(&stamp_name) {
689+
let contents = match fs::read_to_string(&stamp_name) {
690690
Ok(f) => f,
691+
Err(ref e) if e.kind() == ErrorKind::InvalidData => panic!("Can't read stamp contents"),
691692
Err(_) => return true,
692693
};
693-
let mut contents = String::new();
694-
f.read_to_string(&mut contents)
695-
.expect("Can't read stamp contents");
696694
let expected_hash = runtest::compute_stamp_hash(config);
697695
if contents != expected_hash {
698696
return true;

‎src/tools/compiletest/src/runtest.rs

+19-51
Original file line numberDiff line numberDiff line change
@@ -458,11 +458,7 @@ impl<'test> TestCx<'test> {
458458
None => 2,
459459
};
460460

461-
let mut src = String::new();
462-
File::open(&self.testpaths.file)
463-
.unwrap()
464-
.read_to_string(&mut src)
465-
.unwrap();
461+
let src = fs::read_to_string(&self.testpaths.file).unwrap();
466462
let mut srcs = vec![src];
467463

468464
let mut round = 0;
@@ -500,12 +496,7 @@ impl<'test> TestCx<'test> {
500496
let mut expected = match self.props.pp_exact {
501497
Some(ref file) => {
502498
let filepath = self.testpaths.file.parent().unwrap().join(file);
503-
let mut s = String::new();
504-
File::open(&filepath)
505-
.unwrap()
506-
.read_to_string(&mut s)
507-
.unwrap();
508-
s
499+
fs::read_to_string(&filepath).unwrap()
509500
}
510501
None => srcs[srcs.len() - 2].clone(),
511502
};
@@ -1949,10 +1940,7 @@ impl<'test> TestCx<'test> {
19491940

19501941
fn dump_output_file(&self, out: &str, extension: &str) {
19511942
let outfile = self.make_out_name(extension);
1952-
File::create(&outfile)
1953-
.unwrap()
1954-
.write_all(out.as_bytes())
1955-
.unwrap();
1943+
fs::write(&outfile, out).unwrap();
19561944
}
19571945

19581946
/// Create a filename for output with the given extension. Example:
@@ -2149,11 +2137,7 @@ impl<'test> TestCx<'test> {
21492137
path: &P,
21502138
mut other_files: Option<&mut Vec<String>>,
21512139
) -> Vec<usize> {
2152-
let mut file =
2153-
fs::File::open(path).expect("markdown_test_output_check_entry File::open failed");
2154-
let mut content = String::new();
2155-
file.read_to_string(&mut content)
2156-
.expect("markdown_test_output_check_entry read_to_string failed");
2140+
let content = fs::read_to_string(&path).unwrap();
21572141
let mut ignore = false;
21582142
content
21592143
.lines()
@@ -2826,11 +2810,7 @@ impl<'test> TestCx<'test> {
28262810
}
28272811

28282812
fn check_mir_dump(&self) {
2829-
let mut test_file_contents = String::new();
2830-
fs::File::open(self.testpaths.file.clone())
2831-
.unwrap()
2832-
.read_to_string(&mut test_file_contents)
2833-
.unwrap();
2813+
let test_file_contents = fs::read_to_string(&self.testpaths.file).unwrap();
28342814
if let Some(idx) = test_file_contents.find("// END RUST SOURCE") {
28352815
let (_, tests_text) = test_file_contents.split_at(idx + "// END_RUST SOURCE".len());
28362816
let tests_text_str = String::from(tests_text);
@@ -2894,9 +2874,7 @@ impl<'test> TestCx<'test> {
28942874
}
28952875
self.check_mir_test_timestamp(test_name, &output_file);
28962876

2897-
let mut dumped_file = fs::File::open(output_file.clone()).unwrap();
2898-
let mut dumped_string = String::new();
2899-
dumped_file.read_to_string(&mut dumped_string).unwrap();
2877+
let dumped_string = fs::read_to_string(&output_file).unwrap();
29002878
let mut dumped_lines = dumped_string
29012879
.lines()
29022880
.map(|l| nocomment_mir_line(l))
@@ -3108,19 +3086,13 @@ impl<'test> TestCx<'test> {
31083086
}
31093087

31103088
fn load_expected_output_from_path(&self, path: &Path) -> Result<String, String> {
3111-
let mut result = String::new();
3112-
match File::open(path).and_then(|mut f| f.read_to_string(&mut result)) {
3113-
Ok(_) => Ok(result),
3114-
Err(e) => Err(format!(
3115-
"failed to load expected output from `{}`: {}",
3116-
path.display(),
3117-
e
3118-
)),
3119-
}
3089+
fs::read_to_string(path).map_err(|err| {
3090+
format!("failed to load expected output from `{}`: {}", path.display(), err)
3091+
})
31203092
}
31213093

31223094
fn delete_file(&self, file: &PathBuf) {
3123-
if let Err(e) = ::std::fs::remove_file(file) {
3095+
if let Err(e) = fs::remove_file(file) {
31243096
self.fatal(&format!(
31253097
"failed to delete `{}`: {}",
31263098
file.display(),
@@ -3182,16 +3154,13 @@ impl<'test> TestCx<'test> {
31823154
for output_file in &files {
31833155
if actual.is_empty() {
31843156
self.delete_file(output_file);
3185-
} else {
3186-
match File::create(&output_file).and_then(|mut f| f.write_all(actual.as_bytes())) {
3187-
Ok(()) => {}
3188-
Err(e) => self.fatal(&format!(
3189-
"failed to write {} to `{}`: {}",
3190-
kind,
3191-
output_file.display(),
3192-
e
3193-
)),
3194-
}
3157+
} else if let Err(err) = fs::write(&output_file, &actual) {
3158+
self.fatal(&format!(
3159+
"failed to write {} to `{}`: {}",
3160+
kind,
3161+
output_file.display(),
3162+
err,
3163+
));
31953164
}
31963165
}
31973166

@@ -3243,9 +3212,8 @@ impl<'test> TestCx<'test> {
32433212
}
32443213

32453214
fn create_stamp(&self) {
3246-
let mut f = File::create(::stamp(&self.config, self.testpaths, self.revision)).unwrap();
3247-
f.write_all(compute_stamp_hash(&self.config).as_bytes())
3248-
.unwrap();
3215+
let stamp = ::stamp(&self.config, self.testpaths, self.revision);
3216+
fs::write(&stamp, compute_stamp_hash(&self.config)).unwrap();
32493217
}
32503218
}
32513219

‎src/tools/error_index_generator/main.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ extern crate serialize as rustc_serialize;
1818
use std::collections::BTreeMap;
1919
use std::env;
2020
use std::error::Error;
21-
use std::fs::{read_dir, File};
22-
use std::io::{Read, Write};
21+
use std::fs::{self, read_dir, File};
22+
use std::io::Write;
2323
use std::path::Path;
2424
use std::path::PathBuf;
2525
use std::cell::RefCell;
@@ -210,8 +210,7 @@ fn load_all_errors(metadata_dir: &Path) -> Result<ErrorMetadataMap, Box<dyn Erro
210210
for entry in read_dir(metadata_dir)? {
211211
let path = entry?.path();
212212

213-
let mut metadata_str = String::new();
214-
File::open(&path).and_then(|mut f| f.read_to_string(&mut metadata_str))?;
213+
let metadata_str = fs::read_to_string(&path)?;
215214

216215
let some_errors: ErrorMetadataMap = json::decode(&metadata_str)?;
217216

‎src/tools/tidy/src/bins.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,10 @@ pub fn check(_path: &Path, _bad: &mut bool) {}
2424
#[cfg(unix)]
2525
pub fn check(path: &Path, bad: &mut bool) {
2626
use std::fs;
27-
use std::io::Read;
2827
use std::process::{Command, Stdio};
2928
use std::os::unix::prelude::*;
3029

31-
if let Ok(mut file) = fs::File::open("/proc/version") {
32-
let mut contents = String::new();
33-
file.read_to_string(&mut contents).unwrap();
30+
if let Ok(contents) = fs::read_to_string("/proc/version") {
3431
// Probably on Windows Linux Subsystem or Docker via VirtualBox,
3532
// all files will be marked as executable, so skip checking.
3633
if contents.contains("Microsoft") || contents.contains("boot2docker") {

‎src/tools/tidy/src/cargo.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,7 @@
1515
//! `extern crate` declarations. This should help us keep the DAG correctly
1616
//! structured through various refactorings to prune out unnecessary edges.
1717
18-
use std::io::prelude::*;
19-
use std::fs::File;
18+
use std::fs;
2019
use std::path::Path;
2120

2221
pub fn check(path: &Path, bad: &mut bool) {
@@ -41,10 +40,8 @@ pub fn check(path: &Path, bad: &mut bool) {
4140
// Verify that the dependencies in Cargo.toml at `tomlfile` are sync'd with the
4241
// `extern crate` annotations in the lib.rs at `libfile`.
4342
fn verify(tomlfile: &Path, libfile: &Path, bad: &mut bool) {
44-
let mut toml = String::new();
45-
let mut librs = String::new();
46-
t!(t!(File::open(tomlfile)).read_to_string(&mut toml));
47-
t!(t!(File::open(libfile)).read_to_string(&mut librs));
43+
let toml = t!(fs::read_to_string(&tomlfile));
44+
let librs = t!(fs::read_to_string(&libfile));
4845

4946
if toml.contains("name = \"bootstrap\"") {
5047
return

‎src/tools/tidy/src/deps.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
//! Check license of third-party deps by inspecting vendor
1212
1313
use std::collections::{BTreeSet, HashSet, HashMap};
14-
use std::fs::File;
15-
use std::io::Read;
14+
use std::fs;
1615
use std::path::Path;
1716
use std::process::Command;
1817

@@ -262,8 +261,7 @@ fn check_license(path: &Path) -> bool {
262261
if !path.exists() {
263262
panic!("{} does not exist", path.display());
264263
}
265-
let mut contents = String::new();
266-
t!(t!(File::open(path)).read_to_string(&mut contents));
264+
let contents = t!(fs::read_to_string(&path));
267265

268266
let mut found_license = false;
269267
for line in contents.lines() {

‎src/tools/tidy/src/extdeps.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@
1010

1111
// ! Check for external package sources. Allow only vendorable packages.
1212

13-
use std::fs::File;
14-
use std::io::Read;
13+
use std::fs;
1514
use std::path::Path;
1615

1716
/// List of whitelisted sources for packages
@@ -25,8 +24,7 @@ pub fn check(path: &Path, bad: &mut bool) {
2524
let path = path.join("../Cargo.lock");
2625

2726
// open and read the whole file
28-
let mut cargo_lock = String::new();
29-
t!(t!(File::open(path)).read_to_string(&mut cargo_lock));
27+
let cargo_lock = t!(fs::read_to_string(&path));
3028

3129
// process each line
3230
for line in cargo_lock.lines() {

‎src/tools/tidy/src/features.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
2121
use std::collections::HashMap;
2222
use std::fmt;
23-
use std::fs::File;
23+
use std::fs::{self, File};
2424
use std::io::prelude::*;
2525
use std::path::Path;
2626

@@ -183,9 +183,7 @@ fn test_filen_gate(filen_underscore: &str, features: &mut Features) -> bool {
183183
}
184184

185185
pub fn collect_lang_features(base_src_path: &Path, bad: &mut bool) -> Features {
186-
let mut contents = String::new();
187-
let path = base_src_path.join("libsyntax/feature_gate.rs");
188-
t!(t!(File::open(path)).read_to_string(&mut contents));
186+
let contents = t!(fs::read_to_string(base_src_path.join("libsyntax/feature_gate.rs")));
189187

190188
// we allow rustc-internal features to omit a tracking issue.
191189
// these features must be marked with `// rustc internal` in its own group.

0 commit comments

Comments
 (0)
Please sign in to comment.