Class: Wasmtime::Memory::UnsafeSlice

Inherits:
Object
  • Object
show all
Defined in:
ext/src/ruby_api/memory/unsafe_slice.rs

Overview

Represents a slice of a WebAssembly memory. This is useful for creating Ruby strings from WASM memory without any extra memory allocations.

The returned UnsafeSlice lazily reads the underlying memory, meaning that the actual pointer to the string buffer is not materialzed until #to_str is called.

Instance Method Summary collapse

Instance Method Details

#to_memory_viewFiddle::MemoryView

Get this slice as a Fiddle memory view, which can be cheaply read by other Ruby extensions.

Returns:

  • (Fiddle::MemoryView)

    Memory view of the slice.



78
79
80
81
82
83
84
85
86
# File 'ext/src/ruby_api/memory/unsafe_slice.rs', line 78

pub fn to_memory_view(rb_self: Obj<Self>) -> Result<Value, Error> {
    let klass = *memoize!(RClass: {
        let c = fiddle_memory_view_class().unwrap();
        gc::register_mark_object(c);
        c
    });

    klass.new_instance((rb_self,))
}

#to_strString

Gets the memory slice as a Ruby string without copying the underlying buffer.

Returns:

  • (String)

    Binary String of the memory.



93
94
95
96
97
98
99
100
101
102
103
# File 'ext/src/ruby_api/memory/unsafe_slice.rs', line 93

pub fn to_str(rb_self: Obj<Self>) -> Result<Value, Error> {
    let raw_slice = rb_self.get().get_raw_slice()?;
    let id = IVAR_NAME.into_id();
    let rstring = unsafe {
        let val = rb_str_new_static(raw_slice.as_ptr() as _, raw_slice.len() as _);
        rb_ivar_set(val, id.as_raw(), rb_self.as_raw());
        rb_obj_freeze(val)
    };

    Ok(unsafe { Value::from_raw(rstring) })
}