Skip to content

Instantly share code, notes, and snippets.

@derrickturk
Created January 24, 2015 19:37
Show Gist options
  • Save derrickturk/a0997e5ea93ea39381c1 to your computer and use it in GitHub Desktop.
Save derrickturk/a0997e5ea93ea39381c1 to your computer and use it in GitHub Desktop.
Binary I/O in Rust
#![allow(unstable)]
use std::os;
use std::io;
use std::io::stdio;
use std::result;
use std::str::StrExt;
struct Record {
filename: String,
stage_num: u32,
data: Vec<(f64, f64)>
}
fn read_header<T: io::Buffer>(reader: &mut T) -> io::IoResult<Vec<String>> {
let mut res = Vec::new();
match result::fold(reader.lines(), (),
|_, string| res.push(String::from_str(string.trim_right()))) {
Ok(_) => Ok(res),
Err(e) => Err(e)
}
}
fn read_binary<T: io::Reader>(header: &Vec<String>, reader: &mut T)
-> io::IoResult<Vec<Record>> {
let mut res = Vec::new();
loop {
let rec = read_record(header, reader);
match rec {
Ok(record) => res.push(record),
Err(io::IoError { kind: io::IoErrorKind::EndOfFile, .. }) => return Ok(res),
Err(e) => return Err(e),
}
}
}
fn read_record<T: io::Reader>(header: &Vec<String>, reader: &mut T)
-> io::IoResult<Record> {
let fnum = try!(reader.read_le_u32());
if fnum as usize > header.len() {
return Err(io::IoError {
kind: io::IoErrorKind::InvalidInput,
desc: "Invalid index into header file.",
detail: None
});
}
let stage_num = try!(reader.read_le_u32());
let data_length = try!(reader.read_le_u32().map(|l| l / 2));
let mut data: Vec<(f64, f64)> =
Vec::with_capacity(data_length as usize);
for _ in range(0u32, data_length) {
let first = reader.read_le_f64();
if first.is_err() { return Err(first.unwrap_err()); }
let second = reader.read_le_f64();
if second.is_err() { return Err(second.unwrap_err()); }
data.push((first.unwrap(), second.unwrap()));
}
return Ok(Record {
filename: header[fnum as usize].clone(),
stage_num: stage_num,
data: data
});
}
fn main() {
if os::args().len() != 3 {
if os::args().len() < 1 {
let _ = writeln!(&mut stdio::stderr(),
"Usage: readbin <bin-file> <hdr-file>");
} else {
let _ = writeln!(&mut stdio::stderr(),
"Usage: {} <bin-file> <hdr-file>\n", os::args()[0]);
}
return;
}
let binfile = io::File::open(&Path::new(&os::args()[1][])).unwrap();
let hdrfile = io::File::open(&Path::new(&os::args()[2][])).unwrap();
let hdr = read_header(&mut io::BufferedReader::new(hdrfile)).unwrap();
let records = read_binary(&hdr, &mut io::BufferedReader::new(binfile))
.unwrap();
println!("File\tStage\tX\tY");
for rec in records.iter() {
for &(x, y) in rec.data.iter() {
println!("{}\t{}\t{}\t{}",
rec.filename, rec.stage_num, x, y);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment