ark-api-ffi 0.16.0

Ark low-level Wasm FFI API
Documentation
//! Core entrypoints shared by all module types

use bytemuck::Pod;
use bytemuck::Zeroable;

/// `ark_initialize` - Initialize module
///
/// This gets called once when a module is started and enables the module to prepare its state and resources.
/// If something goes wrong, the module can communicate that by panicking, and then it will be unloaded.
///
/// # Example
///
/// ```
/// #[no_mangle]
/// pub unsafe fn ark_initialize() {
/// }
/// ```
pub type InitializeFn = fn();

/// `ark_alloc` - Allocate a raw buffer in the module
///
/// This is called from the host to be able to allocate and write memory
/// in a module that it then can pass in as a pointer when calling other
/// entrypoint functions in the module
///
/// # Example
///
/// ```
/// #[no_mangle]
/// pub unsafe fn ark_alloc(size: usize, alignment: usize) -> *mut u8 {
///     std::ptr::null_mut()
/// }
/// ```
pub type AllocFn = fn(size: u32, alignment: u32) -> *mut u8;

/// `ark_free` - Free a raw buffer in the module
///
/// This is intended to be used on memory allocated with `ark_alloc`
///
/// # Example
///
/// ```
/// #[no_mangle]
/// pub unsafe fn ark_free(ptr: *mut u8, size: usize, alignment: usize) {
/// }
/// ```
pub type FreeFn = fn(ptr: *mut u8, size: u32, alignment: u32);

/// `ark_register_panic_hook` - Register module specific panic hook
///
/// This gets called once when a module is started (or possibly by tests), and
/// enables the module to catch panics and report them back to the host.
pub type RegisterPanicHookFn = fn();

/// Type for the data pointed to by the return value of `ark_get_alloc_stats`.
#[derive(Debug, Copy, Clone, Default, Pod, Zeroable)]
#[repr(C)]
pub struct AllocStats {
    // These are all cumulative.
    pub cumul_alloc_count: u64,
    pub cumul_alloc_size: u64,
    pub cumul_free_count: u64,
    pub cumul_free_size: u64,
}

// Utilities to compute some common stats from the cumulative sums.
impl AllocStats {
    pub fn current_allocated_size(&self) -> usize {
        (self.cumul_alloc_size - self.cumul_free_size) as usize
    }

    pub fn current_allocation_count(&self) -> usize {
        (self.cumul_alloc_count - self.cumul_free_count) as usize
    }
}

/// `ark_get_alloc_stats` - Returns a pointer into Wasm memory to an instance of the `AllocStats` data structure.
///
/// `AllocStats` counts allocations and frees, so the host can get an idea of current
/// memory use in a module.
pub type GetAllocStatsFn = fn() -> u32;

pub const INITIALIZE: &str = "ark_initialize";
pub const ALLOC: &str = "ark_alloc";
pub const FREE: &str = "ark_free";
pub const REGISTER_PANIC_HOOK: &str = "ark_register_panic_hook";
pub const GET_ALLOC_STATS: &str = "ark_get_alloc_stats";