ark-module 0.17.0-pre.18

Ark Wasm module implementation helper
Documentation
//! Utilities to handle Wasm module entrypoint parameters for slices & strings

#![allow(unused_unsafe)] // want to require unsafe blocks in unsafe functions for clarity. tracking issue: https://github.com/rust-lang/rust/issues/71668

/// Interpret Wasm memory ptr and length as a byte slice
///
/// Compared to [`std::slice::from_raw_parts`] this handles null pointers, and requires null pointers for 0 length slice.
/// While [`std::slice::from_raw_parts`] asserts in debug on null pointers for 0 length slices.
///
/// # Safety
///
/// User has to make sure specified lifetime of slice doesnt extend past the lifetime of the memory pointed to
#[doc(hidden)]
pub unsafe fn param_byte_slice<'a>(ptr: *const u8, len: u32) -> &'a [u8] {
    if len > 0 {
        assert!(!ptr.is_null());
        // SAFETY: Sound as we verify no null pointers and alignment is not important for byte slices
        unsafe { std::slice::from_raw_parts(ptr, len as usize) }
    } else {
        &[]
    }
}

/// Interpret Wasm memory ptr and length as a UTF-8 string
///
/// # Safety
///
/// User has to make sure specified lifetime of slice doesnt extend past the lifetime of the memory pointed to
#[doc(hidden)]
pub unsafe fn param_str<'a>(ptr: *const u8, len: u32) -> &'a str {
    // SAFETY: This operates under same lifetime constraints as the calling function describes in its safety contract
    let slice = unsafe { param_byte_slice(ptr, len) };

    // strings have to be UTF-8, this validates it at runtime as cost is small.
    // we could switch to the unsafe unchecked version as host should never send non-UTF8 strings
    std::str::from_utf8(slice).unwrap()
}