Add encode and decode options and test suites

This commit is contained in:
Gilbert Wong 2018-08-07 10:27:04 +08:00
parent 79481db659
commit 96d251ec3c
3 changed files with 25 additions and 10 deletions

View File

@ -14,8 +14,10 @@
-module(emqx_base62).
-export([encode/1, decode/1]).
-export([encode/1,
encode/2,
decode/1,
decode/2]).
%% @doc Encode any data to base62 binary
-spec encode(string()
@ -28,18 +30,23 @@ encode(S) when is_list(S)->
encode(B) when is_binary(B) ->
encode(B, <<>>).
%% encode(D, string) ->
%% binary_to_list(encode(D)).
%% @doc Decode base62 binary to origin data binary
decode(L) when is_list(L) ->
decode(list_to_binary(L));
decode(B) when is_binary(B) ->
decode(B, <<>>).
%% encode_base62(<<H:24, Rest/binary>>, Acc) ->
%% encode_byte_group(H, Acc);
%% encode_base62(<<H:16, Rest/binary>>, Acc) ->
%% encode_byte_group(H, Acc);
%%====================================================================
%% Internal functions
%%====================================================================
encode(D, string) ->
binary_to_list(encode(D));
encode(<<Index1:6, Index2:6, Index3:6, Index4:6, Rest/binary>>, Acc) ->
CharList = [encode_char(Index1), encode_char(Index2), encode_char(Index3), encode_char(Index4)],
NewAcc = <<Acc/binary,(iolist_to_binary(CharList))/binary>>,
@ -55,6 +62,10 @@ encode(<<Index1:6, Index2:2>>, Acc) ->
encode(<<>>, Acc) ->
Acc.
decode(D, integer) ->
binary_to_integer(decode(D));
decode(D, string) ->
binary_to_list(decode(D));
decode(<<Head:8, Rest/binary>>, Acc)
when bit_size(Rest) >= 8->
case Head == $9 of
@ -99,3 +110,4 @@ decode_char(I) when I >= $A andalso I =< $Z->
decode_char(9, I) ->
I + 61 - $A.

View File

@ -126,9 +126,9 @@ from_hexstr(S) ->
I = list_to_integer(binary_to_list(S), 16), <<I:128>>.
to_base62(<<I:128>>) ->
binary_to_list(emqx_base62:encode(I)).
emqx_base62:encode(I).
from_base62(S) ->
I = binary_to_integer(emqx_base62:decode(S)),
I = emqx_base62:decode(S, integer),
<<I:128>>.

View File

@ -32,5 +32,8 @@ t_base62_encode(_) ->
<<"65535">> = ?BASE62:decode(?BASE62:encode(<<"65535">>)),
<<X:128/unsigned-big-integer>> = emqx_guid:gen(),
<<Y:128/unsigned-big-integer>> = emqx_guid:gen(),
X = erlang:binary_to_integer(?BASE62:decode(?BASE62:encode(X))),
Y = erlang:binary_to_integer(?BASE62:decode(?BASE62:encode(Y))).
X = ?BASE62:decode(?BASE62:encode(X), integer),
Y = ?BASE62:decode(?BASE62:encode(Y), integer),
<<"helloworld">> = ?BASE62:decode(?BASE62:encode("helloworld")),
"helloworld" = ?BASE62:decode(?BASE62:encode("helloworld", string), string).