use objc2::runtime::AnyObject;
use std::ffi::c_void;
use super::runtime::get_class;
use crate::msg_send;
pub fn nsdata_from_bytes(bytes: &[u8]) -> *mut AnyObject {
unsafe {
let cls = get_class("NSData").expect("NSData class not found");
let alloc = msg_send!(cls, alloc);
let sel = objc2::sel!(initWithBytes:length:);
let func: unsafe extern "C" fn(
*mut AnyObject,
objc2::runtime::Sel,
*const c_void,
usize,
) -> *mut AnyObject = std::mem::transmute(super::runtime::objc_msgSend as *const c_void);
func(alloc, sel, bytes.as_ptr() as *const c_void, bytes.len())
}
}
#[must_use]
pub fn nsdata_to_vec(obj: *mut AnyObject) -> Vec<u8> {
if obj.is_null() {
return Vec::new();
}
unsafe {
let len_sel = objc2::sel!(length);
let len_func: unsafe extern "C" fn(*const AnyObject, objc2::runtime::Sel) -> usize =
std::mem::transmute(super::runtime::objc_msgSend as *const c_void);
let len = len_func(obj as *const AnyObject, len_sel);
if len == 0 {
return Vec::new();
}
let bytes_sel = objc2::sel!(bytes);
let bytes_func: unsafe extern "C" fn(
*const AnyObject,
objc2::runtime::Sel,
) -> *const c_void = std::mem::transmute(super::runtime::objc_msgSend as *const c_void);
let ptr = bytes_func(obj as *const AnyObject, bytes_sel).cast::<u8>();
if ptr.is_null() {
return Vec::new();
}
std::slice::from_raw_parts(ptr, len).to_vec()
}
}