sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::ptr;

use libc::c_void;
use objc2_core_foundation::{
    CFArray, CFBoolean, CFDictionary, CFNumber, CFRetained, CFString, CFURL, kCFTypeArrayCallBacks,
    kCFURLVolumeAvailableCapacityForImportantUsageKey, kCFURLVolumeAvailableCapacityKey,
};

pub(super) unsafe fn build_requested_properties(
    properties: &[Option<&CFString>],
) -> Option<CFRetained<CFArray>> {
    unsafe {
        CFArray::new(
            None,
            properties.as_ptr() as *mut *const c_void,
            properties.len() as _,
            &kCFTypeArrayCallBacks,
        )
    }
}

pub(super) fn get_disk_properties(
    volume_url: &CFURL,
    requested_properties: &CFArray,
) -> Option<CFRetained<CFDictionary>> {
    unsafe { volume_url.resource_properties_for_keys(Some(requested_properties), ptr::null_mut()) }
}

pub(super) fn get_available_volume_space(disk_props: &CFDictionary) -> Option<u64> {
    // `AvailableCapacityForImportantUsage` is preferred over `AvailableCapacity` because it accounts for more of the system's properties, such as the trash and system-managed caches.
    unsafe {
        get_int_value(
            disk_props,
            kCFURLVolumeAvailableCapacityForImportantUsageKey,
        )
        .filter(|bytes| *bytes != 0)
        .or_else(|| get_int_value(disk_props, kCFURLVolumeAvailableCapacityKey))
    }
}

pub(super) unsafe fn get_dict_value<T, F: FnOnce(*const c_void) -> Option<T>>(
    dict: &CFDictionary,
    key: Option<&CFString>,
    callback: F,
) -> Option<T> {
    let mut value = std::ptr::null();
    let key: *const CFString = key.map(|key| key as *const CFString).unwrap_or(ptr::null());
    if unsafe { dict.value_if_present(key.cast(), &mut value) } {
        callback(value)
    } else {
        None
    }
}

pub(crate) unsafe fn get_str_value(dict: &CFDictionary, key: Option<&CFString>) -> Option<String> {
    unsafe {
        get_dict_value(dict, key, |v| {
            let v = &*v.cast::<CFString>();
            Some(v.to_string())
        })
    }
}

pub(super) unsafe fn get_bool_value(dict: &CFDictionary, key: Option<&CFString>) -> Option<bool> {
    unsafe {
        get_dict_value(dict, key, |v| {
            let v = &*v.cast::<CFBoolean>();
            Some(v.as_bool())
        })
    }
}

pub(crate) unsafe fn get_int_value(dict: &CFDictionary, key: Option<&CFString>) -> Option<u64> {
    unsafe {
        get_dict_value(dict, key, |v| {
            let v = &*v.cast::<CFNumber>();
            Some(v.as_i64()? as u64)
        })
    }
}