sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use crate::sys::utils::{IOReleaser, MAIN_PORT};

use objc2_core_foundation::{CFDictionary, CFRetained};
use objc2_io_kit::io_connect_t;
use objc2_io_kit::{
    IOIteratorNext, IOServiceClose, IOServiceGetMatchingServices, IOServiceMatching, IOServiceOpen,
    io_iterator_t, kIOReturnSuccess,
};

pub(crate) struct IoService(io_connect_t);

impl IoService {
    fn new(obj: io_connect_t) -> Option<Self> {
        if obj == 0 { None } else { Some(Self(obj)) }
    }

    pub(super) fn inner(&self) -> io_connect_t {
        self.0
    }

    // Code from https://github.com/Chris911/iStats.
    pub(super) fn new_connection() -> Option<Self> {
        let mut iterator: io_iterator_t = 0;

        unsafe {
            let Some(matching) = IOServiceMatching(c"AppleSMC".as_ptr()) else {
                sinf_debug!("IOServiceMatching call failed, `AppleSMC` not found");
                return None;
            };
            let matching = CFRetained::<CFDictionary>::from(&matching);

            let result = IOServiceGetMatchingServices(*MAIN_PORT, Some(matching), &mut iterator);
            if result != kIOReturnSuccess {
                sinf_debug!("Error: IOServiceGetMatchingServices() = {result}");
                return None;
            }
            let iterator = match IOReleaser::new(iterator) {
                Some(i) => i,
                None => {
                    sinf_debug!(
                        "Component error: IOServiceGetMatchingServices succeeded but returned invalid descriptor"
                    );
                    return None;
                }
            };

            let device = match IOReleaser::new(IOIteratorNext(iterator.inner())) {
                Some(d) => d,
                None => {
                    sinf_debug!("Error: no SMC found");
                    return None;
                }
            };

            let mut conn = 0;
            let result = IOServiceOpen(
                device.inner(),
                #[allow(deprecated)]
                libc::mach_task_self(),
                0,
                &mut conn,
            );
            if result != kIOReturnSuccess {
                sinf_debug!("Error: IOServiceOpen() = {}", result);
                return None;
            }
            let conn = IoService::new(conn);
            if conn.is_none() {
                sinf_debug!("Error: IOServiceOpen() succeeded but returned invalid descriptor...");
            }
            conn
        }
    }
}

impl Drop for IoService {
    fn drop(&mut self) {
        IOServiceClose(self.0);
    }
}