pub fn enable() -> bool {
imp::enable()
}
#[cfg(not(target_os = "macos"))]
mod imp {
pub fn enable() -> bool {
false
}
}
#[cfg(target_os = "macos")]
mod imp {
use std::ffi::{c_char, c_void, CStr};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::OnceLock;
#[repr(C)]
struct Object {
_private: [u8; 0],
}
type Id = *mut Object;
type Sel = *const c_void;
type Imp = unsafe extern "C" fn();
type NewLibrary = unsafe extern "C" fn(Id, Sel, Id, Id, *mut Id) -> Id;
#[link(name = "objc", kind = "dylib")]
unsafe extern "C" {
fn sel_registerName(name: *const c_char) -> Sel;
fn object_getClass(obj: Id) -> Id;
fn class_getInstanceMethod(cls: Id, sel: Sel) -> *mut c_void;
fn method_getImplementation(m: *mut c_void) -> Option<Imp>;
fn method_setImplementation(m: *mut c_void, imp: Imp) -> Option<Imp>;
fn objc_getClass(name: *const c_char) -> Id;
fn objc_msgSend();
}
#[link(name = "Metal", kind = "framework")]
unsafe extern "C" {
fn MTLCreateSystemDefaultDevice() -> Id;
}
const PRAGMAS: &str = "#pragma METAL fp math_mode(safe)\n#pragma METAL fp contract(off)\n";
static ORIGINAL: AtomicUsize = AtomicUsize::new(0);
static INSTALLED: OnceLock<bool> = OnceLock::new();
fn sel(name: &CStr) -> Sel {
unsafe { sel_registerName(name.as_ptr()) }
}
unsafe extern "C" fn new_library(
this: Id,
cmd: Sel,
source: Id,
options: Id,
error: *mut Id,
) -> Id {
let original: NewLibrary = unsafe { std::mem::transmute(ORIGINAL.load(Ordering::Acquire)) };
let send_id: unsafe extern "C" fn(Id, Sel) -> Id =
unsafe { std::mem::transmute(objc_msgSend as unsafe extern "C" fn()) };
let utf8: unsafe extern "C" fn(Id, Sel) -> *const c_char =
unsafe { std::mem::transmute(objc_msgSend as unsafe extern "C" fn()) };
let from_utf8: unsafe extern "C" fn(Id, Sel, *const c_char) -> Id =
unsafe { std::mem::transmute(objc_msgSend as unsafe extern "C" fn()) };
let set_u64: unsafe extern "C" fn(Id, Sel, u64) =
unsafe { std::mem::transmute(objc_msgSend as unsafe extern "C" fn()) };
let responds: unsafe extern "C" fn(Id, Sel, Sel) -> i8 =
unsafe { std::mem::transmute(objc_msgSend as unsafe extern "C" fn()) };
let text = unsafe { utf8(source, sel(c"UTF8String")) };
let strict = if text.is_null() {
source
} else {
let mut s = String::from(PRAGMAS);
s.push_str(&unsafe { CStr::from_ptr(text) }.to_string_lossy());
s.push('\0');
unsafe {
from_utf8(
objc_getClass(c"NSString".as_ptr()),
sel(c"stringWithUTF8String:"),
s.as_ptr().cast(),
)
}
};
let options = if options.is_null() {
unsafe {
send_id(
send_id(objc_getClass(c"MTLCompileOptions".as_ptr()), sel(c"new")),
sel(c"autorelease"),
)
}
} else {
options
};
for (setter, value) in [
(c"setMathMode:", 0u64),
(c"setMathFloatingPointFunctions:", 1),
] {
if unsafe { responds(options, sel(c"respondsToSelector:"), sel(setter)) } != 0 {
unsafe { set_u64(options, sel(setter), value) };
}
}
if unsafe {
responds(
options,
sel(c"respondsToSelector:"),
sel(c"setFastMathEnabled:"),
)
} != 0
{
let set_bool: unsafe extern "C" fn(Id, Sel, i8) =
unsafe { std::mem::transmute(objc_msgSend as unsafe extern "C" fn()) };
if unsafe { responds(options, sel(c"respondsToSelector:"), sel(c"setMathMode:")) } == 0
{
unsafe { set_bool(options, sel(c"setFastMathEnabled:"), 0) };
}
}
unsafe { original(this, cmd, strict, options, error) }
}
pub fn enable() -> bool {
*INSTALLED.get_or_init(|| unsafe {
let device = MTLCreateSystemDefaultDevice();
if device.is_null() {
return false;
}
let class = object_getClass(device);
let method =
class_getInstanceMethod(class, sel(c"newLibraryWithSource:options:error:"));
let release: unsafe extern "C" fn(Id, Sel) =
std::mem::transmute(objc_msgSend as unsafe extern "C" fn());
release(device, sel(c"release"));
let Some(previous) = (!method.is_null())
.then(|| method_getImplementation(method))
.flatten()
else {
return false;
};
ORIGINAL.store(previous as usize, Ordering::Release);
let ours: NewLibrary = new_library;
method_setImplementation(method, std::mem::transmute::<NewLibrary, Imp>(ours));
true
})
}
}