mirror of
https://github.com/sloanelybutsurely/typeid-elixir.git
synced 2024-11-28 01:42:54 -05:00
fix base32 encoding
This commit is contained in:
parent
fd9431991d
commit
a9c52b8496
2 changed files with 38 additions and 6 deletions
|
@ -1,9 +1,22 @@
|
|||
defmodule TypeID.Base32 do
|
||||
import Bitwise
|
||||
|
||||
crockford_alphabet = ~c"0123456789abcdefghjkmnpqrstvwxyz"
|
||||
crockford_alphabet = ~c"0123456789ABCDEFGHJKMNPQRSTVWXYZ"
|
||||
|
||||
encoded = for e1 <- crockford_alphabet, e2 <- crockford_alphabet, do: bsl(e1, 8) + e2
|
||||
to_lower_enc = &Enum.map(&1, fn c -> if c in ?A..?Z, do: c - ?A + ?a, else: c end)
|
||||
to_lower_dec =
|
||||
&Enum.map(&1, fn {encoding, value} = pair ->
|
||||
if encoding in ?A..?Z do
|
||||
{encoding - ?A + ?a, value}
|
||||
else
|
||||
pair
|
||||
end
|
||||
end)
|
||||
|
||||
lower = to_lower_enc.(crockford_alphabet)
|
||||
|
||||
|
||||
encoded = for e1 <- lower, e2 <- lower, do: bsl(e1, 8) + e2
|
||||
|
||||
to_decode_list = fn alphabet ->
|
||||
alphabet = Enum.sort(alphabet)
|
||||
|
@ -14,8 +27,9 @@ defmodule TypeID.Base32 do
|
|||
end
|
||||
|
||||
{min, decoded} =
|
||||
crockford_alphabet
|
||||
lower
|
||||
|> Enum.with_index()
|
||||
|> to_lower_dec.()
|
||||
|> to_decode_list.()
|
||||
|
||||
@spec encode(binary()) :: binary()
|
||||
|
|
|
@ -5,14 +5,32 @@ defmodule TypeIDTest do
|
|||
test "returns a new TypeID struct" do
|
||||
tid = TypeID.new("test")
|
||||
assert is_struct(tid, TypeID)
|
||||
assert "test" == TypeID.type(tid)
|
||||
end
|
||||
end
|
||||
|
||||
describe "from_string!/1" do
|
||||
test "parses TypeIDs as defined by the spec" do
|
||||
describe "type/1" do
|
||||
test "returns the type (prefix) of the given TypeID" do
|
||||
tid = TypeID.from_string!("test_01h44had5rfswbvpc383ktj0aa")
|
||||
assert "test" == TypeID.type(tid)
|
||||
assert "01890915-34b8-7e78-bdd9-8340e7a9014a" == TypeID.uuid(tid)
|
||||
end
|
||||
end
|
||||
|
||||
describe "suffix/1" do
|
||||
test "returns the base 32 suffix of the given TypeID" do
|
||||
tid = TypeID.from_string!("test_01h44had5rfswbvpc383ktj0aa")
|
||||
assert "01h44had5rfswbvpc383ktj0aa" == TypeID.suffix(tid)
|
||||
end
|
||||
end
|
||||
|
||||
describe "serialization" do
|
||||
test "to_string/1 and from_string!/1 are idempotent" do
|
||||
tid1 = TypeID.from_string!("test_01h44had5rfswbvpc383ktj0aa")
|
||||
tid2 =
|
||||
tid1
|
||||
|> TypeID.to_string()
|
||||
|> TypeID.from_string!()
|
||||
assert tid1 == tid2
|
||||
end
|
||||
end
|
||||
|
||||
|
|
Loading…
Reference in a new issue