getting rusty

It has been a little while, and I have been distracted from this project. Never the less, here is the next challenge solution; I tried to take advantage of more of the built in safety features provided by Rust, but I am still using/abusing unwrap here and there.

extern crate zip;
extern crate regex;
use std::io::Read;
use std::io::prelude::*;

fn main() {
    let args: Vec<_> = std::env::args().collect();
    if args.len() < 2 {
        println!("Usage: {} <filename>", args[0]);
        return;
    }
    let fname = std::path::Path::new(&*args[1]);
    match std::fs::File::open(fname) {
        Err(e) => panic!("file read error: {}", e),
        Ok(f) => {

            let mut archive = zip::ZipArchive::new(f).unwrap();
            
            let mut znum: i32 = 90052;
            let re = regex::Regex::new("ext nothing is ([[:digit:]]+)").unwrap();

            loop {
                let mut sub = String::new();
                let zfname = format!("{}.txt", znum.to_string());
                let response = read_zip(&mut archive, zfname);
                match re.captures(&response.as_str()) {
                    Some(c) => sub = c.get(1).map_or("0", |m| m.as_str()).to_string(),
                    None => (),
                };
                match sub.parse::<i32>() {
                    Ok(v) => znum = v,
                    Err(_) => break
                };
            }
        }
    }

}

fn read_zip<R: Read + Seek>(archive: &mut zip::read::ZipArchive<R>,
                            filename: String) -> String {
    let zf  = archive.by_name(&filename).unwrap();
    print!("{}", zf.comment());

    let zb: Vec<_> = zf.bytes().map(|b| b).filter_map(Result::ok).collect();
    let s = match std::str::from_utf8(&zb) {
        Ok(v) => v,
        Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
    };
    return s.to_string()
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s