defmodule WaParser.LEB128 do
def encode_unsigned(0) do
<<0x00>>
end
def encode_unsigned(int) when int < 0x80 do
<<int>>
end
def encode_unsigned(int) do
encode_unsigned(int, [])
end
defp encode_unsigned(0, acc) do
size = Enum.count(acc)
acc
|> Enum.reverse()
|> Enum.with_index(fn bits, index ->
if index < size - 1 do
<<1::1, bits::7>>
else
<<bits>>
end
end)
|> Enum.into(<<>>)
end
defp encode_unsigned(int, acc) do
seven_bits = Bitwise.band(int, 0x7F)
int = Bitwise.bsr(int, 7)
encode_unsigned(int, [seven_bits | acc])
end
end