Skip to content

Commit

Permalink
Auto merge of #7580 - alexcrichton:less-unwrap, r=ehuss
Browse files Browse the repository at this point in the history
Don't panic when parsing `/proc/stat`

Use more robust error handling than `.unwrap()`!

Closes #7577
  • Loading branch information
bors committed Nov 11, 2019
2 parents 1292915 + 540fb9d commit 8280633
Showing 1 changed file with 19 additions and 19 deletions.
38 changes: 19 additions & 19 deletions src/cargo/util/cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,26 +45,26 @@ mod imp {
pub fn current() -> io::Result<State> {
let mut state = String::new();
File::open("/proc/stat")?.read_to_string(&mut state)?;
let mut parts = state.lines().next().unwrap().split_whitespace();
if parts.next() != Some("cpu") {
return Err(io::Error::new(
io::ErrorKind::Other,
"cannot parse /proc/stat",
));
}

Ok(State {
user: parts.next().unwrap().parse::<u64>().unwrap(),
nice: parts.next().unwrap().parse::<u64>().unwrap(),
system: parts.next().unwrap().parse::<u64>().unwrap(),
idle: parts.next().unwrap().parse::<u64>().unwrap(),
iowait: parts.next().unwrap().parse::<u64>().unwrap(),
irq: parts.next().unwrap().parse::<u64>().unwrap(),
softirq: parts.next().unwrap().parse::<u64>().unwrap(),
steal: parts.next().unwrap().parse::<u64>().unwrap(),
guest: parts.next().unwrap().parse::<u64>().unwrap(),
guest_nice: parts.next().unwrap().parse::<u64>().unwrap(),
})
(|| {
let mut parts = state.lines().next()?.split_whitespace();
if parts.next()? != "cpu" {
return None;
}
Some(State {
user: parts.next()?.parse::<u64>().ok()?,
nice: parts.next()?.parse::<u64>().ok()?,
system: parts.next()?.parse::<u64>().ok()?,
idle: parts.next()?.parse::<u64>().ok()?,
iowait: parts.next()?.parse::<u64>().ok()?,
irq: parts.next()?.parse::<u64>().ok()?,
softirq: parts.next()?.parse::<u64>().ok()?,
steal: parts.next()?.parse::<u64>().ok()?,
guest: parts.next()?.parse::<u64>().ok()?,
guest_nice: parts.next()?.parse::<u64>().ok()?,
})
})()
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "first line of /proc/stat malformed"))
}

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

0 comments on commit 8280633

Please sign in to comment.