Debian Codegraph @

.cargo/vendor/quick-error/examples/context.rs

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