Current section
Files
Jump to
Current section
Files
lib/aphora/helper.ex
# Copyright 2019 Schicksal
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule Aphora.Helper do
@moduledoc """
This module provides methods, which help to utilize `t:Aphora.Worker.aphora_id/0` correctly, by enabling the en- and decoding as well as the fetching of specific information.
"""
@encoding_alphabet %{
0 => "-",
1 => "0",
2 => "1",
3 => "2",
4 => "3",
5 => "4",
6 => "5",
7 => "6",
8 => "7",
9 => "8",
10 => "9",
11 => "A",
12 => "B",
13 => "C",
14 => "D",
15 => "E",
16 => "F",
17 => "G",
18 => "H",
19 => "I",
20 => "J",
21 => "K",
22 => "L",
23 => "M",
24 => "N",
25 => "O",
26 => "P",
27 => "Q",
28 => "R",
29 => "S",
30 => "T",
31 => "U",
32 => "V",
33 => "W",
34 => "X",
35 => "Y",
36 => "Z",
37 => "_",
38 => "a",
39 => "b",
40 => "c",
41 => "d",
42 => "e",
43 => "f",
44 => "g",
45 => "h",
46 => "i",
47 => "j",
48 => "k",
49 => "l",
50 => "m",
51 => "n",
52 => "o",
53 => "p",
54 => "q",
55 => "r",
56 => "s",
57 => "t",
58 => "u",
59 => "v",
60 => "w",
61 => "x",
62 => "y",
63 => "z"
}
@doc since: "0.2.0"
@spec encode(<<_::72>>) :: Aphora.Worker.aphora_id()
def encode(binary) do
grouped = for <<character::6 <- binary>>, do: character
encoded = for character <- grouped, do: Map.fetch!(@encoding_alphabet, character)
Enum.join(encoded)
end
@decoding_alphabet %{
"-" => 0,
"0" => 1,
"1" => 2,
"2" => 3,
"3" => 4,
"4" => 5,
"5" => 6,
"6" => 7,
"7" => 8,
"8" => 9,
"9" => 10,
"A" => 11,
"B" => 12,
"C" => 13,
"D" => 14,
"E" => 15,
"F" => 16,
"G" => 17,
"H" => 18,
"I" => 19,
"J" => 20,
"K" => 21,
"L" => 22,
"M" => 23,
"N" => 24,
"O" => 25,
"P" => 26,
"Q" => 27,
"R" => 28,
"S" => 29,
"T" => 30,
"U" => 31,
"V" => 32,
"W" => 33,
"X" => 34,
"Y" => 35,
"Z" => 36,
"_" => 37,
"a" => 38,
"b" => 39,
"c" => 40,
"d" => 41,
"e" => 42,
"f" => 43,
"g" => 44,
"h" => 45,
"i" => 46,
"j" => 47,
"k" => 48,
"l" => 49,
"m" => 50,
"n" => 51,
"o" => 52,
"p" => 53,
"q" => 54,
"r" => 55,
"s" => 56,
"t" => 57,
"u" => 58,
"v" => 59,
"w" => 60,
"x" => 61,
"y" => 62,
"z" => 63
}
@doc since: "0.2.0"
@spec decode(Aphora.Worker.aphora_id()) :: <<_::72>>
def decode(aphora_id) do
encoded = String.graphemes(aphora_id)
grouped = for character <- encoded, do: Map.fetch!(@decoding_alphabet, character)
Enum.into(grouped, <<>>, fn byte -> <<byte::6>> end)
end
end