Skip to content

Instantly share code, notes, and snippets.

@myobie
Created April 27, 2020 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myobie/94ca667c1216b2fae3b72a7d72446220 to your computer and use it in GitHub Desktop.
Save myobie/94ca667c1216b2fae3b72a7d72446220 to your computer and use it in GitHub Desktop.
defmodule Example.RandomTest do
use ExUnit.Case
test "loads wasm file" do
{:ok, bytes} = File.read("priv/vendor/needs-random.wasm")
{:ok, agent} = Agent.start_link(fn -> nil end)
{:ok, instance} =
Wasmex.start_link(%{
bytes: bytes,
imports: %{
"wasi_snapshot_preview1" => %{
"proc_exit" => {[:i32], [], fn _ -> throw("proc_exit") end},
"random_get" =>
{[:i32, :i32], [:i32],
fn address, size ->
case random_bytes(agent, address, size) do
{:error, error} -> throw("error: #{error}")
{:ok, value} -> value
end
end}
}
}
})
:ok = Agent.update(agent, fn _old -> instance end)
assert {:ok, [0]} == Wasmex.call_function(instance, "test_random", [])
end
defp random_bytes(agent, address, size) do
bytes = :crypto.strong_rand_bytes(size)
instance = Agent.get(agent, fn state -> state end)
case instance do
nil ->
{:error, :instance_not_setup}
instance ->
{:ok, memory} = Wasmex.memory(instance, :uint8, 0)
bytes
|> :binary.bin_to_list()
|> Enum.with_index()
|> Enum.each(fn {byte, index} ->
Wasmex.Memory.set(memory, address + index, byte)
end)
{:ok, 0}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment