ark-module 0.17.0-pre.18

Ark Wasm module implementation helper
Documentation
use ark_api_ffi as ffi;

/// A panic hook for use with [`std::panic::set_hook`] which registers the panic
/// with the core host API so that it can be displayed in some way by the host
fn hook(info: &std::panic::PanicInfo<'_>) {
    let error_msg = info
        .payload()
        .downcast_ref::<String>()
        .map(String::as_str)
        .or_else(|| info.payload().downcast_ref::<&'static str>().copied())
        .unwrap_or("");
    let location = info.location();

    let (file_ptr, file_len, line, column) = match location {
        Some(loc) => (
            loc.file().as_ptr(),
            loc.file().len() as u32,
            loc.line(),
            loc.column(),
        ),
        None => (std::ptr::null(), 0, 0, 0),
    };

    // SAFETY: Calling FFI with well defined parameters
    unsafe {
        let _ = ffi::core_v2::core__register_panic(
            error_msg.as_ptr(),
            error_msg.len() as u32,
            file_ptr,
            file_len,
            line,
            column,
        );
    }
}

#[no_mangle]
#[doc(hidden)]
#[allow(clippy::disallowed_types)] // we generally prefer `parking_lot::Once`, but in Wasm this is fine and avoids dependency
pub unsafe fn ark_register_panic_hook() {
    use std::sync::Once;
    static SET_HOOK: Once = Once::new();
    SET_HOOK.call_once(|| {
        std::panic::set_hook(Box::new(hook));
    });
}