use core::{
ffi::{CStr, c_char, c_void},
marker::PhantomData,
};
use super::{ffi, kern_error};
use crate::Result;
pub(super) struct Cf(ffi::CfRef);
impl Cf {
pub(super) fn new(object: ffi::CfRef) -> Option<Cf> {
if object.is_null() {
None
} else {
Some(Cf(object))
}
}
pub(super) fn string(what: &'static str, text: &str) -> Result<Cf> {
let len = ffi::CfIndex::try_from(text.len()).unwrap_or(0);
let object = unsafe {
ffi::CFStringCreateWithBytes(
core::ptr::null(),
text.as_ptr(),
len,
ffi::CF_STRING_ENCODING_UTF8,
0,
)
};
Cf::new(object).ok_or_else(|| kern_error(what, "CFStringCreateWithBytes", 0))
}
pub(super) fn raw(&self) -> ffi::CfRef {
self.0
}
pub(super) fn get(&self) -> Ref<'_> {
Ref {
object: self.0,
owner: PhantomData,
}
}
pub(super) fn lent(&self, object: ffi::CfRef) -> Option<Ref<'_>> {
(!object.is_null()).then_some(Ref {
object,
owner: PhantomData,
})
}
}
impl Drop for Cf {
fn drop(&mut self) {
unsafe { ffi::CFRelease(self.0) };
}
}
#[derive(Clone, Copy)]
pub(super) struct Ref<'a> {
object: ffi::CfRef,
owner: PhantomData<&'a Cf>,
}
impl<'a> Ref<'a> {
fn is(self, type_id: ffi::CfTypeId) -> bool {
let id = unsafe { ffi::CFGetTypeID(self.object) };
id == type_id
}
pub(super) fn raw(self) -> ffi::CfRef {
self.object
}
pub(super) fn is_dictionary(self) -> bool {
self.is(ffi::CFDictionaryGetTypeID())
}
pub(super) fn value(self, key: &Cf) -> Option<Ref<'a>> {
if !self.is_dictionary() {
return None;
}
let object = unsafe { ffi::CFDictionaryGetValue(self.object, key.raw()) };
(!object.is_null()).then_some(Ref {
object,
owner: PhantomData,
})
}
pub(super) fn items(self, max: usize) -> impl Iterator<Item = Ref<'a>> {
let count = if self.is(ffi::CFArrayGetTypeID()) {
let count = unsafe { ffi::CFArrayGetCount(self.object) };
count.clamp(0, ffi::CfIndex::try_from(max).unwrap_or(ffi::CfIndex::MAX))
} else {
0
};
(0..count).filter_map(move |index| {
let object = unsafe { ffi::CFArrayGetValueAtIndex(self.object, index) };
(!object.is_null()).then_some(Ref {
object,
owner: PhantomData,
})
})
}
pub(super) fn int(self) -> Option<i64> {
if !self.is(ffi::CFNumberGetTypeID()) {
return None;
}
let mut n: i64 = 0;
let exact = unsafe {
ffi::CFNumberGetValue(
self.object,
ffi::CF_NUMBER_SINT64_TYPE,
(&raw mut n).cast::<c_void>(),
)
};
(exact != 0).then_some(n)
}
pub(super) fn flag(self) -> Option<bool> {
if !self.is(ffi::CFBooleanGetTypeID()) {
return None;
}
let value = unsafe { ffi::CFBooleanGetValue(self.object) };
Some(value != 0)
}
pub(super) fn text(self, buf: &mut [u8]) -> Option<&[u8]> {
if !self.is(ffi::CFStringGetTypeID()) {
return None;
}
let size = ffi::CfIndex::try_from(buf.len()).ok()?;
let ok = unsafe {
ffi::CFStringGetCString(
self.object,
buf.as_mut_ptr().cast::<c_char>(),
size,
ffi::CF_STRING_ENCODING_UTF8,
)
};
if ok == 0 {
return None;
}
let end = buf.iter().position(|&b| b == 0)?;
Some(&buf[..end])
}
pub(super) fn data(self) -> Option<&'a [u8]> {
if !self.is(ffi::CFDataGetTypeID()) {
return None;
}
let len = usize::try_from(unsafe { ffi::CFDataGetLength(self.object) }).ok()?;
let bytes = unsafe { ffi::CFDataGetBytePtr(self.object) };
if bytes.is_null() {
return None;
}
Some(unsafe { core::slice::from_raw_parts(bytes, len) })
}
}
pub(super) struct Io(pub(super) ffi::IoObject);
impl Io {
pub(super) fn new(object: ffi::IoObject) -> Option<Io> {
if object == 0 { None } else { Some(Io(object)) }
}
pub(super) fn matching(matching: ffi::CfRef) -> Option<Io> {
if matching.is_null() {
return None;
}
let service =
unsafe { ffi::IOServiceGetMatchingService(ffi::IO_MAIN_PORT_DEFAULT, matching) };
Io::new(service)
}
pub(super) fn service(class: &CStr) -> Option<Io> {
let matching = unsafe { ffi::IOServiceMatching(class.as_ptr()) };
Io::matching(matching)
}
pub(super) fn at_path(path: &CStr) -> Option<Io> {
let entry =
unsafe { ffi::IORegistryEntryFromPath(ffi::IO_MAIN_PORT_DEFAULT, path.as_ptr()) };
Io::new(entry)
}
pub(super) fn bsd_device(name: &CStr) -> Option<Io> {
let matching =
unsafe { ffi::IOBSDNameMatching(ffi::IO_MAIN_PORT_DEFAULT, 0, name.as_ptr()) };
Io::matching(matching)
}
pub(super) fn property(&self, key: &Cf) -> Option<Cf> {
Cf::new(unsafe {
ffi::IORegistryEntryCreateCFProperty(self.0, key.raw(), core::ptr::null(), 0)
})
}
pub(super) fn parent(&self) -> Option<Io> {
let mut parent: ffi::IoObject = 0;
let kr = unsafe {
ffi::IORegistryEntryGetParentEntry(self.0, c"IOService".as_ptr(), &raw mut parent)
};
let parent = Io::new(parent)?;
(kr == ffi::KERN_SUCCESS).then_some(parent)
}
pub(super) fn child(&self) -> Option<Io> {
let mut child: ffi::IoObject = 0;
let kr = unsafe {
ffi::IORegistryEntryGetChildEntry(self.0, c"IOService".as_ptr(), &raw mut child)
};
let child = Io::new(child)?;
(kr == ffi::KERN_SUCCESS).then_some(child)
}
}
impl Drop for Io {
fn drop(&mut self) {
unsafe { ffi::IOObjectRelease(self.0) };
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_iokit_null_is_none_and_never_released() {
assert!(Cf::new(core::ptr::null()).is_none());
assert!(Io::new(0).is_none());
let platform = Io::service(c"IOPlatformExpertDevice").unwrap();
let missing = Cf::string("test", "sys-lib: no such property").unwrap();
assert!(platform.property(&missing).is_none());
}
}