From 540fb9dd833c9f7651d84e9ff5e3ef530ed7b014 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 11 Nov 2019 09:39:57 -0800 Subject: [PATCH] Don't panic when parsing `/proc/stat` Use more robust error handling than `.unwrap()`! Closes #7577 --- src/cargo/util/cpu.rs | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/cargo/util/cpu.rs b/src/cargo/util/cpu.rs index 453eb571906..6d462c231b3 100644 --- a/src/cargo/util/cpu.rs +++ b/src/cargo/util/cpu.rs @@ -45,26 +45,26 @@ mod imp { pub fn current() -> io::Result { 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::().unwrap(), - nice: parts.next().unwrap().parse::().unwrap(), - system: parts.next().unwrap().parse::().unwrap(), - idle: parts.next().unwrap().parse::().unwrap(), - iowait: parts.next().unwrap().parse::().unwrap(), - irq: parts.next().unwrap().parse::().unwrap(), - softirq: parts.next().unwrap().parse::().unwrap(), - steal: parts.next().unwrap().parse::().unwrap(), - guest: parts.next().unwrap().parse::().unwrap(), - guest_nice: parts.next().unwrap().parse::().unwrap(), - }) + (|| { + let mut parts = state.lines().next()?.split_whitespace(); + if parts.next()? != "cpu" { + return None; + } + Some(State { + user: parts.next()?.parse::().ok()?, + nice: parts.next()?.parse::().ok()?, + system: parts.next()?.parse::().ok()?, + idle: parts.next()?.parse::().ok()?, + iowait: parts.next()?.parse::().ok()?, + irq: parts.next()?.parse::().ok()?, + softirq: parts.next()?.parse::().ok()?, + steal: parts.next()?.parse::().ok()?, + guest: parts.next()?.parse::().ok()?, + guest_nice: parts.next()?.parse::().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 {