emqttd_base62.erl 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2016 Feng Lee <feng@emqtt.io>.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqttd_base62).
  17. -export([encode/1, decode/1]).
  18. %% @doc Encode an integer to base62 string
  19. -spec(encode(non_neg_integer()) -> binary()).
  20. encode(I) when is_integer(I) andalso I > 0 ->
  21. list_to_binary(encode(I, [])).
  22. encode(I, Acc) when I < 62 ->
  23. [char(I) | Acc];
  24. encode(I, Acc) ->
  25. encode(I div 62, [char(I rem 62) | Acc]).
  26. char(I) when I < 10 ->
  27. $0 + I;
  28. char(I) when I < 36 ->
  29. $A + I - 10;
  30. char(I) when I < 62 ->
  31. $a + I - 36.
  32. %% @doc Decode base62 string to an integer
  33. -spec(decode(string() | binary()) -> integer()).
  34. decode(B) when is_binary(B) ->
  35. decode(binary_to_list(B));
  36. decode(S) when is_list(S) ->
  37. decode(S, 0).
  38. decode([], I) ->
  39. I;
  40. decode([C|S], I) ->
  41. decode(S, I * 62 + byte(C)).
  42. byte(C) when $0 =< C andalso C =< $9 ->
  43. C - $0;
  44. byte(C) when $A =< C andalso C =< $Z ->
  45. C - $A + 10;
  46. byte(C) when $a =< C andalso C =< $z ->
  47. C - $a + 36.