Open fd in main()

main() now opens the NRG image, instead of letting parse_nrg_metadata()
do it.

parse_nrg_metadata() was renamed read_nrg_metadata().
This commit is contained in:
Matteo Cypriani 2016-12-06 14:31:51 -05:00
parent 423aec0a63
commit c3584042cc
2 changed files with 27 additions and 10 deletions

View File

@ -1,4 +1,5 @@
use std::env;
use std::fs::File;
use std::process;
extern crate nrgrip;
@ -27,10 +28,21 @@ fn main() {
exit_usage(&prog_name);
}
match nrgrip::metadata::parse_nrg_metadata(img_name) {
Err(err) => println!("{}", err.to_string()),
// Open the image file
let fd = File::open(&img_name);
if fd.is_err() {
println!("Can't open \"{}\": {}",
img_name, fd.unwrap_err().to_string());
process::exit(1);
}
let mut fd = fd.unwrap();
// Read the image's metadata
match nrgrip::metadata::read_nrg_metadata(&mut fd) {
Err(err) => println!("Error reading \"{}\": {}",
img_name, err.to_string()),
Ok(metadata) => println!("\n\
*** Metadata ***\n\
{}", metadata),
};
}
}

View File

@ -16,28 +16,33 @@ use self::metadata::NrgMetadata;
use self::readers::*;
pub fn parse_nrg_metadata(img_name: String) -> Result<NrgMetadata, NrgError> {
/// Reads the metadata chunks from an open NRG image file `fd`.
///
/// `fd`'s offset can be anywhere when this function is called: it will be reset
/// before anything is read.
///
/// In case of success, `fd`'s offset will be left after the "END!" string of
/// the NRG footer. Otherwise, the offset is undefined and should be reset by
/// the caller if any additional reading operations are to be done.
pub fn read_nrg_metadata(fd: &mut File) -> Result<NrgMetadata, NrgError> {
let mut nm = NrgMetadata::new();
// Open the image file
let mut fd = try!(File::open(img_name));
// Get the file size
nm.file_size = try!(fd.seek(SeekFrom::End(0)));
// Get the NRG format from the footer
nm.nrg_version = try!(read_nrg_version(&mut fd, nm.file_size));
nm.nrg_version = try!(read_nrg_version(fd, nm.file_size));
if nm.nrg_version != 2 {
// We handle only NRG v2
return Err(NrgError::NrgFormatV1);
}
// Read the first chunk offset
nm.chunk_offset = try!(read_u64(&mut fd));
nm.chunk_offset = try!(read_u64(fd));
// Read all the chunks
try!(fd.seek(SeekFrom::Start(nm.chunk_offset)));
try!(read_nrg_chunks(&mut fd, &mut nm));
try!(read_nrg_chunks(fd, &mut nm));
Ok(nm)
}