ui-automation 0.1.1

Control the User Interface, cross-platform.
Documentation
// Copyright (C) 2024 Tristan Gerritsen <tristan@thewoosh.org>
// All Rights Reserved.

use core::slice;
use std::ffi::c_void;

use super::{CFIndex, CFType};

pub type CFDataRef = *const c_void;

pub struct CFData {
    inner: CFType,
}

impl CFData {
    pub fn from_create(ptr: CFDataRef) -> Option<Self> {
        if ptr.is_null() {
            return None;
        }

        let inner = CFType::from_create(ptr)?;
        Some(Self { inner })
    }

    #[must_use]
    pub fn len(&self) -> usize {
        let length = unsafe { CFDataGetLength(self.inner.ptr()) };
        length as _
    }

    #[must_use]
    pub fn byte_ptr(&self) -> *const u8 {
        unsafe { CFDataGetBytePtr(self.inner.ptr()) }
    }

    #[must_use]
    pub fn as_slice(&self) -> &[u8] {
        let data = self.byte_ptr();

        if data.is_null() {
            return &[];
        }

        unsafe {
            slice::from_raw_parts(data, self.len())
        }
    }
}

extern "C-unwind" {
    pub(super) fn CFDataGetBytePtr(the_data: CFDataRef) -> *const u8;
    pub(super) fn CFDataGetLength(the_data: CFDataRef) -> CFIndex;
}