Skip to content

Commit

Permalink
doc(examples) Add the greet example.
Browse files Browse the repository at this point in the history
  • Loading branch information
Hywan committed May 21, 2019
1 parent fd1855c commit 49642ef
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 0 deletions.
54 changes: 54 additions & 0 deletions examples/greet.rb
@@ -0,0 +1,54 @@
# coding: utf-8
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)

require "wasmer"

# Instantiates the module.
file = File.expand_path "greet.wasm", File.dirname(__FILE__)
bytes = IO.read file, mode: "rb"
instance = Wasmer::Instance.new bytes

# Set the subject to greet.
subject = "Wasmer 💎".bytes
length_of_subject = subject.length

# Allocate memory for the subject, and get a pointer to it.
input_pointer = instance.exports.allocate length_of_subject

# Write the subject into the memory.
memory = instance.memory.uint8_view input_pointer

for nth in 0..length_of_subject - 1
memory[nth] = subject[nth]
end

# C-string terminates by NULL.
memory[length_of_subject] = 0

# Run the `greet` function. Give the pointer to the subject.
output_pointer = instance.exports.greet input_pointer

# Read the result of the `greet` function.
memory = instance.memory.uint8_view output_pointer

output = ""
nth = 0

while true
char = memory[nth]

if 0 == char
break
end

output += char.chr
nth += 1
end

length_of_output = nth

puts output

# Deallocate the subject, and the output.
instance.exports.deallocate(input_pointer, length_of_subject)
instance.exports.deallocate(output_pointer, length_of_output)
29 changes: 29 additions & 0 deletions examples/greet.rs
@@ -0,0 +1,29 @@
use std::ffi::{CStr, CString};
use std::mem;
use std::os::raw::{c_char, c_void};

#[no_mangle]
pub extern fn allocate(size: usize) -> *mut c_void {
let mut buffer = Vec::with_capacity(size);
let pointer = buffer.as_mut_ptr();
mem::forget(buffer);

pointer as *mut c_void
}

#[no_mangle]
pub extern fn deallocate(pointer: *mut c_void, capacity: usize) {
unsafe {
let _ = Vec::from_raw_parts(pointer, 0, capacity);
}
}

#[no_mangle]
pub extern fn greet(subject: *mut c_char) -> *mut c_char {
let subject = unsafe { CStr::from_ptr(subject).to_bytes().to_vec() };
let mut output = b"Hello, ".to_vec();
output.extend(&subject);
output.extend(&[b'!']);

unsafe { CString::from_vec_unchecked(output) }.into_raw()
}
Binary file added examples/greet.wasm
Binary file not shown.

0 comments on commit 49642ef

Please sign in to comment.