Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance Wasmer::XxxArray #15

Merged
merged 3 commits into from
Jun 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,11 @@ pub extern "C" fn Init_wasmer() {

// Declare the `[]` (get) method.
itself.def("[]", memory::view::$mod_name::ruby_memory_view_get);
});

// Declare the `each` method.
itself.def("each", memory::view::$mod_name::ruby_memory_view_each);
})
.include("Enumerable");
};
}

Expand Down
17 changes: 16 additions & 1 deletion src/memory/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ macro_rules! memory_view {
use lazy_static::lazy_static;
use rutie::{
class, methods, wrappable_struct, AnyException, Exception, Fixnum, Integer,
NilClass, Object,
NilClass, Object, VM,
};
use std::{mem::size_of, rc::Rc};
use wasmer_runtime as runtime;
Expand Down Expand Up @@ -71,6 +71,15 @@ macro_rules! memory_view {
Ok(view[offset + index].get())
}
}

pub fn each(&self) {
let view = self.memory.view::<$wasm_type>();

for nth in self.offset..view.len() {
let value = view[nth].get() as i64;
VM::yield_object(Integer::from(value));
}
}
}

wrappable_struct!(MemoryView, MemoryViewWrapper, MEMORY_VIEW_WRAPPER);
Expand Down Expand Up @@ -117,6 +126,12 @@ macro_rules! memory_view {
))
})
}

fn ruby_memory_view_each() -> RubyMemoryView {
let memory_view = _itself.get_data(&*MEMORY_VIEW_WRAPPER);
memory_view.each();
_itself
}
);
}
};
Expand Down
24 changes: 16 additions & 8 deletions tests/memory_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -99,20 +99,28 @@ def test_hello_world
nth = 0
string = ""

while true
char = memory[nth]

if 0 == char
break
end

string += char.chr
memory.each do |char|
break if 0 == char
string << char.chr
nth += 1
end

assert_equal 13, nth
assert_equal "Hello, World!", string
end

def test_enumerable
instance = Wasmer::Instance.new self.bytes
memory = instance.memory.int16_view
memory[0] = 1
memory[1] = 10
memory[2] = 100
memory[3] = 1000
memory[5] = 2
sum = memory.take_while{|x| x > 0}.inject(0, &:+)
assert_equal 1111, sum
end

def test_views_share_the_same_buffer
instance = Wasmer::Instance.new self.bytes
int8 = instance.memory.int8_view
Expand Down