Skip to content

Commit 8280633

Browse files
committed
Auto merge of #7580 - alexcrichton:less-unwrap, r=ehuss
Don't panic when parsing `/proc/stat` Use more robust error handling than `.unwrap()`! Closes #7577
2 parents 1292915 + 540fb9d commit 8280633

File tree

1 file changed

+19
-19
lines changed

1 file changed

+19
-19
lines changed

src/cargo/util/cpu.rs

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -45,26 +45,26 @@ mod imp {
4545
pub fn current() -> io::Result<State> {
4646
let mut state = String::new();
4747
File::open("/proc/stat")?.read_to_string(&mut state)?;
48-
let mut parts = state.lines().next().unwrap().split_whitespace();
49-
if parts.next() != Some("cpu") {
50-
return Err(io::Error::new(
51-
io::ErrorKind::Other,
52-
"cannot parse /proc/stat",
53-
));
54-
}
5548

56-
Ok(State {
57-
user: parts.next().unwrap().parse::<u64>().unwrap(),
58-
nice: parts.next().unwrap().parse::<u64>().unwrap(),
59-
system: parts.next().unwrap().parse::<u64>().unwrap(),
60-
idle: parts.next().unwrap().parse::<u64>().unwrap(),
61-
iowait: parts.next().unwrap().parse::<u64>().unwrap(),
62-
irq: parts.next().unwrap().parse::<u64>().unwrap(),
63-
softirq: parts.next().unwrap().parse::<u64>().unwrap(),
64-
steal: parts.next().unwrap().parse::<u64>().unwrap(),
65-
guest: parts.next().unwrap().parse::<u64>().unwrap(),
66-
guest_nice: parts.next().unwrap().parse::<u64>().unwrap(),
67-
})
49+
(|| {
50+
let mut parts = state.lines().next()?.split_whitespace();
51+
if parts.next()? != "cpu" {
52+
return None;
53+
}
54+
Some(State {
55+
user: parts.next()?.parse::<u64>().ok()?,
56+
nice: parts.next()?.parse::<u64>().ok()?,
57+
system: parts.next()?.parse::<u64>().ok()?,
58+
idle: parts.next()?.parse::<u64>().ok()?,
59+
iowait: parts.next()?.parse::<u64>().ok()?,
60+
irq: parts.next()?.parse::<u64>().ok()?,
61+
softirq: parts.next()?.parse::<u64>().ok()?,
62+
steal: parts.next()?.parse::<u64>().ok()?,
63+
guest: parts.next()?.parse::<u64>().ok()?,
64+
guest_nice: parts.next()?.parse::<u64>().ok()?,
65+
})
66+
})()
67+
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "first line of /proc/stat malformed"))
6868
}
6969

7070
pub fn pct_idle(prev: &State, next: &State) -> f64 {

0 commit comments

Comments
 (0)