Skip to content

Commit

Permalink
fix: do not forget leading zeroes when decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
geonnave committed Mar 3, 2022
1 parent 3c1b0d4 commit eb86102
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ erl_crash.dump
*.ez
*.beam
/config/*.secret.exs
*.swp
9 changes: 8 additions & 1 deletion lib/base58.ex
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,14 @@ defmodule Base58 do

def decode(""), do: "" # return empty string unmodified
def decode("\0"), do: "" # treat null values as empty
def decode(binary), do: decode(binary, 0)
def decode(binary) do
# avoid dropping leading zeros -- see https://github.com/dwyl/base58/issues/27
origlen = String.length(binary)
binary = String.trim_leading(binary, "1")
newlen = String.length(binary)
String.duplicate(<<0>>, origlen - newlen) <> decode(binary, 0)
end
def decode("", 0), do: ""
def decode("", acc), do: :binary.encode_unsigned(acc)
def decode(<<head, tail::binary>>, acc),
do: decode(tail, acc * 58 + Enum.find_index(@alnum, &(&1 == head)))
Expand Down
8 changes: 8 additions & 0 deletions test/base58_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ defmodule Base58Test do
assert decoded == int
end

test "decode 11111 returns <<0, 0, 0, 0, 0>>" do
assert <<0, 0, 0, 0, 0>> == decode("11111")
end

test "decode 11112 returns <<0, 0, 0, 0, 1>>" do
assert <<0, 0, 0, 0, 1>> == decode("11112")
end

property "Check a batch of int values can be decoded" do
check all(int <- integer()) do
assert decode_to_int(encode(int)) == int
Expand Down

0 comments on commit eb86102

Please sign in to comment.