Skip to content

Commit

Permalink
create decode_to_int/1 to decode integer values #14
Browse files Browse the repository at this point in the history
  • Loading branch information
nelsonic committed Apr 26, 2020
1 parent 6ea4d4c commit c184aea
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 7 deletions.
31 changes: 28 additions & 3 deletions lib/base58.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ defmodule Base58 do
"Cn8eVZg"
iex> Base58.encode(42)
"m8Uq"
"4yP"
"""
def encode(""), do: ""
def encode(binary) when is_binary(binary) do
Expand All @@ -30,8 +30,21 @@ defmodule Base58 do
end

# If the parameter is not a binary convert it to binary before encode.
def encode(anything) do
:erlang.term_to_binary(anything)
def encode(int) when is_integer(int) do
int
|> Integer.to_string()
|> encode()
end

def encode(val) when is_float(val) do
val
|> Float.to_string()
|> encode()
end

def encode(atom) when is_atom(atom) do
atom
|> Atom.to_string()
|> encode()
end

Expand Down Expand Up @@ -86,4 +99,16 @@ defmodule Base58 do
defp recurse([head | tail], acc) do
recurse(tail, (acc * 58) + Enum.find_index(@alnum, &(&1 == head)))
end

@doc """
`decode_to_int/1` decodes the given Base58 string back to an Integer.
## Examples
iex> Base58.encode(42) |> Base58.decode_to_int()
42
"""
def decode_to_int(encoded) do
decode(encoded)
|> String.to_integer()
end
end
28 changes: 24 additions & 4 deletions test/base58_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,14 @@ defmodule Base58Test do

test "converts any value to binary and then Base58 encodes it" do
# Integer
assert "m8UW" == encode(23)
assert "8NmHr9odQSJL4n" == encode(3.14)
assert "4pa" == encode(23)
assert "4pa" == encode("23")
# Float
assert "2JstGb" == encode(3.14)
assert "2JstGb" == encode("3.14")
# Atom
assert "2g14LRptojh8i" == encode(:hello)
assert "Cn8eVZg" == encode(:hello)
assert "Cn8eVZg" == encode("hello")
end

test "returns z when binary is represented by 57" do
Expand All @@ -34,7 +38,7 @@ defmodule Base58Test do
assert "Z" == encode(" ")
end

test "encode <<0>> retuens 1" do
test "encode <<0>> returns 1" do
assert "1" == encode(<<0>>)
end

Expand All @@ -47,6 +51,22 @@ defmodule Base58Test do
assert decode(encode("123")) == "123"
end

test "decode :atom" do
assert encode(:hello) |> decode() == "hello"
end

test "decode_to_int(encode(int) == int)" do
int = 42
decoded = Base58.encode(int) |> Base58.decode_to_int()
assert decoded == int
end

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

property "Compare result with Base58 package" do
check all(bin <- binary()) do
case bin == "" do
Expand Down

0 comments on commit c184aea

Please sign in to comment.