diff --git a/examples/dump.rs b/examples/dump.rs index d6d06f4b..6300a94b 100644 --- a/examples/dump.rs +++ b/examples/dump.rs @@ -1,7 +1,7 @@ extern crate procfs; fn main() { - let pid = std::env::args().nth(1).and_then(|s| i32::from_str_radix(&s, 10).ok()); + let pid = std::env::args().nth(1).and_then(|s| s.parse::().ok()); let prc = if let Some(pid) = pid { println!("Info for pid={}", pid); diff --git a/examples/process_hierarchy.rs b/examples/process_hierarchy.rs index 963b2888..5d7ebbee 100644 --- a/examples/process_hierarchy.rs +++ b/examples/process_hierarchy.rs @@ -16,7 +16,7 @@ fn main() { // Those can be identified by checking if their parent PID is zero. for process in &processes { if process.stat.ppid == 0 { - print_process(&process, &processes, 0); + print_process(process, &processes, 0); } } } @@ -26,7 +26,7 @@ fn main() { /// It's a depth-first tree exploration. /// /// depth: The hierarchical depth of the process -fn print_process(process: &Process, all_processes: &Vec, depth: usize) { +fn print_process(process: &Process, all_processes: &[Process], depth: usize) { let cmdline = match process.cmdline() { Ok(cmdline) => cmdline.join(" "), Err(_) => "zombie process".into(), @@ -47,15 +47,15 @@ fn print_process(process: &Process, all_processes: &Vec, depth: usize) let children = get_children(process.pid, all_processes); for child in &children { - print_process(child, &all_processes, depth + 1); + print_process(child, all_processes, depth + 1); } } /// Get all children of a specific process, by iterating through all processes and /// checking their parent pid. -pub fn get_children(pid: i32, all_processes: &Vec) -> Vec<&Process> { +pub fn get_children(pid: i32, all_processes: &[Process]) -> Vec<&Process> { all_processes - .into_iter() + .iter() .filter(|process| process.stat.ppid == pid) .collect() } diff --git a/examples/shm.rs b/examples/shm.rs index 5123681e..02df14cd 100644 --- a/examples/shm.rs +++ b/examples/shm.rs @@ -1,5 +1,3 @@ -#![allow(clippy::print_literal)] - extern crate procfs; /// List processes using posix shared memory segments @@ -14,20 +12,17 @@ fn main() { for prc in procfs::process::all_processes().unwrap() { match prc.smaps() { Ok(memory_maps) => { - for (memory_map, memory_map_data) in &memory_maps { - match memory_map.pathname { - procfs::process::MMapPath::Vsys(key) => { - if key == shared_memory.key && memory_map.inode == shared_memory.shmid { - println!("{}: {:?}", prc.pid, prc.cmdline().unwrap()); - } + for (memory_map, _memory_map_data) in &memory_maps { + if let procfs::process::MMapPath::Vsys(key) = memory_map.pathname { + if key == shared_memory.key && memory_map.inode == shared_memory.shmid { + println!("{}: {:?}", prc.pid, prc.cmdline().unwrap()); } - _ => (), } } } Err(_) => continue, } } - println!(""); + println!(); } } diff --git a/src/cpuinfo.rs b/src/cpuinfo.rs index d96c373c..cb161a73 100644 --- a/src/cpuinfo.rs +++ b/src/cpuinfo.rs @@ -30,27 +30,25 @@ impl CpuInfo { // the first line of a cpu block must start with "processor" let mut found_first = false; - for line in reader.lines() { - if let Ok(line) = line { - if !line.is_empty() { - let mut s = line.split(':'); - let key = expect!(s.next()); - if !found_first && key.trim() == "processor" { - found_first = true; - } - if !found_first { - continue; - } - if let Some(value) = s.next() { - let key = key.trim().to_owned(); - let value = value.trim().to_owned(); - - map.get_or_insert(HashMap::new()).insert(key, value); - } - } else if let Some(map) = map.take() { - list.push(map); - found_first = false; + for line in reader.lines().flatten() { + if !line.is_empty() { + let mut s = line.split(':'); + let key = expect!(s.next()); + if !found_first && key.trim() == "processor" { + found_first = true; } + if !found_first { + continue; + } + if let Some(value) = s.next() { + let key = key.trim().to_owned(); + let value = value.trim().to_owned(); + + map.get_or_insert(HashMap::new()).insert(key, value); + } + } else if let Some(map) = map.take() { + list.push(map); + found_first = false; } } if let Some(map) = map.take() { diff --git a/src/lib.rs b/src/lib.rs index f7950e0e..dfde991e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,9 @@ // The suggested fix with `strip_prefix` removes support for Rust 1.33 and 1.38 #![allow(clippy::unknown_clippy_lints)] #![allow(clippy::manual_strip)] +#![allow(clippy::from_str_radix_10)] +// `#[non_exhaustive]` require Rust 1.40+ but procfs minimal Rust version is 1.34 +#![allow(clippy::manual_non_exhaustive)] // Don't throw rustc lint warnings for the deprecated name `intra_doc_link_resolution_failure`. // The suggested rename to `broken_intra_doc_links` removes support for Rust 1.33 and 1.38. #![allow(renamed_and_removed_lints)] @@ -134,7 +137,6 @@ impl IntoResult for Result { } } -#[macro_use] #[allow(unused_macros)] macro_rules! proc_panic { ($e:expr) => { @@ -171,7 +173,6 @@ macro_rules! expect { }; } -#[macro_use] macro_rules! from_str { ($t:tt, $e:expr) => {{ let e = $e; @@ -483,13 +484,9 @@ impl From for ProcError { fn from(io: std::io::Error) -> Self { use std::io::ErrorKind; let kind = io.kind(); - let path: Option = io.get_ref().and_then(|inner| { - if let Some(ref inner) = inner.downcast_ref::() { - Some(inner.path.clone()) - } else { - None - } - }); + let path: Option = io + .get_ref() + .and_then(|inner| inner.downcast_ref::().map(|inner| inner.path.clone())); match kind { ErrorKind::PermissionDenied => ProcError::PermissionDenied(path), ErrorKind::NotFound => ProcError::NotFound(path), @@ -597,7 +594,10 @@ pub fn ticks_per_second() -> std::io::Result { if cfg!(unix) { match unsafe { sysconf(_SC_CLK_TCK) } { -1 => Err(std::io::Error::last_os_error()), - x => Ok(x.into()), + #[cfg(target_pointer_width = "64")] + x => Ok(x), + #[cfg(target_pointer_width = "32")] + x => Ok(x.into()) } } else { panic!("Not supported on non-unix platforms") @@ -653,8 +653,10 @@ pub fn page_size() -> std::io::Result { if cfg!(unix) { match unsafe { sysconf(_SC_PAGESIZE) } { -1 => Err(std::io::Error::last_os_error()), - x => Ok(x.into()), - } + #[cfg(target_pointer_width = "64")] + x => Ok(x), + #[cfg(target_pointer_width = "32")] + x => Ok(x.into()) } } else { panic!("Not supported on non-unix platforms") } @@ -871,7 +873,7 @@ impl CpuTime { /// Time spent waiting for I/O to complete pub fn iowait_duration(&self) -> Option { - self.iowait_ms().map(|io| Duration::from_millis(io)) + self.iowait_ms().map(Duration::from_millis) } /// Milliseconds spent servicing interrupts @@ -882,7 +884,7 @@ impl CpuTime { /// Time spent servicing interrupts pub fn irq_duration(&self) -> Option { - self.irq_ms().map(|ms| Duration::from_millis(ms)) + self.irq_ms().map(Duration::from_millis) } /// Milliseconds spent servicing softirqs @@ -893,7 +895,7 @@ impl CpuTime { /// Time spent servicing softirqs pub fn softirq_duration(&self) -> Option { - self.softirq_ms().map(|ms| Duration::from_millis(ms)) + self.softirq_ms().map(Duration::from_millis) } /// Milliseconds of stolen time @@ -904,7 +906,7 @@ impl CpuTime { /// Amount of stolen time pub fn steal_duration(&self) -> Option { - self.steal_ms().map(|ms| Duration::from_millis(ms)) + self.steal_ms().map(Duration::from_millis) } /// Milliseconds spent running a virtual CPU for guest operating systems under control of the linux kernel @@ -915,7 +917,7 @@ impl CpuTime { /// Time spent running a virtual CPU for guest operating systems under control of the linux kernel pub fn guest_duration(&self) -> Option { - self.guest_ms().map(|ms| Duration::from_millis(ms)) + self.guest_ms().map(Duration::from_millis) } /// Milliseconds spent running a niced guest @@ -926,7 +928,7 @@ impl CpuTime { /// Time spent running a niced guest pub fn guest_nice_duration(&self) -> Option { - self.guest_nice_ms().map(|ms| Duration::from_millis(ms)) + self.guest_nice_ms().map(Duration::from_millis) } } diff --git a/src/meminfo.rs b/src/meminfo.rs index 56f01348..4a6e0670 100644 --- a/src/meminfo.rs +++ b/src/meminfo.rs @@ -382,9 +382,7 @@ impl Meminfo { file_huge_pages: map.remove("FileHugePages"), }; - if cfg!(test) && !map.is_empty() { - panic!("meminfo map is not empty: {:#?}", map); - } + assert!(!(cfg!(test) && !map.is_empty()), "meminfo map is not empty: {:#?}", map); Ok(meminfo) } @@ -396,6 +394,7 @@ mod test { use crate::{kernel_config, KernelVersion}; #[allow(clippy::cognitive_complexity)] + #[allow(clippy::blocks_in_if_conditions)] #[test] fn test_meminfo() { // TRAVIS diff --git a/src/net.rs b/src/net.rs index 48504986..177a1e8a 100644 --- a/src/net.rs +++ b/src/net.rs @@ -1,6 +1,5 @@ // Don't throw clippy warnings for manual string stripping. // The suggested fix with `strip_prefix` removes support for Rust 1.33 and 1.38 -#![allow(clippy::unknown_clippy_lints)] #![allow(clippy::manual_strip)] //! Information about the networking layer. diff --git a/src/pressure.rs b/src/pressure.rs index 1776e567..5e2d8295 100644 --- a/src/pressure.rs +++ b/src/pressure.rs @@ -97,14 +97,14 @@ impl IoPressure { fn get_f32(map: &HashMap<&str, &str>, value: &str) -> ProcResult { map.get(value).map_or_else( || Err(ProcError::Incomplete(None)), - |v| Ok(v.parse::().map_err(|_| ProcError::Incomplete(None))?), + |v| v.parse::().map_err(|_| ProcError::Incomplete(None)), ) } fn get_total(map: &HashMap<&str, &str>) -> ProcResult { map.get("total").map_or_else( || Err(ProcError::Incomplete(None)), - |v| Ok(v.parse::().map_err(|_| ProcError::Incomplete(None))?), + |v| v.parse::().map_err(|_| ProcError::Incomplete(None)), ) } @@ -154,6 +154,7 @@ mod test { use std::f32::EPSILON; use std::path::Path; + #[allow(clippy::manual_range_contains)] fn valid_percentage(value: f32) -> bool { value >= 0.00 && value < 100.0 } diff --git a/src/process/mod.rs b/src/process/mod.rs index fa55458f..7b4bd714 100644 --- a/src/process/mod.rs +++ b/src/process/mod.rs @@ -596,9 +596,7 @@ impl Io { cancelled_write_bytes: expect!(map.remove("cancelled_write_bytes")), }; - if cfg!(test) && !map.is_empty() { - panic!("io map is not empty: {:#?}", map); - } + assert!(!(cfg!(test) && !map.is_empty()), "io map is not empty: {:#?}", map); Ok(io) } @@ -952,14 +950,14 @@ impl Process { // supposedly responsible for creating smaps, has lead me to believe that the only size suffixes we'll ever encounter // "kB", which is most likely kibibytes. Actually checking if the size suffix is any of the above is a way to // future-proof the code, but I am not sure it is worth doing so. - let size_multiplier = if let Some(_) = size_suffix { 1024 } else { 1 }; + let size_multiplier = if size_suffix.is_some() { 1024 } else { 1 }; let v = v.parse::().map_err(|_| { ProcError::Other("Value in `Key: Value` pair was not actually a number".into()) })?; // This ignores the case when our Key: Value pairs are really Key Value pairs. Is this a good idea? - let k = k.trim_end_matches(":"); + let k = k.trim_end_matches(':'); current_data.map.insert(k.into(), v * size_multiplier); } @@ -1260,7 +1258,7 @@ impl std::iter::Iterator for TasksIter { fn next(&mut self) -> Option> { match self.inner.next() { Some(Ok(tp)) => Some(Task::from_rel_path(self.pid, &tp.path())), - Some(Err(e)) => Some(Err(ProcError::Io(e.into(), None))), + Some(Err(e)) => Some(Err(ProcError::Io(e, None))), None => None, } } @@ -1279,14 +1277,12 @@ pub fn all_processes() -> ProcResult> { pub fn all_processes_with_root(root: impl AsRef) -> ProcResult> { let mut v = Vec::new(); let root = root.as_ref(); - for dir in expect!(std::fs::read_dir(root), format!("No {} directory", root.display())) { - if let Ok(entry) = dir { - if i32::from_str(&entry.file_name().to_string_lossy()).is_ok() { - match Process::new_with_root(entry.path()) { - Ok(prc) => v.push(prc), - Err(ProcError::InternalError(e)) => return Err(ProcError::InternalError(e)), - _ => {} - } + for entry in expect!(std::fs::read_dir(root), format!("No {} directory", root.display())).flatten() { + if i32::from_str(&entry.file_name().to_string_lossy()).is_ok() { + match Process::new_with_root(entry.path()) { + Ok(prc) => v.push(prc), + Err(ProcError::InternalError(e)) => return Err(ProcError::InternalError(e)), + _ => {} } } } diff --git a/src/process/mount.rs b/src/process/mount.rs index 9deb3152..fc1e1c6a 100644 --- a/src/process/mount.rs +++ b/src/process/mount.rs @@ -323,9 +323,9 @@ impl MountNFSStatistics { } else if line.starts_with("sec:") { sec = Some(line[4..].trim().split(',').map(|s| s.to_string()).collect()); } else if line.starts_with("bytes:") { - bytes = Some(NFSByteCounter::from_str(&line[6..].trim())?); + bytes = Some(NFSByteCounter::from_str(line[6..].trim())?); } else if line.starts_with("events:") { - events = Some(NFSEventCounter::from_str(&line[7..].trim())?); + events = Some(NFSEventCounter::from_str(line[7..].trim())?); } if line == "per-op statistics" { parsing_per_op = true; diff --git a/src/process/status.rs b/src/process/status.rs index 5500421e..596b16e2 100644 --- a/src/process/status.rs +++ b/src/process/status.rs @@ -201,13 +201,13 @@ impl Status { pid: from_str!(i32, &expect!(map.remove("Pid"))), ppid: from_str!(i32, &expect!(map.remove("PPid"))), tracerpid: from_str!(i32, &expect!(map.remove("TracerPid"))), - ruid: expect!(Status::parse_uid_gid(&expect!(map.get("Uid")), 0)), - euid: expect!(Status::parse_uid_gid(&expect!(map.get("Uid")), 1)), - suid: expect!(Status::parse_uid_gid(&expect!(map.get("Uid")), 2)), + ruid: expect!(Status::parse_uid_gid(expect!(map.get("Uid")), 0)), + euid: expect!(Status::parse_uid_gid(expect!(map.get("Uid")), 1)), + suid: expect!(Status::parse_uid_gid(expect!(map.get("Uid")), 2)), fuid: expect!(Status::parse_uid_gid(&expect!(map.remove("Uid")), 3)), - rgid: expect!(Status::parse_uid_gid(&expect!(map.get("Gid")), 0)), - egid: expect!(Status::parse_uid_gid(&expect!(map.get("Gid")), 1)), - sgid: expect!(Status::parse_uid_gid(&expect!(map.get("Gid")), 2)), + rgid: expect!(Status::parse_uid_gid(expect!(map.get("Gid")), 0)), + egid: expect!(Status::parse_uid_gid(expect!(map.get("Gid")), 1)), + sgid: expect!(Status::parse_uid_gid(expect!(map.get("Gid")), 2)), fgid: expect!(Status::parse_uid_gid(&expect!(map.remove("Gid")), 3)), fdsize: from_str!(u32, &expect!(map.remove("FDSize"))), groups: Status::parse_list(&expect!(map.remove("Groups")))?, diff --git a/src/sys/fs/binfmt_misc.rs b/src/sys/fs/binfmt_misc.rs index 17cafb7f..deae34bd 100644 --- a/src/sys/fs/binfmt_misc.rs +++ b/src/sys/fs/binfmt_misc.rs @@ -85,7 +85,7 @@ impl BinFmtEntry { } } - if magic.len() > 0 && mask.len() == 0 { + if !magic.is_empty() && mask.is_empty() { mask.resize(magic.len(), 0xff); } @@ -236,7 +236,7 @@ offset 12 magic 7f454c460201010000000000000000000200f300 mask ffffffffffffff00fffffffffffffffffeffffff"#; - let entry = BinFmtEntry::from_string("test".to_owned(), &data).unwrap(); + let entry = BinFmtEntry::from_string("test".to_owned(), data).unwrap(); println!("{:#?}", entry); assert_eq!(entry.flags, BinFmtFlags::F | BinFmtFlags::C | BinFmtFlags::O); assert!(entry.enabled); @@ -259,7 +259,7 @@ mask ffffffffffffff00fffffffffffffffffeffffff"#; interpreter /bin/hello flags: extension .hello"#; - let entry = BinFmtEntry::from_string("test".to_owned(), &data).unwrap(); + let entry = BinFmtEntry::from_string("test".to_owned(), data).unwrap(); println!("{:#?}", entry); assert_eq!(entry.flags, BinFmtFlags::empty()); assert!(entry.enabled); diff --git a/src/sys/kernel/mod.rs b/src/sys/kernel/mod.rs index 570b1052..1de721d7 100644 --- a/src/sys/kernel/mod.rs +++ b/src/sys/kernel/mod.rs @@ -104,7 +104,7 @@ impl cmp::Ord for Version { impl cmp::PartialOrd for Version { fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(&other)) + Some(self.cmp(other)) } }