| 1 |
use std::{ |
| 2 |
ffi::{CStr, CString}, |
| 3 |
os::unix::prelude::OsStrExt, |
| 4 |
path::{Path, PathBuf}, |
| 5 |
str::FromStr, |
| 6 |
}; |
| 7 |
|
| 8 |
use anyhow::bail; |
| 9 |
|
| 10 |
use super::bindings; |
| 11 |
use crate::collection::disks::unix::{FileSystem, Usage}; |
| 12 |
|
| 13 |
pub(crate) struct Partition { |
| 14 |
device: String, |
| 15 |
mount_point: PathBuf, |
| 16 |
fs_type: FileSystem, |
| 17 |
} |
| 18 |
|
| 19 |
impl Partition { |
| 20 |
|
| 21 |
#[inline] |
| 22 |
pub fn mount_point(&self) -> &Path { |
| 23 |
self.mount_point.as_path() |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
#[inline] |
| 28 |
pub fn fs_type(&self) -> &FileSystem { |
| 29 |
&self.fs_type |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
pub fn usage(&self) -> anyhow::Result<Usage> { |
| 34 |
let path = CString::new(self.mount_point().as_os_str().as_bytes())?; |
| 35 |
let mut vfs = std::mem::MaybeUninit::<libc::statvfs>::uninit(); |
| 36 |
|
| 37 |
|
| 38 |
let result = unsafe { libc::statvfs(path.as_ptr(), vfs.as_mut_ptr()) }; |
| 39 |
|
| 40 |
if result == 0 { |
| 41 |
|
| 42 |
|
| 43 |
Ok(Usage::new(unsafe { vfs.assume_init() })) |
| 44 |
} else { |
| 45 |
bail!("statvfs failed to get the disk usage for disk {path:?}") |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
#[inline] |
| 51 |
pub fn get_device_name(&self) -> String { |
| 52 |
self.device.clone() |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
fn partitions_iter() -> anyhow::Result<impl Iterator<Item = Partition>> { |
| 57 |
let mounts = bindings::mounts()?; |
| 58 |
|
| 59 |
unsafe fn ptr_to_cow<'a>(ptr: *const i8) -> std::borrow::Cow<'a, str> { |
| 60 |
unsafe { CStr::from_ptr(ptr).to_string_lossy() } |
| 61 |
} |
| 62 |
|
| 63 |
Ok(mounts.into_iter().map(|stat| { |
| 64 |
|
| 65 |
let device = unsafe { ptr_to_cow(stat.f_mntfromname.as_ptr()).to_string() }; |
| 66 |
|
| 67 |
let fs_type = { |
| 68 |
|
| 69 |
let fs_type_str = unsafe { ptr_to_cow(stat.f_fstypename.as_ptr()) }; |
| 70 |
FileSystem::from_str(&fs_type_str).unwrap_or(FileSystem::Other(fs_type_str.to_string())) |
| 71 |
}; |
| 72 |
|
| 73 |
let mount_point = { |
| 74 |
|
| 75 |
let path_str = unsafe { ptr_to_cow(stat.f_mntonname.as_ptr()).to_string() }; |
| 76 |
PathBuf::from(path_str) |
| 77 |
}; |
| 78 |
|
| 79 |
Partition { |
| 80 |
device, |
| 81 |
mount_point, |
| 82 |
fs_type, |
| 83 |
} |
| 84 |
})) |
| 85 |
} |
| 86 |
|
| 87 |
#[expect(dead_code)] |
| 88 |
|
| 89 |
pub(crate) fn partitions() -> anyhow::Result<Vec<Partition>> { |
| 90 |
partitions_iter().map(|iter| iter.collect()) |
| 91 |
} |
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
pub(crate) fn physical_partitions() -> anyhow::Result<Vec<Partition>> { |
| 96 |
partitions_iter().map(|iter| { |
| 97 |
iter.filter(|partition| partition.fs_type().is_physical()) |
| 98 |
.collect() |
| 99 |
}) |
| 100 |
} |