use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
use std::os::unix::fs::MetadataExt;
use std::path::PathBuf;
use objc2_core_foundation::{
CFDictionary, CFRetained, CFURL, kCFURLVolumeIsEjectableKey, kCFURLVolumeIsInternalKey,
kCFURLVolumeIsRemovableKey, kCFURLVolumeNameKey, kCFURLVolumeTotalCapacityKey,
};
use crate::{Disk, DiskKind, DiskRefreshKind};
use super::DiskInner;
#[cfg(target_os = "macos")]
use super::bsd_name::get_bsd_name;
use super::properties::{get_available_volume_space, get_bool_value, get_int_value, get_str_value};
pub(super) unsafe fn new_disk(
disk: Option<&mut Disk>,
mount_point: PathBuf,
volume_url: CFRetained<CFURL>,
c_disk: libc::statfs,
disk_props: &CFDictionary,
refresh_kind: DiskRefreshKind,
uuid: OsString,
) -> Option<Disk> {
let (total_space, available_space) = if refresh_kind.storage() {
(
unsafe { get_int_value(disk_props, kCFURLVolumeTotalCapacityKey) },
get_available_volume_space(disk_props),
)
} else {
(None, None)
};
if let Some(disk) = disk {
let disk = &mut disk.inner;
if let Some(total_space) = total_space {
disk.total_space = total_space;
}
if let Some(available_space) = available_space {
disk.available_space = available_space;
}
disk.refresh_io(refresh_kind);
disk.refresh_kind(refresh_kind);
disk.updated = true;
return None;
}
let name = unsafe { get_str_value(disk_props, kCFURLVolumeNameKey) }.map(OsString::from)?;
let file_system = {
let len = c_disk
.f_fstypename
.iter()
.position(|&b| b == 0)
.unwrap_or(c_disk.f_fstypename.len());
OsString::from_vec(
c_disk.f_fstypename[..len]
.iter()
.map(|c| *c as u8)
.collect(),
)
};
#[cfg(target_os = "macos")]
let bsd_name = get_bsd_name(&c_disk);
let ejectable =
unsafe { get_bool_value(disk_props, kCFURLVolumeIsEjectableKey) }.unwrap_or(false);
let removable =
unsafe { get_bool_value(disk_props, kCFURLVolumeIsRemovableKey) }.unwrap_or(false);
let is_removable = if ejectable || removable {
true
} else {
let internal =
unsafe { get_bool_value(disk_props, kCFURLVolumeIsInternalKey) }.unwrap_or_default();
!internal
};
let device_id = std::fs::metadata(mount_point.as_path())
.ok()
.map(|metadata| metadata.dev());
let is_read_only = (c_disk.f_flags & libc::MNT_RDONLY as u32) != 0;
let mut disk = DiskInner {
type_: DiskKind::Unknown(-1),
name,
id: device_id,
#[cfg(target_os = "macos")]
bsd_name,
file_system,
mount_point,
volume_url,
total_space: total_space.unwrap_or(0),
available_space: available_space.unwrap_or(0),
is_removable,
is_read_only,
read_bytes: 0,
written_bytes: 0,
old_read_bytes: 0,
old_written_bytes: 0,
updated: true,
uuid,
};
disk.refresh_kind(refresh_kind);
disk.refresh_io(refresh_kind);
Some(Disk { inner: disk })
}