Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Elixir

wasi/elixir.livemd

Elixir

Mix.install([
  {:wasmex, "~> 0.8.3"}
])

WASM

{:ok, store} =
  Wasmex.Store.new_wasi(%Wasmex.Wasi.WasiOptions{
    preopen: [
      %Wasmex.Wasi.PreopenOptions{path: "..", alias: "."}
    ]
  })
{:ok, #Wasmex.StoreOrCaller<#Reference<0.774482462.2183135239.82196>>}
wasm_file = File.read!("../target/wasm32-wasi/debug/automata.wasm")
{:ok, module} = Wasmex.Module.compile(store, wasm_file)
{:ok, pid} = Wasmex.start_link(%{store: store, module: module})
{:ok, memory} = Wasmex.memory(pid)
{:ok, #Wasmex.Memory<#Reference<0.774482462.2183135239.82237>>}
Wasmex.Module.exports(module)
%{
  "__externref_drop_slice" => {:fn, [:i32, :i32], []},
  "__externref_heap_live_count" => {:fn, [], [:i32]},
  "__externref_table_alloc" => {:fn, [], [:i32]},
  "__externref_table_dealloc" => {:fn, [:i32], []},
  "__wbindgen_exn_store" => {:fn, [:i32], []},
  "__wbindgen_free" => {:fn, [:i32, :i32, :i32], []},
  "__wbindgen_malloc" => {:fn, [:i32, :i32], [:i32]},
  "__wbindgen_realloc" => {:fn, [:i32, :i32, :i32, :i32], [:i32]},
  "alloc" => {:fn, [:i32], [:i32]},
  "grep_file" => {:fn, [:i32, :i32, :i32, :i32], [:i64]},
  "memory" => {:memory, %{minimum: 17, shared: false, memory64: false}}
}
file = "./sample.txt"
regex = "\"[^\"]*\""
{:ok, [file_address]} = Wasmex.call_function(pid, "alloc", [String.length(file)])
{:ok, [regex_address]} = Wasmex.call_function(pid, "alloc", [String.length(regex)])
Wasmex.Memory.write_binary(store, memory, file_address, file)
Wasmex.Memory.write_binary(store, memory, regex_address, regex)
:ok
{:ok, [ptr]} =
  Wasmex.call_function(pid, "grep_file", [
    file_address,
    String.length(file),
    regex_address,
    String.length(regex)
  ])

start = Bitwise.&amp;&amp;&amp;(Bitwise.>>>(ptr, 32), 0xFFFFFFFF)
length = Bitwise.&amp;&amp;&amp;(ptr, 0xFFFFFFFF)
4
for i <- 0..(length - 1) do
  <> =
    Wasmex.Memory.read_binary(store, memory, start + i * 8, 4)

  <> =
    Wasmex.Memory.read_binary(store, memory, start + i * 8 + 4, 4)

  Wasmex.Memory.read_string(store, memory, address, length)
end
["\"Esto es un texto entre comillas\"", "\"pero esto también es un texto entre comillas.\"",
 "\"tercero\"", "\"este es el texto final, contiene números como 1 o 18 y emojis como 🙉\""]