Mix . install ( [
:orb ,
{ :wasmex , "~> 0.8.3" } ,
{ :mime , "~> 2.0.5" } ,
{ :kino , "~> 0.12.0" }
] )
Define our Mime Type module using Orb
defmodule MimeType do
use Orb
defw ( txt , I32.UnsafePointer , do: MIME . type ( "txt" ) )
defw ( json , I32.UnsafePointer , do: MIME . type ( "json" ) )
defw ( html , I32.UnsafePointer , do: MIME . type ( "html" ) )
defw ( css , I32.UnsafePointer , do: MIME . type ( "css" ) )
defw ( wasm , I32.UnsafePointer , do: MIME . type ( "wasm" ) )
defw ( epub , I32.UnsafePointer , do: MIME . type ( "epub" ) )
defw ( rss , I32.UnsafePointer , do: MIME . type ( "rss" ) )
defw ( atom , I32.UnsafePointer , do: MIME . type ( "atom" ) )
defw ( csv , I32.UnsafePointer , do: MIME . type ( "csv" ) )
defw ( woff2 , I32.UnsafePointer , do: MIME . type ( "woff2" ) )
defw ( pdf , I32.UnsafePointer , do: MIME . type ( "pdf" ) )
defw ( js , I32.UnsafePointer , do: "application/javascript" )
defw ( xml , I32.UnsafePointer , do: "application/xml" )
defw ( sqlite , I32.UnsafePointer , do: "application/vnd.sqlite3" )
end
We can run the WebAssembly module in Elixir using Wasmex
file_extension = "html"
{ :ok , pid } = Wasmex . start_link ( % { bytes: Orb . to_wat ( MimeType ) } )
{ :ok , memory } = Wasmex . memory ( pid )
{ :ok , store } = Wasmex . store ( pid )
byte_count = Wasmex.Memory . size ( store , memory )
bytes = Wasmex.Memory . read_binary ( store , memory , 0 , byte_count )
case Wasmex . call_function ( pid , file_extension , [ ] ) do
{ :ok , [ str_ptr ] } ->
slice = binary_slice ( bytes , str_ptr .. - 1 // 1 )
for ( << chunk :: size ( 8 ) <- slice >> , do: chunk )
|> Enum . take_while ( fn c -> c != 0 end )
|> List . to_string ( )
{ :error , _ } ->
nil
end