56ZUOVSM6J5FLDA5VRM3R57IRJF5GMRKVXJOD2BF7WRH53E43A6AC
end
test "Encode signed" do
assert WaParser.LEB128.encode_signed(0) == <<0x00>>
assert WaParser.LEB128.encode_signed(123_456) == <<0xC0, 0xC4, 0x07>>
assert WaParser.LEB128.encode_signed(-123_456) == <<0xC0, 0xBB, 0x78>>
end
test "Decode signed" do
assert WaParser.LEB128.decode_signed(<<0x00>>) == 0
assert WaParser.LEB128.decode_signed(<<0xC0, 0xC4, 0x07>>) == 123_456
assert WaParser.LEB128.decode_signed(<<0xC0, 0xBB, 0x78>>) == -123_456
acc
|> Enum.reverse()
|> Enum.with_index(fn bits, index ->
if index < size - 1 do
<<1::1, bits::7>>
defp decode_unsigned(<<1::1, byte::7, rest::bytes>>, acc) do
decode_unsigned(rest, <<byte::7, acc::bitstring>>)
end
def encode_signed(0) do
<<0x00>>
end
def encode_signed(int) do
int |> to_bitstring |> seven_bits_encoding
end
defp to_bitstring(int) do
abs =
if int < 0 do
int * -1
defp encode_unsigned(int, acc) do
seven_bits = Bitwise.band(int, 0x7F)
int = Bitwise.bsr(int, 7)
encode_unsigned(int, [seven_bits | acc])
defp seven_bits_encoding(<<sb::size(7), rest::bitstring>>, acc) do
byte =
case acc do
[] -> <<sb>>
_ -> <<1::1, sb::7>>
end
seven_bits_encoding(rest, [byte | acc])
def decode_unsigned(bytes) do
{result, _} =
for <<(<<_sign::1, byte::7>> <- bytes)>>, reduce: {0, 0} do
{result, m} ->
result = Bitwise.bor(result, Bitwise.bsl(byte, 7 * m))
{result, m + 1}
end
result
defp decode_signed(<<1::1, byte::7, rest::bytes>>, acc) do
decode_signed(rest, <<byte::7, acc::bitstring>>)