diff --git a/src/ids/base32.gleam b/src/ids/base32.gleam index 12fa183..b053d0e 100644 --- a/src/ids/base32.gleam +++ b/src/ids/base32.gleam @@ -8,17 +8,21 @@ import gleam/string /// Used by ULID and TypeID @internal pub fn encode(bytes: BitArray, alphabet: String) -> String { + let alphabet_with_index = + alphabet + |> string.to_graphemes + |> list.index_map(fn(x, i) { #(i, x) }) + // pad 2 bits because we only supply 128 bits of data but need 130 bits for encoding - encode_bytes(<<0:size(2), bytes:bits>>, alphabet) + encode_bytes(<<0:size(2), bytes:bits>>, alphabet_with_index) } /// Recursively grabs 5 bits and uses them as index in the alphabet and concatinates them to a string. -fn encode_bytes(binary: BitArray, alphabet: String) -> String { +fn encode_bytes(binary: BitArray, alphabet: List(#(Int, String))) -> String { case binary { <> -> { alphabet - |> string.to_graphemes - |> list.at(index) + |> list.key_find(index) |> result.unwrap("0") |> string.append(encode_bytes(rest, alphabet)) }