1 #[macro_use(quick_error)] extern crate quick_error;
2 
3 use std::io::{self, stderr, Read, Write};
4 use std::fs::File;
5 use std::env;
6 use std::num::ParseIntError;
7 use std::path::{Path, PathBuf};
8 
9 use quick_error::ResultExt;
10 
11 quick_error! {
12     #[derive(Debug)]
13     pub enum Error {
14         NoFileName {
15             description("no file name specified")
16         }
17         Io(err: io::Error, path: PathBuf) {
18             display("could not read file {:?}: {}", path, err)
19             context(path: &'a Path, err: io::Error)
20                 -> (err, path.to_path_buf())
21         }
22         Parse(err: ParseIntError, path: PathBuf) {
23             display("could not parse file {:?}: {}", path, err)
24             context(path: &'a Path, err: ParseIntError)
25                 -> (err, path.to_path_buf())
26         }
27     }
28 }
29 
parse_file() -> Result<u64, Error>30 fn parse_file() -> Result<u64, Error> {
31     let fname = try!(env::args().skip(1).next().ok_or(Error::NoFileName));
32     let fname = Path::new(&fname);
33     let mut file = try!(File::open(fname).context(fname));
34     let mut buf = String::new();
35     try!(file.read_to_string(&mut buf).context(fname));
36     Ok(try!(buf.parse().context(fname)))
37 }
38 
main()39 fn main() {
40     match parse_file() {
41         Ok(val) => {
42             println!("Read: {}", val);
43         }
44         Err(e) => {
45             writeln!(&mut stderr(), "Error: {}", e).ok();
46         }
47     }
48 }
49