Skip to content

Commit

Permalink
feat(instance) Support module without an exported memory.
Browse files Browse the repository at this point in the history
  • Loading branch information
Hywan committed Feb 7, 2020
1 parent 0f72689 commit 48b34a8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 23 deletions.
46 changes: 26 additions & 20 deletions src/instance/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,20 +60,14 @@ methods!(
.to_bytes_unchecked(),
)?;
let exported_functions = ExportedFunctions::new(instance.instance.clone());

let memory = instance
.instance
.exports()
.find_map(|(_, export)| match export {
Export::Memory(memory) => Some(Memory::new(Rc::new(memory))),
_ => None,
})
.ok_or_else(|| {
AnyException::new(
"RuntimeError",
Some("The WebAssembly module has no exported memory."),
)
})?;
let exported_memory =
instance
.instance
.exports()
.find_map(|(_, export)| match export {
Export::Memory(memory) => Some(Memory::new(Rc::new(memory))),
_ => None,
});

let wasmer_module = Module::from_existing("Wasmer");

Expand All @@ -87,11 +81,12 @@ methods!(

ruby_instance.instance_variable_set("@exports", ruby_exported_functions);

let ruby_memory: RubyMemory = wasmer_module
.get_nested_class("Memory")
.wrap_data(memory, &*MEMORY_WRAPPER);

ruby_instance.instance_variable_set("@memory", ruby_memory);
if let Some(exported_memory) = exported_memory {
let ruby_exported_memory: RubyMemory = wasmer_module
.get_nested_class("Memory")
.wrap_data(exported_memory, &*MEMORY_WRAPPER);
ruby_instance.instance_variable_set("@memory", ruby_exported_memory);
}

Ok(ruby_instance)
})
Expand All @@ -108,6 +103,17 @@ methods!(

// Glue code to call the `Instance.memory` getter method.
fn ruby_instance_memory() -> RubyMemory {
unsafe { _itself.instance_variable_get("@memory").to::<RubyMemory>() }
unwrap_or_raise(|| {
let memory = _itself.instance_variable_get("@memory");

if !memory.is_nil() {
Ok(unsafe { memory.to::<RubyMemory>() })
} else {
Err(AnyException::new(
"RuntimeError",
Some("The WebAssembly module has no exported memory."),
))
}
})
}
);
6 changes: 3 additions & 3 deletions tests/instance_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ def test_constructor_needs_bytes
assert_equal "WebAssembly module must be represented by Ruby bytes only.", error.message
end

def test_module_must_have_an_exported_memory
def test_module_without_an_exported_memory
bytes = IO.read File.expand_path("no_memory.wasm", File.dirname(__FILE__)), mode: "rb"
error = assert_raises(RuntimeError) {
bytes = IO.read File.expand_path("no_memory.wasm", File.dirname(__FILE__)), mode: "rb"
Wasmer::Instance.new bytes
Wasmer::Instance.new(bytes).memory
}
assert_equal "The WebAssembly module has no exported memory.", error.message
end
Expand Down

0 comments on commit 48b34a8

Please sign in to comment.