Skip to content

Commit

Permalink
Merge pull request #160 from pymongo/fix_warnings
Browse files Browse the repository at this point in the history
fix all warnings and some clippy lints
  • Loading branch information
eminence committed Nov 23, 2021
2 parents f6f227c + 70014d0 commit fc91e46
Show file tree
Hide file tree
Showing 13 changed files with 76 additions and 86 deletions.
2 changes: 1 addition & 1 deletion 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::<i32>().ok());

let prc = if let Some(pid) = pid {
println!("Info for pid={}", pid);
Expand Down
10 changes: 5 additions & 5 deletions examples/process_hierarchy.rs
Expand Up @@ -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);
}
}
}
Expand All @@ -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<Process>, 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(),
Expand All @@ -47,15 +47,15 @@ fn print_process(process: &Process, all_processes: &Vec<Process>, 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<Process>) -> 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()
}
15 changes: 5 additions & 10 deletions examples/shm.rs
@@ -1,5 +1,3 @@
#![allow(clippy::print_literal)]

extern crate procfs;

/// List processes using posix shared memory segments
Expand All @@ -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!();
}
}
38 changes: 18 additions & 20 deletions src/cpuinfo.rs
Expand Up @@ -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() {
Expand Down
38 changes: 20 additions & 18 deletions src/lib.rs
Expand Up @@ -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)]
Expand Down Expand Up @@ -134,7 +137,6 @@ impl<T, E> IntoResult<T, E> for Result<T, E> {
}
}

#[macro_use]
#[allow(unused_macros)]
macro_rules! proc_panic {
($e:expr) => {
Expand Down Expand Up @@ -171,7 +173,6 @@ macro_rules! expect {
};
}

#[macro_use]
macro_rules! from_str {
($t:tt, $e:expr) => {{
let e = $e;
Expand Down Expand Up @@ -483,13 +484,9 @@ impl From<std::io::Error> for ProcError {
fn from(io: std::io::Error) -> Self {
use std::io::ErrorKind;
let kind = io.kind();
let path: Option<PathBuf> = io.get_ref().and_then(|inner| {
if let Some(ref inner) = inner.downcast_ref::<IoErrorWrapper>() {
Some(inner.path.clone())
} else {
None
}
});
let path: Option<PathBuf> = io
.get_ref()
.and_then(|inner| inner.downcast_ref::<IoErrorWrapper>().map(|inner| inner.path.clone()));
match kind {
ErrorKind::PermissionDenied => ProcError::PermissionDenied(path),
ErrorKind::NotFound => ProcError::NotFound(path),
Expand Down Expand Up @@ -597,7 +594,10 @@ pub fn ticks_per_second() -> std::io::Result<i64> {
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")
Expand Down Expand Up @@ -653,8 +653,10 @@ pub fn page_size() -> std::io::Result<i64> {
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")
}
Expand Down Expand Up @@ -871,7 +873,7 @@ impl CpuTime {

/// Time spent waiting for I/O to complete
pub fn iowait_duration(&self) -> Option<Duration> {
self.iowait_ms().map(|io| Duration::from_millis(io))
self.iowait_ms().map(Duration::from_millis)
}

/// Milliseconds spent servicing interrupts
Expand All @@ -882,7 +884,7 @@ impl CpuTime {

/// Time spent servicing interrupts
pub fn irq_duration(&self) -> Option<Duration> {
self.irq_ms().map(|ms| Duration::from_millis(ms))
self.irq_ms().map(Duration::from_millis)
}

/// Milliseconds spent servicing softirqs
Expand All @@ -893,7 +895,7 @@ impl CpuTime {

/// Time spent servicing softirqs
pub fn softirq_duration(&self) -> Option<Duration> {
self.softirq_ms().map(|ms| Duration::from_millis(ms))
self.softirq_ms().map(Duration::from_millis)
}

/// Milliseconds of stolen time
Expand All @@ -904,7 +906,7 @@ impl CpuTime {

/// Amount of stolen time
pub fn steal_duration(&self) -> Option<Duration> {
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
Expand All @@ -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<Duration> {
self.guest_ms().map(|ms| Duration::from_millis(ms))
self.guest_ms().map(Duration::from_millis)
}

/// Milliseconds spent running a niced guest
Expand All @@ -926,7 +928,7 @@ impl CpuTime {

/// Time spent running a niced guest
pub fn guest_nice_duration(&self) -> Option<Duration> {
self.guest_nice_ms().map(|ms| Duration::from_millis(ms))
self.guest_nice_ms().map(Duration::from_millis)
}
}

Expand Down
5 changes: 2 additions & 3 deletions src/meminfo.rs
Expand Up @@ -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)
}
Expand All @@ -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
Expand Down
1 change: 0 additions & 1 deletion 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.
Expand Down
5 changes: 3 additions & 2 deletions src/pressure.rs
Expand Up @@ -97,14 +97,14 @@ impl IoPressure {
fn get_f32(map: &HashMap<&str, &str>, value: &str) -> ProcResult<f32> {
map.get(value).map_or_else(
|| Err(ProcError::Incomplete(None)),
|v| Ok(v.parse::<f32>().map_err(|_| ProcError::Incomplete(None))?),
|v| v.parse::<f32>().map_err(|_| ProcError::Incomplete(None)),
)
}

fn get_total(map: &HashMap<&str, &str>) -> ProcResult<u64> {
map.get("total").map_or_else(
|| Err(ProcError::Incomplete(None)),
|v| Ok(v.parse::<u64>().map_err(|_| ProcError::Incomplete(None))?),
|v| v.parse::<u64>().map_err(|_| ProcError::Incomplete(None)),
)
}

Expand Down Expand Up @@ -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
}
Expand Down
24 changes: 10 additions & 14 deletions src/process/mod.rs
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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::<u64>().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);
}
Expand Down Expand Up @@ -1260,7 +1258,7 @@ impl std::iter::Iterator for TasksIter {
fn next(&mut self) -> Option<ProcResult<Task>> {
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,
}
}
Expand All @@ -1279,14 +1277,12 @@ pub fn all_processes() -> ProcResult<Vec<Process>> {
pub fn all_processes_with_root(root: impl AsRef<Path>) -> ProcResult<Vec<Process>> {
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)),
_ => {}
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/process/mount.rs
Expand Up @@ -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;
Expand Down
12 changes: 6 additions & 6 deletions src/process/status.rs
Expand Up @@ -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")))?,
Expand Down

0 comments on commit fc91e46

Please sign in to comment.