Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.