Skip to content

Commit

Permalink
Use saturating_sub instead of - for unsigned ints
Browse files Browse the repository at this point in the history
This fixes a panic if the operation with the unsigned ints would result
in a negative number

Signed-off-by: Djordje Lukic <[email protected]>
  • Loading branch information
rumpl committed Feb 3, 2023
1 parent ab60bfc commit e01e604
Show file tree
Hide file tree
Showing 6 changed files with 6 additions and 6 deletions.
2 changes: 1 addition & 1 deletion crates/libcgroups/src/systemd/cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub fn convert_shares_to_cgroup2(shares: u64) -> u64 {
return 0;
}

1 + ((shares - 2) * 9999) / 262142
1 + ((shares.saturating_sub(2)) * 9999) / 262142
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion crates/libcgroups/src/v1/hugetlb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ impl HugeTlb {
}

fn is_power_of_two(number: u64) -> bool {
(number != 0) && (number & (number - 1)) == 0
(number != 0) && (number & (number.saturating_sub(1))) == 0
}

fn stats_for_page_size(cgroup_path: &Path, page_size: &str) -> Result<HugeTlbStats> {
Expand Down
2 changes: 1 addition & 1 deletion crates/libcgroups/src/v2/cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ impl Cpu {
return 0;
}

let weight = 1 + ((shares - 2) * 9999) / 262142;
let weight = 1 + ((shares.saturating_sub(2)) * 9999) / 262142;
weight.min(MAX_CPU_WEIGHT)
}

Expand Down
2 changes: 1 addition & 1 deletion crates/libcgroups/src/v2/hugetlb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl HugeTlb {
}

fn is_power_of_two(number: u64) -> bool {
(number != 0) && (number & (number - 1)) == 0
(number != 0) && (number & (number.saturating_sub(1))) == 0
}

fn stats_for_page_size(cgroup_path: &Path, page_size: &str) -> Result<HugeTlbStats> {
Expand Down
2 changes: 1 addition & 1 deletion crates/libcgroups/src/v2/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ impl Io {
if v == 0 {
return 0;
}
1 + (v - 10) * 9999 / 990
1 + (v.saturating_sub(10)) * 9999 / 990
}

fn io_max_path(path: &Path) -> PathBuf {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ fn get_realtime_runtime() -> Option<i64> {
fn test_cpu_cgroups() -> TestResult {
let cgroup_name = "test_cpu_cgroups";
// Kernel counts 0 as a CPU, so on a system with 8 logical cores you will need `0-7` range set.
let cpu_range = format!("0-{}", num_cpus::get() - 1);
let cpu_range = format!("0-{}", num_cpus::get().saturating_sub(1));

let realtime_period = get_realtime_period();
let realtime_runtime = get_realtime_runtime();
Expand Down

0 comments on commit e01e604

Please sign in to comment.