Factor out the code for reading a file into a utility function.

This commit is contained in:
Dan Gohman
2017-10-03 09:09:48 -07:00
parent f064418652
commit ba14499fe9
2 changed files with 13 additions and 12 deletions

View File

@@ -20,6 +20,14 @@ pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
Ok(buffer) Ok(buffer)
} }
/// Read an entire file into a vector of bytes.
pub fn read_to_end<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
let mut file = File::open(path)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
Ok(buffer)
}
/// Look for a directive in a comment string. /// Look for a directive in a comment string.
/// The directive is of the form "foo:" and should follow the leading `;` in the comment: /// The directive is of the form "foo:" and should follow the leading `;` in the comment:
/// ///

View File

@@ -16,7 +16,7 @@ use std::path::Path;
use std::process::Command; use std::process::Command;
use tempdir::TempDir; use tempdir::TempDir;
use term; use term;
use utils::{pretty_verifier_error, pretty_error, parse_sets_and_isa}; use utils::{pretty_verifier_error, pretty_error, parse_sets_and_isa, read_to_end};
macro_rules! vprintln { macro_rules! vprintln {
($x: expr, $($tts:tt)*) => { ($x: expr, $($tts:tt)*) => {
@@ -34,13 +34,6 @@ macro_rules! vprint {
} }
} }
fn read_wasm_file(path: PathBuf) -> Result<Vec<u8>, io::Error> {
let mut buf: Vec<u8> = Vec::new();
let mut file = File::open(path)?;
file.read_to_end(&mut buf)?;
Ok(buf)
}
pub fn run( pub fn run(
files: Vec<String>, files: Vec<String>,
flag_verbose: bool, flag_verbose: bool,
@@ -92,7 +85,7 @@ fn handle_module(
Some(ext) => { Some(ext) => {
match ext.to_str() { match ext.to_str() {
Some("wasm") => { Some("wasm") => {
read_wasm_file(path.clone()).map_err(|err| { read_to_end(path.clone()).map_err(|err| {
String::from(err.description()) String::from(err.description())
})? })?
} }
@@ -110,9 +103,9 @@ fn handle_module(
} else { } else {
return Err(String::from(e.description())); return Err(String::from(e.description()));
})?; })?;
read_wasm_file(file_path).map_err(|err| { read_to_end(file_path).map_err(
String::from(err.description()) |err| String::from(err.description()),
})? )?
} }
None | Some(&_) => { None | Some(&_) => {
return Err(String::from("the file extension is not wasm or wat")); return Err(String::from("the file extension is not wasm or wat"));