Skip to content

Commit da02395

Browse files
committed
Apply review suggestion
1 parent 995b629 commit da02395

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

src/system_information/disk.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ pub struct Disk {
55
pub name: String,
66
pub mount_point: String,
77
pub total_space: u64,
8+
pub used_space: u64,
89
pub available_space: u64,
910
pub usage_percent: f64,
1011
}
@@ -24,16 +25,19 @@ impl From<&sysinfo::Disk> for Disk {
2425
fn from(sysinfo_disk: &sysinfo::Disk) -> Self {
2526
let total_space = sysinfo_disk.total_space();
2627
let available_space = sysinfo_disk.available_space();
27-
let usage_percent = if total_space > 0 {
28-
(total_space - available_space) as f64 / total_space as f64 * 100.0
29-
} else {
30-
0.0
28+
// There shouldn't be negative used bytes. We prevent underflow, to not falsely report more
29+
// used than total space.
30+
let used_space = total_space.saturating_sub(available_space);
31+
let usage_percent = match used_space {
32+
0 => 0.0,
33+
used_space => used_space as f64 / total_space as f64 * 100.0,
3134
};
3235

3336
let disk = Disk {
3437
name: sysinfo_disk.name().to_string_lossy().into_owned(),
3538
mount_point: sysinfo_disk.mount_point().to_string_lossy().into_owned(),
3639
total_space,
40+
used_space,
3741
available_space,
3842
usage_percent,
3943
};
@@ -43,6 +47,7 @@ impl From<&sysinfo::Disk> for Disk {
4347
disk.mount_point,
4448
disk.name,
4549
disk.space.total = disk.total_space,
50+
disk.space.used = disk.used_space,
4651
disk.space.available = disk.available_space,
4752
disk.space.usage_percent = format!("{:.1}%", disk.usage_percent),
4853
"disk usage high"
@@ -52,6 +57,7 @@ impl From<&sysinfo::Disk> for Disk {
5257
disk.mount_point,
5358
disk.name,
5459
disk.space.total = disk.total_space,
60+
disk.space.used = disk.used_space,
5561
disk.space.available = disk.available_space,
5662
disk.space.usage_percent = format!("{:.1}%", disk.usage_percent),
5763
"found disk"

0 commit comments

Comments
 (0)