From c184aea7877e4904c4f86d345556602ee7e2941d Mon Sep 17 00:00:00 2001 From: nelsonic Date: Sun, 26 Apr 2020 11:40:34 +0100 Subject: [PATCH] create decode_to_int/1 to decode integer values #14 --- lib/base58.ex | 31 ++++++++++++++++++++++++++++--- test/base58_test.exs | 28 ++++++++++++++++++++++++---- 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/lib/base58.ex b/lib/base58.ex index 966a361..d5b5514 100644 --- a/lib/base58.ex +++ b/lib/base58.ex @@ -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 @@ -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 @@ -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 diff --git a/test/base58_test.exs b/test/base58_test.exs index 9ed4cbe..01db845 100644 --- a/test/base58_test.exs +++ b/test/base58_test.exs @@ -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 @@ -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 @@ -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