diff --git a/src/blkio.rs b/src/blkio.rs index 457dceb..a399697 100644 --- a/src/blkio.rs +++ b/src/blkio.rs @@ -84,14 +84,14 @@ pub struct IoStat { fn parse_io_service(s: String) -> Result> { s.lines() - .filter(|x| x.split_whitespace().collect::>().len() == 3) + .filter(|x| x.split_whitespace().count() == 3) .map(|x| { let mut spl = x.split_whitespace(); - (spl.nth(0).unwrap(), spl.nth(0).unwrap(), spl.nth(0).unwrap()) + (spl.next().unwrap(), spl.next().unwrap(), spl.next().unwrap()) }) .map(|(a, b, c)| { - let mut spl = a.split(":"); - (spl.nth(0).unwrap(), spl.nth(0).unwrap(), b, c) + let mut spl = a.split(':'); + (spl.next().unwrap(), spl.next().unwrap(), b, c) }) .collect::>() .chunks(5) @@ -131,15 +131,14 @@ fn get_value(s: &str) -> String { arr[1].to_string() } -fn parse_io_stat(s: String) -> Result> { +fn parse_io_stat(s: String) -> Vec { // line: // 8:0 rbytes=180224 wbytes=0 rios=3 wios=0 dbytes=0 dios=0 - let v = s - .lines() - .filter(|x| x.split_whitespace().collect::>().len() == 7) + s.lines() + .filter(|x| x.split_whitespace().count() == 7) .map(|x| { let arr = x.split_whitespace().collect::>(); - let device = arr[0].split(":").collect::>(); + let device = arr[0].split(':').collect::>(); let (major, minor) = (device[0], device[1]); IoStat { @@ -153,14 +152,12 @@ fn parse_io_stat(s: String) -> Result> { dios: get_value(arr[6]).parse::().unwrap(), } }) - .collect::>(); - - Ok(v) + .collect::>() } fn parse_io_service_total(s: String) -> Result { s.lines() - .filter(|x| x.split_whitespace().collect::>().len() == 2) + .filter(|x| x.split_whitespace().count() == 2) .fold(Err(Error::new(ParseError)), |_, x| { match x.split_whitespace().collect::>().as_slice() { ["Total", val] => val.parse::().map_err(|_| Error::new(ParseError)), @@ -197,9 +194,9 @@ fn parse_blkio_data(s: String) -> Result> { }); if err.is_err() { - return Err(Error::new(ParseError)); + Err(Error::new(ParseError)) } else { - return Ok(res); + Ok(res) } } @@ -407,19 +404,19 @@ impl BlkIoController { Self { base: root.clone(), path: root, - v2: v2, + v2, } } fn blkio_v2(&self) -> BlkIo { - let mut blkio: BlkIo = Default::default(); - blkio.io_stat = self - .open_path("io.stat", false) - .and_then(read_string_from) - .and_then(parse_io_stat) - .unwrap_or(Vec::new()); - - blkio + BlkIo { + io_stat: self + .open_path("io.stat", false) + .and_then(read_string_from) + .map(parse_io_stat) + .unwrap_or_default(), + ..Default::default() + } } /// Gathers statistics about and reports the state of the block devices used by the control @@ -433,222 +430,222 @@ impl BlkIoController { .open_path("blkio.io_merged", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_merged_total: self .open_path("blkio.io_merged", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_merged_recursive: self .open_path("blkio.io_merged_recursive", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_merged_recursive_total: self .open_path("blkio.io_merged_recursive", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_queued: self .open_path("blkio.io_queued", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_queued_total: self .open_path("blkio.io_queued", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_queued_recursive: self .open_path("blkio.io_queued_recursive", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_queued_recursive_total: self .open_path("blkio.io_queued_recursive", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_service_bytes: self .open_path("blkio.io_service_bytes", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_service_bytes_total: self .open_path("blkio.io_service_bytes", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_service_bytes_recursive: self .open_path("blkio.io_service_bytes_recursive", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_service_bytes_recursive_total: self .open_path("blkio.io_service_bytes_recursive", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_serviced: self .open_path("blkio.io_serviced", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_serviced_total: self .open_path("blkio.io_serviced", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_serviced_recursive: self .open_path("blkio.io_serviced_recursive", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_serviced_recursive_total: self .open_path("blkio.io_serviced_recursive", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_service_time: self .open_path("blkio.io_service_time", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_service_time_total: self .open_path("blkio.io_service_time", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_service_time_recursive: self .open_path("blkio.io_service_time_recursive", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_service_time_recursive_total: self .open_path("blkio.io_service_time_recursive", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_wait_time: self .open_path("blkio.io_wait_time", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_wait_time_total: self .open_path("blkio.io_wait_time", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_wait_time_recursive: self .open_path("blkio.io_wait_time_recursive", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_wait_time_recursive_total: self .open_path("blkio.io_wait_time_recursive", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), leaf_weight: self .open_path("blkio.leaf_weight", false) - .and_then(|file| read_u64_from(file)) + .and_then(read_u64_from) .unwrap_or(0u64), leaf_weight_device: self .open_path("blkio.leaf_weight_device", false) .and_then(read_string_from) .and_then(parse_blkio_data) - .unwrap_or(Vec::new()), + .unwrap_or_default(), sectors: self .open_path("blkio.sectors", false) .and_then(read_string_from) .and_then(parse_blkio_data) - .unwrap_or(Vec::new()), + .unwrap_or_default(), sectors_recursive: self .open_path("blkio.sectors_recursive", false) .and_then(read_string_from) .and_then(parse_blkio_data) - .unwrap_or(Vec::new()), + .unwrap_or_default(), throttle: BlkIoThrottle { io_service_bytes: self .open_path("blkio.throttle.io_service_bytes", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_service_bytes_total: self .open_path("blkio.throttle.io_service_bytes", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_service_bytes_recursive: self .open_path("blkio.throttle.io_service_bytes_recursive", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_service_bytes_recursive_total: self .open_path("blkio.throttle.io_service_bytes_recursive", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_serviced: self .open_path("blkio.throttle.io_serviced", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_serviced_total: self .open_path("blkio.throttle.io_serviced", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), io_serviced_recursive: self .open_path("blkio.throttle.io_serviced_recursive", false) .and_then(read_string_from) .and_then(parse_io_service) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_serviced_recursive_total: self .open_path("blkio.throttle.io_serviced_recursive", false) .and_then(read_string_from) .and_then(parse_io_service_total) - .unwrap_or(0), + .unwrap_or_default(), read_bps_device: self .open_path("blkio.throttle.read_bps_device", false) .and_then(read_string_from) .and_then(parse_blkio_data) - .unwrap_or(Vec::new()), + .unwrap_or_default(), read_iops_device: self .open_path("blkio.throttle.read_iops_device", false) .and_then(read_string_from) .and_then(parse_blkio_data) - .unwrap_or(Vec::new()), + .unwrap_or_default(), write_bps_device: self .open_path("blkio.throttle.write_bps_device", false) .and_then(read_string_from) .and_then(parse_blkio_data) - .unwrap_or(Vec::new()), + .unwrap_or_default(), write_iops_device: self .open_path("blkio.throttle.write_iops_device", false) .and_then(read_string_from) .and_then(parse_blkio_data) - .unwrap_or(Vec::new()), + .unwrap_or_default(), }, time: self .open_path("blkio.time", false) .and_then(read_string_from) .and_then(parse_blkio_data) - .unwrap_or(Vec::new()), + .unwrap_or_default(), time_recursive: self .open_path("blkio.time_recursive", false) .and_then(read_string_from) .and_then(parse_blkio_data) - .unwrap_or(Vec::new()), + .unwrap_or_default(), weight: self .open_path("blkio.weight", false) - .and_then(|file| read_u64_from(file)) + .and_then(read_u64_from) .unwrap_or(0u64), weight_device: self .open_path("blkio.weight_device", false) .and_then(read_string_from) .and_then(parse_blkio_data) - .unwrap_or(Vec::new()), + .unwrap_or_default(), io_stat: Vec::new(), } } diff --git a/src/cgroup.rs b/src/cgroup.rs index 5dedab5..4dda0c0 100644 --- a/src/cgroup.rs +++ b/src/cgroup.rs @@ -62,7 +62,7 @@ impl Cgroup { /// Create this control group. fn create(&self) { if self.hier.v2() { - let _ret = create_v2_cgroup(self.hier.root().clone(), &self.path); + let _ret = create_v2_cgroup(self.hier.root(), &self.path); } else { for subsystem in &self.subsystems { subsystem.to_controller().create(); @@ -112,13 +112,11 @@ impl Cgroup { .collect::>(); } - let cg = Cgroup { + Cgroup { path: path.to_str().unwrap().to_string(), - subsystems: subsystems, + subsystems, hier, - }; - - cg + } } /// Create a handle for a control group in the hierarchy `hier`, with name `path` and `relative_paths` @@ -146,7 +144,7 @@ impl Cgroup { let cn = x.controller_name(); if relative_paths.contains_key(&cn) { let rp = relative_paths.get(&cn).unwrap(); - let valid_path = rp.trim_start_matches("/").to_string(); + let valid_path = rp.trim_start_matches('/').to_string(); let mut p = PathBuf::from(valid_path); p.push(path); x.enter(p.as_ref()) @@ -157,13 +155,11 @@ impl Cgroup { .collect::>(); } - let cg = Cgroup { - subsystems: subsystems, + Cgroup { + subsystems, hier, path: path.to_str().unwrap().to_string(), - }; - - cg + } } /// The list of subsystems that this control group supports. @@ -179,8 +175,8 @@ impl Cgroup { /// will change. pub fn delete(&self) -> Result<()> { if self.v2() { - if self.path != "" { - let mut p = self.hier.root().clone(); + if !self.path.is_empty() { + let mut p = self.hier.root(); p.push(self.path.clone()); return fs::remove_dir(p).map_err(|e| Error::with_cause(RemoveFailed, e)); } @@ -222,7 +218,7 @@ impl Cgroup { /// let cpu: &CpuController = control_group.controller_of() /// .expect("No cpu controller attached!"); /// ``` - pub fn controller_of<'a, T>(self: &'a Self) -> Option<&'a T> + pub fn controller_of<'a, T>(&'a self) -> Option<&'a T> where &'a T: From<&'a Subsystem>, T: Controller + ControllIdentifier, @@ -249,7 +245,7 @@ impl Cgroup { pub fn add_task(&self, pid: CgroupPid) -> Result<()> { if self.v2() { let subsystems = self.subsystems(); - if subsystems.len() > 0 { + if !subsystems.is_empty() { let c = subsystems[0].to_controller(); c.add_task(&pid) } else { @@ -291,7 +287,7 @@ impl Cgroup { // Collect the tasks from all subsystems let mut v = if self.v2() { let subsystems = self.subsystems(); - if subsystems.len() > 0 { + if !subsystems.is_empty() { let c = subsystems[0].to_controller(); c.tasks() } else { @@ -313,9 +309,9 @@ impl Cgroup { } } -pub const UNIFIED_MOUNTPOINT: &'static str = "/sys/fs/cgroup"; +pub const UNIFIED_MOUNTPOINT: &str = "/sys/fs/cgroup"; -fn enable_controllers(controllers: &Vec, path: &PathBuf) { +fn enable_controllers(controllers: &[String], path: &PathBuf) { let mut f = path.clone(); f.push("cgroup.subtree_control"); for c in controllers { @@ -327,8 +323,8 @@ fn enable_controllers(controllers: &Vec, path: &PathBuf) { fn supported_controllers() -> Vec { let p = format!("{}/{}", UNIFIED_MOUNTPOINT, "cgroup.controllers"); let ret = fs::read_to_string(p.as_str()); - ret.unwrap_or(String::new()) - .split(" ") + ret.unwrap_or_default() + .split(' ') .map(|x| x.to_string()) .collect::>() } @@ -342,16 +338,15 @@ fn create_v2_cgroup(root: PathBuf, path: &str) -> Result<()> { enable_controllers(&controllers, &fp); // path: "a/b/c" - let elements = path.split("/").collect::>(); + let elements = path.split('/').collect::>(); let last_index = elements.len() - 1; for (i, ele) in elements.iter().enumerate() { // ROOT/a fp.push(ele); // create dir, need not check if is a file or directory if !fp.exists() { - match ::std::fs::create_dir(fp.clone()) { - Err(e) => return Err(Error::with_cause(ErrorKind::FsError, e)), - Ok(_) => {} + if let Err(e) = std::fs::create_dir(fp.clone()) { + return Err(Error::with_cause(ErrorKind::FsError, e)); } } diff --git a/src/cpu.rs b/src/cpu.rs index 6293e3c..baaedad 100644 --- a/src/cpu.rs +++ b/src/cpu.rs @@ -116,7 +116,7 @@ impl CpuController { Self { base: root.clone(), path: root, - v2: v2, + v2, } } @@ -133,7 +133,7 @@ impl CpuController { Err(e) => Err(Error::with_cause(ReadFailed, e)), } }) - .unwrap_or("".to_string()), + .unwrap_or_default(), } } @@ -299,8 +299,5 @@ fn parse_cfs_quota_and_period(mut file: File) -> Result { .parse::() .map_err(|e| Error::with_cause(ParseError, e))?; - Ok(CFSQuotaAndPeriod { - quota: quota, - period: period, - }) + Ok(CFSQuotaAndPeriod { quota, period }) } diff --git a/src/cpuacct.rs b/src/cpuacct.rs index 57eafbd..7928e45 100644 --- a/src/cpuacct.rs +++ b/src/cpuacct.rs @@ -111,35 +111,35 @@ impl CpuAcctController { CpuAcct { stat: self .open_path("cpuacct.stat", false) - .and_then(|file| read_string_from(file)) - .unwrap_or("".to_string()), + .and_then(read_string_from) + .unwrap_or_default(), usage: self .open_path("cpuacct.usage", false) - .and_then(|file| read_u64_from(file)) + .and_then(read_u64_from) .unwrap_or(0), usage_all: self .open_path("cpuacct.usage_all", false) - .and_then(|file| read_string_from(file)) - .unwrap_or("".to_string()), + .and_then(read_string_from) + .unwrap_or_default(), usage_percpu: self .open_path("cpuacct.usage_percpu", false) - .and_then(|file| read_string_from(file)) - .unwrap_or("".to_string()), + .and_then(read_string_from) + .unwrap_or_default(), usage_percpu_sys: self .open_path("cpuacct.usage_percpu_sys", false) - .and_then(|file| read_string_from(file)) - .unwrap_or("".to_string()), + .and_then(read_string_from) + .unwrap_or_default(), usage_percpu_user: self .open_path("cpuacct.usage_percpu_user", false) - .and_then(|file| read_string_from(file)) - .unwrap_or("".to_string()), + .and_then(read_string_from) + .unwrap_or_default(), usage_sys: self .open_path("cpuacct.usage_sys", false) - .and_then(|file| read_u64_from(file)) + .and_then(read_u64_from) .unwrap_or(0), usage_user: self .open_path("cpuacct.usage_user", false) - .and_then(|file| read_u64_from(file)) + .and_then(read_u64_from) .unwrap_or(0), } } diff --git a/src/cpuset.rs b/src/cpuset.rs index 957ed7a..4bc5b57 100644 --- a/src/cpuset.rs +++ b/src/cpuset.rs @@ -146,7 +146,7 @@ fn find_no_empty_parent(from: &str, file: &str) -> Result<(String, Vec) Err(e) => return Err(Error::with_cause(ReadFailed, e)), }; - if current_value != "" { + if !current_value.is_empty() { return Ok((current_value, v)); } v.push(current_path.clone()); @@ -167,7 +167,7 @@ fn copy_from_parent(current: &str, file: &str) -> Result<()> { // find not empty cpus/memes from current directory. let (value, parents) = find_no_empty_parent(current, file)?; - if value == "" || parents.len() == 0 { + if value.is_empty() || parents.is_empty() { return Ok(()); } @@ -208,17 +208,17 @@ impl<'a> From<&'a Subsystem> for &'a CpuSetController { fn parse_range(s: String) -> Result> { let mut fin = Vec::new(); - if s == "".to_string() { + if s.is_empty() { return Ok(fin); } // first split by commas - let comma_split = s.split(","); + let comma_split = s.split(','); for sp in comma_split { - if sp.contains("-") { + if sp.contains('-') { // this is a true range - let dash_split = sp.split("-").collect::>(); + let dash_split = sp.split('-').collect::>(); if dash_split.len() != 2 { return Err(Error::new(ParseError)); } @@ -247,7 +247,7 @@ impl CpuSetController { Self { base: root.clone(), path: root, - v2: v2, + v2, } } @@ -257,7 +257,7 @@ impl CpuSetController { CpuSet { cpu_exclusive: { self.open_path("cpuset.cpu_exclusive", false) - .and_then(|file| read_u64_from(file)) + .and_then(read_u64_from) .map(|x| x == 1) .unwrap_or(false) }, @@ -265,19 +265,19 @@ impl CpuSetController { self.open_path("cpuset.cpus", false) .and_then(read_string_from) .and_then(parse_range) - .unwrap_or(Vec::new()) + .unwrap_or_default() }, effective_cpus: { self.open_path("cpuset.effective_cpus", false) .and_then(read_string_from) .and_then(parse_range) - .unwrap_or(Vec::new()) + .unwrap_or_default() }, effective_mems: { self.open_path("cpuset.effective_mems", false) .and_then(read_string_from) .and_then(parse_range) - .unwrap_or(Vec::new()) + .unwrap_or_default() }, mem_exclusive: { self.open_path("cpuset.mem_exclusive", false) @@ -324,7 +324,7 @@ impl CpuSetController { self.open_path("cpuset.mems", false) .and_then(read_string_from) .and_then(parse_range) - .unwrap_or(Vec::new()) + .unwrap_or_default() }, sched_load_balance: { self.open_path("cpuset.sched_load_balance", false) diff --git a/src/devices.rs b/src/devices.rs index 838d17e..1cd1ea8 100644 --- a/src/devices.rs +++ b/src/devices.rs @@ -102,7 +102,7 @@ impl DevicePermissions { /// Checks whether the string is a valid descriptor of DevicePermissions. pub fn is_valid(s: &str) -> bool { - if s == "" { + if s.is_empty() { return false; } for i in s.chars() { @@ -110,7 +110,7 @@ impl DevicePermissions { return false; } } - return true; + true } /// Returns a Vec will all the permissions that a device can have. @@ -123,9 +123,10 @@ impl DevicePermissions { } /// Convert a string into DevicePermissions. + #[allow(clippy::should_implement_trait)] pub fn from_str(s: &str) -> Result> { let mut v = Vec::new(); - if s == "" { + if s.is_empty() { return Ok(v); } for e in s.chars() { @@ -206,7 +207,7 @@ impl DevicesController { devtype: DeviceType, major: i64, minor: i64, - perm: &Vec, + perm: &[DevicePermissions], ) -> Result<()> { let perms = perm .iter() @@ -238,7 +239,7 @@ impl DevicesController { devtype: DeviceType, major: i64, minor: i64, - perm: &Vec, + perm: &[DevicePermissions], ) -> Result<()> { let perms = perm .iter() @@ -274,13 +275,13 @@ impl DevicesController { error!("allowed_devices: acc: {:?}, ls: {:?}", acc, ls); Err(Error::new(ParseError)) } else { - let devtype = DeviceType::from_char(ls[0].chars().nth(0)); + let devtype = DeviceType::from_char(ls[0].chars().next()); let mut major = ls[1].parse::(); let mut minor = ls[2].parse::(); - if major.is_err() && ls[1] == "*".to_string() { + if major.is_err() && ls[1] == "*" { major = Ok(-1); } - if minor.is_err() && ls[2] == "*".to_string() { + if minor.is_err() && ls[2] == "*" { minor = Ok(-1); } if devtype.is_none() || major.is_err() || minor.is_err() || !DevicePermissions::is_valid(&ls[3]) { @@ -295,7 +296,7 @@ impl DevicesController { devtype: devtype.unwrap(), major: major.unwrap(), minor: minor.unwrap(), - access: access, + access, }); Ok(acc) } diff --git a/src/events.rs b/src/events.rs index b06f3c0..86f8f75 100644 --- a/src/events.rs +++ b/src/events.rs @@ -53,7 +53,7 @@ fn register_memory_event( let event_control_path = cg_dir.join("cgroup.event_control"); let data; - if arg == "" { + if arg.is_empty() { data = format!("{} {}", eventfd, event_file.as_raw_fd()); } else { data = format!("{} {} {}", eventfd, event_file.as_raw_fd(), arg); @@ -70,11 +70,8 @@ fn register_memory_event( thread::spawn(move || { loop { let mut buf = [0; 8]; - match eventfd_file.read(&mut buf) { - Err(_err) => { - return; - } - Ok(_) => {} + if eventfd_file.read(&mut buf).is_err() { + return; } // When a cgroup is destroyed, an event is sent to eventfd. diff --git a/src/freezer.rs b/src/freezer.rs index 93a0185..7f0fc1c 100644 --- a/src/freezer.rs +++ b/src/freezer.rs @@ -87,7 +87,7 @@ impl FreezerController { Self { base: root.clone(), path: root, - v2: v2, + v2, } } diff --git a/src/hierarchies.rs b/src/hierarchies.rs index 26edf98..9a5d8df 100644 --- a/src/hierarchies.rs +++ b/src/hierarchies.rs @@ -268,6 +268,12 @@ impl V1 { } } +impl Default for V1 { + fn default() -> Self { + Self::new() + } +} + impl V2 { /// Finds where control groups are mounted to and returns a hierarchy in which control groups /// can be created. @@ -278,7 +284,13 @@ impl V2 { } } -pub const UNIFIED_MOUNTPOINT: &'static str = "/sys/fs/cgroup"; +impl Default for V2 { + fn default() -> Self { + Self::new() + } +} + +pub const UNIFIED_MOUNTPOINT: &str = "/sys/fs/cgroup"; #[cfg(all(target_os = "linux", not(target_env = "musl")))] pub fn is_cgroup2_unified_mode() -> bool { @@ -294,7 +306,7 @@ pub fn is_cgroup2_unified_mode() -> bool { fs_stat.unwrap().filesystem_type() == statfs::CGROUP2_SUPER_MAGIC } -pub const INIT_CGROUP_PATHS: &'static str = "/proc/1/cgroup"; +pub const INIT_CGROUP_PATHS: &str = "/proc/1/cgroup"; #[cfg(all(target_os = "linux", target_env = "musl"))] pub fn is_cgroup2_unified_mode() -> bool { diff --git a/src/hugetlb.rs b/src/hugetlb.rs index ed8d83d..b688879 100644 --- a/src/hugetlb.rs +++ b/src/hugetlb.rs @@ -92,8 +92,8 @@ impl HugeTlbController { Self { base: root.clone(), path: root, - sizes: sizes, - v2: v2, + sizes, + v2, } } @@ -115,7 +115,7 @@ impl HugeTlbController { self.open_path(&format!("hugetlb.{}.events", hugetlb_size), false) .and_then(flat_keyed_to_vec) .and_then(|x| { - if x.len() == 0 { + if x.is_empty() { return Err(Error::from_string(format!( "get empty from hugetlb.{}.events", hugetlb_size @@ -175,7 +175,7 @@ impl HugeTlbController { } } -pub const HUGEPAGESIZE_DIR: &'static str = "/sys/kernel/mm/hugepages"; +pub const HUGEPAGESIZE_DIR: &str = "/sys/kernel/mm/hugepages"; use regex::Regex; use std::collections::HashMap; use std::fs; @@ -264,8 +264,8 @@ fn parse_size(s: &str, m: &HashMap) -> Result { let caps = re.unwrap().captures(s).unwrap(); let num = caps.name("num"); - let size: u128 = if num.is_some() { - let n = num.unwrap().as_str().trim().parse::(); + let size: u128 = if let Some(num) = num { + let n = num.as_str().trim().parse::(); if n.is_err() { return Err(Error::new(InvalidBytesSize)); } @@ -275,10 +275,10 @@ fn parse_size(s: &str, m: &HashMap) -> Result { }; let q = caps.name("mul"); - let mul: u128 = if q.is_some() { - let t = m.get(q.unwrap().as_str()); - if t.is_some() { - *t.unwrap() + let mul: u128 = if let Some(q) = q { + let t = m.get(q.as_str()); + if let Some(t) = t { + *t } else { return Err(Error::new(InvalidBytesSize)); } @@ -289,7 +289,7 @@ fn parse_size(s: &str, m: &HashMap) -> Result { Ok(size * mul) } -fn custom_size(mut size: f64, base: f64, m: &Vec) -> String { +fn custom_size(mut size: f64, base: f64, m: &[String]) -> String { let mut i = 0; while size >= base && i < m.len() - 1 { size /= base; diff --git a/src/lib.rs b/src/lib.rs index 221d576..52e63be 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,9 +4,11 @@ // SPDX-License-Identifier: Apache-2.0 or MIT // +#![allow(clippy::unnecessary_unwrap)] use log::*; use std::collections::HashMap; +use std::fmt; use std::fs::{self, File}; use std::io::{BufRead, BufReader, Read, Write}; use std::path::{Path, PathBuf}; @@ -123,23 +125,23 @@ pub enum Controllers { Systemd, } -impl Controllers { - pub fn to_string(&self) -> String { +impl fmt::Display for Controllers { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Controllers::Pids => return "pids".to_string(), - Controllers::Mem => return "memory".to_string(), - Controllers::CpuSet => return "cpuset".to_string(), - Controllers::CpuAcct => return "cpuacct".to_string(), - Controllers::Cpu => return "cpu".to_string(), - Controllers::Devices => return "devices".to_string(), - Controllers::Freezer => return "freezer".to_string(), - Controllers::NetCls => return "net_cls".to_string(), - Controllers::BlkIo => return "blkio".to_string(), - Controllers::PerfEvent => return "perf_event".to_string(), - Controllers::NetPrio => return "net_prio".to_string(), - Controllers::HugeTlb => return "hugetlb".to_string(), - Controllers::Rdma => return "rdma".to_string(), - Controllers::Systemd => return "name=systemd".to_string(), + Controllers::Pids => write!(f, "pids"), + Controllers::Mem => write!(f, "memory"), + Controllers::CpuSet => write!(f, "cpuset"), + Controllers::CpuAcct => write!(f, "cpuacct"), + Controllers::Cpu => write!(f, "cpu"), + Controllers::Devices => write!(f, "devices"), + Controllers::Freezer => write!(f, "freezer"), + Controllers::NetCls => write!(f, "net_cls"), + Controllers::BlkIo => write!(f, "blkio"), + Controllers::PerfEvent => write!(f, "perf_event"), + Controllers::NetPrio => write!(f, "net_prio"), + Controllers::HugeTlb => write!(f, "hugetlb"), + Controllers::Rdma => write!(f, "rdma"), + Controllers::Systemd => write!(f, "name=systemd"), } } } @@ -179,13 +181,13 @@ mod sealed { if w { match File::create(&path) { - Err(e) => return Err(Error::with_cause(ErrorKind::WriteFailed, e)), - Ok(file) => return Ok(file), + Err(e) => Err(Error::with_cause(ErrorKind::WriteFailed, e)), + Ok(file) => Ok(file), } } else { match File::open(&path) { - Err(e) => return Err(Error::with_cause(ErrorKind::ReadFailed, e)), - Ok(file) => return Ok(file), + Err(e) => Err(Error::with_cause(ErrorKind::ReadFailed, e)), + Ok(file) => Ok(file), } } } @@ -203,7 +205,7 @@ mod sealed { #[doc(hidden)] fn path_exists(&self, p: &str) -> bool { - if let Err(_) = self.verify_path() { + if self.verify_path().is_err() { return false; } @@ -295,7 +297,7 @@ where /// Create this controller fn create(&self) { self.verify_path() - .expect(format!("path should be valid: {:?}", self.path()).as_str()); + .unwrap_or_else(|_| panic!("path should be valid: {:?}", self.path())); match ::std::fs::create_dir_all(self.get_path()) { Ok(_) => self.post_create(), @@ -360,7 +362,7 @@ where file = "cgroup.procs"; } self.open_path(file, false) - .and_then(|file| { + .map(|file| { let bf = BufReader::new(file); let mut v = Vec::new(); for line in bf.lines() { @@ -369,9 +371,9 @@ where v.push(n); } } - Ok(v.into_iter().map(CgroupPid::from).collect()) + v.into_iter().map(CgroupPid::from).collect() }) - .unwrap_or(vec![]) + .unwrap_or_default() } fn v2(&self) -> bool { @@ -387,17 +389,15 @@ fn remove_dir(dir: &PathBuf) -> Result<()> { return Ok(()); } - if dir.exists() { - if dir.is_dir() { - for entry in fs::read_dir(dir).map_err(|e| Error::with_cause(ReadFailed, e))? { - let entry = entry.map_err(|e| Error::with_cause(ReadFailed, e))?; - let path = entry.path(); - if path.is_dir() { - remove_dir(&path)?; - } + if dir.exists() && dir.is_dir() { + for entry in fs::read_dir(dir).map_err(|e| Error::with_cause(ReadFailed, e))? { + let entry = entry.map_err(|e| Error::with_cause(ReadFailed, e))?; + let path = entry.path(); + if path.is_dir() { + remove_dir(&path)?; } - fs::remove_dir(dir).map_err(|e| Error::with_cause(RemoveFailed, e))?; } + fs::remove_dir(dir).map_err(|e| Error::with_cause(RemoveFailed, e))?; } Ok(()) @@ -641,75 +641,61 @@ impl<'a> From<&'a std::process::Child> for CgroupPid { impl Subsystem { fn enter(self, path: &Path) -> Self { match self { - Subsystem::Pid(cont) => Subsystem::Pid({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::Pid(mut cont) => Subsystem::Pid({ + cont.get_path_mut().push(path); + cont }), - Subsystem::Mem(cont) => Subsystem::Mem({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::Mem(mut cont) => Subsystem::Mem({ + cont.get_path_mut().push(path); + cont }), - Subsystem::CpuSet(cont) => Subsystem::CpuSet({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::CpuSet(mut cont) => Subsystem::CpuSet({ + cont.get_path_mut().push(path); + cont }), - Subsystem::CpuAcct(cont) => Subsystem::CpuAcct({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::CpuAcct(mut cont) => Subsystem::CpuAcct({ + cont.get_path_mut().push(path); + cont }), - Subsystem::Cpu(cont) => Subsystem::Cpu({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::Cpu(mut cont) => Subsystem::Cpu({ + cont.get_path_mut().push(path); + cont }), - Subsystem::Devices(cont) => Subsystem::Devices({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::Devices(mut cont) => Subsystem::Devices({ + cont.get_path_mut().push(path); + cont }), - Subsystem::Freezer(cont) => Subsystem::Freezer({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::Freezer(mut cont) => Subsystem::Freezer({ + cont.get_path_mut().push(path); + cont }), - Subsystem::NetCls(cont) => Subsystem::NetCls({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::NetCls(mut cont) => Subsystem::NetCls({ + cont.get_path_mut().push(path); + cont }), - Subsystem::BlkIo(cont) => Subsystem::BlkIo({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::BlkIo(mut cont) => Subsystem::BlkIo({ + cont.get_path_mut().push(path); + cont }), - Subsystem::PerfEvent(cont) => Subsystem::PerfEvent({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::PerfEvent(mut cont) => Subsystem::PerfEvent({ + cont.get_path_mut().push(path); + cont }), - Subsystem::NetPrio(cont) => Subsystem::NetPrio({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::NetPrio(mut cont) => Subsystem::NetPrio({ + cont.get_path_mut().push(path); + cont }), - Subsystem::HugeTlb(cont) => Subsystem::HugeTlb({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::HugeTlb(mut cont) => Subsystem::HugeTlb({ + cont.get_path_mut().push(path); + cont }), - Subsystem::Rdma(cont) => Subsystem::Rdma({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::Rdma(mut cont) => Subsystem::Rdma({ + cont.get_path_mut().push(path); + cont }), - Subsystem::Systemd(cont) => Subsystem::Systemd({ - let mut c = cont.clone(); - c.get_path_mut().push(path); - c + Subsystem::Systemd(mut cont) => Subsystem::Systemd({ + cont.get_path_mut().push(path); + cont }), } } @@ -760,16 +746,18 @@ impl MaxValue { MaxValue::Value(num) => *num, } } +} - fn to_string(&self) -> String { +impl fmt::Display for MaxValue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - MaxValue::Max => "max".to_string(), - MaxValue::Value(num) => num.to_string(), + MaxValue::Max => write!(f, "max"), + MaxValue::Value(num) => write!(f, "{}", num.to_string()), } } } -pub fn parse_max_value(s: &String) -> Result { +pub fn parse_max_value(s: &str) -> Result { if s.trim() == "max" { return Ok(MaxValue::Max); } @@ -791,11 +779,8 @@ pub fn flat_keyed_to_vec(mut file: File) -> Result> { for line in content.lines() { let parts: Vec<&str> = line.split(' ').collect(); if parts.len() == 2 { - match parts[1].parse::() { - Ok(i) => { - v.push((parts[0].to_string(), i)); - } - Err(_) => {} + if let Ok(i) = parts[1].parse::() { + v.push((parts[0].to_string(), i)); } } } @@ -814,11 +799,8 @@ pub fn flat_keyed_to_hashmap(mut file: File) -> Result> { for line in content.lines() { let parts: Vec<&str> = line.split(' ').collect(); if parts.len() == 2 { - match parts[1].parse::() { - Ok(i) => { - h.insert(parts[0].to_string(), i); - } - Err(_) => {} + if let Ok(i) = parts[1].parse::() { + h.insert(parts[0].to_string(), i); } } } @@ -836,18 +818,15 @@ pub fn nested_keyed_to_hashmap(mut file: File) -> Result = line.split(' ').collect(); - if parts.len() == 0 { + if parts.is_empty() { continue; } let mut th = HashMap::new(); - for item in parts[1..].into_iter() { + for item in parts[1..].iter() { let fields: Vec<&str> = item.split('=').collect(); if fields.len() == 2 { - match fields[1].parse::() { - Ok(i) => { - th.insert(fields[0].to_string(), i); - } - Err(_) => {} + if let Ok(i) = fields[1].parse::() { + th.insert(fields[0].to_string(), i); } } } diff --git a/src/memory.rs b/src/memory.rs index 037e9c3..b682a9c 100644 --- a/src/memory.rs +++ b/src/memory.rs @@ -56,6 +56,7 @@ pub struct OomControl { pub oom_kill: u64, } +#[allow(clippy::unnecessary_wraps)] fn parse_oom_control(s: String) -> Result { let spl = s.split_whitespace().collect::>(); @@ -122,9 +123,10 @@ pub struct NumaStat { pub hierarchical_unevictable_pages_per_node: Vec, } +#[allow(clippy::unnecessary_wraps)] fn parse_numa_stat(s: String) -> Result { // Parse the number of nodes - let _nodes = (s.split_whitespace().collect::>().len() - 8) / 8; + let _nodes = (s.split_whitespace().count() - 8) / 8; let mut ls = s.lines(); let total_line = ls.next().unwrap(); let file_line = ls.next().unwrap(); @@ -142,10 +144,10 @@ fn parse_numa_stat(s: String) -> Result { .parse::() .unwrap_or(0), total_pages_per_node: { - let spl = &total_line.split(" ").collect::>()[1..]; + let spl = &total_line.split(' ').collect::>()[1..]; spl.iter() .map(|x| { - x.split("=").collect::>()[1] + x.split('=').collect::>()[1] .parse::() .unwrap_or(0) }) @@ -157,10 +159,10 @@ fn parse_numa_stat(s: String) -> Result { .parse::() .unwrap_or(0), file_pages_per_node: { - let spl = &file_line.split(" ").collect::>()[1..]; + let spl = &file_line.split(' ').collect::>()[1..]; spl.iter() .map(|x| { - x.split("=").collect::>()[1] + x.split('=').collect::>()[1] .parse::() .unwrap_or(0) }) @@ -172,10 +174,10 @@ fn parse_numa_stat(s: String) -> Result { .parse::() .unwrap_or(0), anon_pages_per_node: { - let spl = &anon_line.split(" ").collect::>()[1..]; + let spl = &anon_line.split(' ').collect::>()[1..]; spl.iter() .map(|x| { - x.split("=").collect::>()[1] + x.split('=').collect::>()[1] .parse::() .unwrap_or(0) }) @@ -187,10 +189,10 @@ fn parse_numa_stat(s: String) -> Result { .parse::() .unwrap_or(0), unevictable_pages_per_node: { - let spl = &unevict_line.split(" ").collect::>()[1..]; + let spl = &unevict_line.split(' ').collect::>()[1..]; spl.iter() .map(|x| { - x.split("=").collect::>()[1] + x.split('=').collect::>()[1] .parse::() .unwrap_or(0) }) @@ -209,10 +211,10 @@ fn parse_numa_stat(s: String) -> Result { }, hierarchical_total_pages_per_node: { if !hier_total_line.is_empty() { - let spl = &hier_total_line.split(" ").collect::>()[1..]; + let spl = &hier_total_line.split(' ').collect::>()[1..]; spl.iter() .map(|x| { - x.split("=").collect::>()[1] + x.split('=').collect::>()[1] .parse::() .unwrap_or(0) }) @@ -234,10 +236,10 @@ fn parse_numa_stat(s: String) -> Result { }, hierarchical_file_pages_per_node: { if !hier_file_line.is_empty() { - let spl = &hier_file_line.split(" ").collect::>()[1..]; + let spl = &hier_file_line.split(' ').collect::>()[1..]; spl.iter() .map(|x| { - x.split("=").collect::>()[1] + x.split('=').collect::>()[1] .parse::() .unwrap_or(0) }) @@ -259,10 +261,10 @@ fn parse_numa_stat(s: String) -> Result { }, hierarchical_anon_pages_per_node: { if !hier_anon_line.is_empty() { - let spl = &hier_anon_line.split(" ").collect::>()[1..]; + let spl = &hier_anon_line.split(' ').collect::>()[1..]; spl.iter() .map(|x| { - x.split("=").collect::>()[1] + x.split('=').collect::>()[1] .parse::() .unwrap_or(0) }) @@ -284,10 +286,10 @@ fn parse_numa_stat(s: String) -> Result { }, hierarchical_unevictable_pages_per_node: { if !hier_unevict_line.is_empty() { - let spl = &hier_unevict_line.split(" ").collect::>()[1..]; + let spl = &hier_unevict_line.split(' ').collect::>()[1..]; spl.iter() .map(|x| { - x.split("=").collect::>()[1] + x.split('=').collect::>()[1] .parse::() .unwrap_or(0) }) @@ -340,6 +342,7 @@ pub struct MemoryStat { pub raw: HashMap, } +#[allow(clippy::unnecessary_wraps)] fn parse_memory_stat(s: String) -> Result { let mut raw = HashMap::new(); @@ -393,7 +396,7 @@ fn parse_memory_stat(s: String) -> Result { total_inactive_file: *raw.get("total_inactive_file").unwrap_or(&0), total_active_file: *raw.get("total_active_file").unwrap_or(&0), total_unevictable: *raw.get("total_unevictable").unwrap_or(&0), - raw: raw, + raw, }) } @@ -532,7 +535,7 @@ impl MemController { Self { base: root.clone(), path: root, - v2: v2, + v2, } } @@ -547,8 +550,8 @@ impl MemController { for value in values { let v = value.0; let f = value.1; - if v.is_some() { - let v = v.unwrap().to_string(); + if let Some(v) = v { + let v = v.to_string(); self.open_path(f, true).and_then(|mut file| { file.write_all(v.as_ref()) .map_err(|e| Error::with_cause(WriteFailed, e)) @@ -589,7 +592,7 @@ impl MemController { .open_path("memory.stat", false) .and_then(read_string_from) .and_then(parse_memory_stat) - .unwrap_or(MemoryStat::default()), + .unwrap_or_default(), swappiness: self .open_path("memory.swap.current", false) .and_then(read_u64_from) @@ -633,12 +636,12 @@ impl MemController { .open_path("memory.numa_stat", false) .and_then(read_string_from) .and_then(parse_numa_stat) - .unwrap_or(NumaStat::default()), + .unwrap_or_default(), oom_control: self .open_path("memory.oom_control", false) .and_then(read_string_from) .and_then(parse_oom_control) - .unwrap_or(OomControl::default()), + .unwrap_or_default(), soft_limit_in_bytes: self .open_path("memory.soft_limit_in_bytes", false) .and_then(read_i64_from) @@ -647,7 +650,7 @@ impl MemController { .open_path("memory.stat", false) .and_then(read_string_from) .and_then(parse_memory_stat) - .unwrap_or(MemoryStat::default()), + .unwrap_or_default(), swappiness: self .open_path("memory.swappiness", false) .and_then(read_u64_from) @@ -681,7 +684,7 @@ impl MemController { slabinfo: self .open_path("memory.kmem.slabinfo", false) .and_then(read_string_from) - .unwrap_or("".to_string()), + .unwrap_or_default(), } } @@ -713,7 +716,7 @@ impl MemController { fail_cnt: self .open_path("memory.swap.events", false) .and_then(flat_keyed_to_hashmap) - .and_then(|x| Ok(*x.get("fail").unwrap_or(&0) as u64)) + .map(|x| *x.get("fail").unwrap_or(&0) as u64) .unwrap(), limit_in_bytes: self .open_path("memory.swap.max", false) @@ -1143,7 +1146,7 @@ total_unevictable 81920 total_inactive_file: 1272135680, total_active_file: 2338816000, total_unevictable: 81920, - raw: raw, + raw, } ); } diff --git a/src/net_cls.rs b/src/net_cls.rs index 77b3f07..fd6d133 100644 --- a/src/net_cls.rs +++ b/src/net_cls.rs @@ -49,7 +49,7 @@ impl ControllerInternal for NetClsController { update_and_test!(self, set_class, res.class_id, get_class); - return Ok(()); + Ok(()) } } @@ -96,6 +96,6 @@ impl NetClsController { /// Get the network class id of the outgoing packets of the control group's tasks. pub fn get_class(&self) -> Result { self.open_path("net_cls.classid", false) - .and_then(|file| read_u64_from(file)) + .and_then(read_u64_from) } } diff --git a/src/net_prio.rs b/src/net_prio.rs index d2b6c68..4620eb3 100644 --- a/src/net_prio.rs +++ b/src/net_prio.rs @@ -94,6 +94,7 @@ impl NetPrioController { } /// A map of priorities for each network interface. + #[allow(clippy::iter_nth_zero, clippy::unnecessary_unwrap)] pub fn ifpriomap(&self) -> Result> { self.open_path("net_prio.ifpriomap", false) .and_then(|file| { @@ -105,6 +106,7 @@ impl NetPrioController { let mut acc = acc.unwrap(); let l = line.unwrap(); let mut sp = l.split_whitespace(); + let ifname = sp.nth(0); let ifprio = sp.nth(1); if ifname.is_none() || ifprio.is_none() { diff --git a/src/pid.rs b/src/pid.rs index fef8421..b03e3dc 100644 --- a/src/pid.rs +++ b/src/pid.rs @@ -96,7 +96,7 @@ impl PidController { Self { base: root.clone(), path: root, - v2: v2, + v2, } } diff --git a/src/systemd.rs b/src/systemd.rs index 3fe0262..8eb3db2 100644 --- a/src/systemd.rs +++ b/src/systemd.rs @@ -66,7 +66,7 @@ impl SystemdController { Self { base: root.clone(), path: root, - v2: v2, + v2, } } } diff --git a/tests/cgroup.rs b/tests/cgroup.rs index 962cdf5..563168b 100644 --- a/tests/cgroup.rs +++ b/tests/cgroup.rs @@ -48,7 +48,7 @@ fn test_cgroup_with_relative_paths() { let cg = Cgroup::load(h, String::from(cgroup_name)); { let subsystems = cg.subsystems(); - subsystems.into_iter().for_each(|sub| match sub { + subsystems.iter().for_each(|sub| match sub { Subsystem::Pid(c) => { let cgroup_path = c.path().to_str().unwrap(); let relative_path = "/pids/"; diff --git a/tests/cpuset.rs b/tests/cpuset.rs index a714683..44e525e 100644 --- a/tests/cpuset.rs +++ b/tests/cpuset.rs @@ -36,7 +36,7 @@ fn test_cpuset_set_cpus() { assert_eq!(0, set.cpus.len()); } else { // for cgroup v1, cpuset is copied from parent. - assert_eq!(true, set.cpus.len() > 0); + assert_eq!(true, !set.cpus.is_empty()); } // 0 @@ -48,10 +48,9 @@ fn test_cpuset_set_cpus() { assert_eq!((0, 0), set.cpus[0]); // all cpus in system - let cpus = - fs::read_to_string("/sys/fs/cgroup/cpuset.cpus.effective").unwrap_or("".to_string()); + let cpus = fs::read_to_string("/sys/fs/cgroup/cpuset.cpus.effective").unwrap_or_default(); let cpus = cpus.trim(); - if cpus != "" { + if !cpus.is_empty() { let r = cpuset.set_cpus(&cpus); assert_eq!(true, r.is_ok()); let set = cpuset.cpuset(); @@ -73,14 +72,14 @@ fn test_cpuset_set_cpus_add_task() { assert_eq!(0, set.cpus.len()); } else { // for cgroup v1, cpuset is copied from parent. - assert_eq!(true, set.cpus.len() > 0); + assert_eq!(true, !set.cpus.is_empty()); } // Add a task to the control group. let pid_i = libc::pid_t::from(nix::unistd::getpid()) as u64; let _ = cg.add_task(CgroupPid::from(pid_i)); let tasks = cg.tasks(); - assert_eq!(true, tasks.len() > 0); + assert_eq!(true, !tasks.is_empty()); println!("tasks after added: {:?}", tasks); // remove task diff --git a/tests/devices.rs b/tests/devices.rs index a88bb29..90c1bef 100644 --- a/tests/devices.rs +++ b/tests/devices.rs @@ -27,7 +27,7 @@ fn test_devices_parsing() { DeviceType::All, -1, -1, - &vec![ + &[ DevicePermissions::Read, DevicePermissions::Write, DevicePermissions::MkNod, @@ -42,7 +42,7 @@ fn test_devices_parsing() { // Now add mknod access to /dev/null device devices - .allow_device(DeviceType::Char, 1, 3, &vec![DevicePermissions::MkNod]) + .allow_device(DeviceType::Char, 1, 3, &[DevicePermissions::MkNod]) .unwrap(); let allowed_devices = devices.allowed_devices(); assert!(allowed_devices.is_ok()); diff --git a/tests/pids.rs b/tests/pids.rs index 94d9ce1..27a2de7 100644 --- a/tests/pids.rs +++ b/tests/pids.rs @@ -89,7 +89,7 @@ fn test_pid_events_is_not_zero() { Ok(ForkResult::Child) => loop { let pids_max = pids.get_pid_max(); if pids_max.is_ok() && pids_max.unwrap() == MaxValue::Value(1) { - if let Err(_) = unsafe { fork() } { + if unsafe { fork() }.is_err() { unsafe { libc::exit(0) }; } else { unsafe { libc::exit(1) };