prop_emqx_base62.erl 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2020-2024 EMQ Technologies Co., Ltd. All Rights Reserved.
  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(prop_emqx_base62).
  17. -include_lib("proper/include/proper.hrl").
  18. %%--------------------------------------------------------------------
  19. %% Properties
  20. %%--------------------------------------------------------------------
  21. prop_symmetric() ->
  22. ?FORALL(
  23. Data,
  24. raw_data(),
  25. begin
  26. Encoded = emqx_base62:encode(Data),
  27. to_binary(Data) =:= emqx_base62:decode(Encoded)
  28. end
  29. ).
  30. prop_size() ->
  31. ?FORALL(
  32. Data,
  33. binary(),
  34. begin
  35. Encoded = emqx_base62:encode(Data),
  36. base62_size(Data, Encoded)
  37. end
  38. ).
  39. %%--------------------------------------------------------------------
  40. %% Helpers
  41. %%--------------------------------------------------------------------
  42. to_binary(Data) when is_list(Data) ->
  43. unicode:characters_to_binary(Data);
  44. to_binary(Data) when is_integer(Data) ->
  45. integer_to_binary(Data);
  46. to_binary(Data) when is_binary(Data) ->
  47. Data.
  48. base62_size(Data, Encoded) ->
  49. DataSize = erlang:size(Data),
  50. EncodedSize = erlang:size(Encoded),
  51. case (DataSize * 8 rem 6) of
  52. 0 ->
  53. %% Due to the particularity of base 62, 3 bytes data maybe encoded
  54. %% as 4 bytes data or 5 bytes data, the encode size maybe in the
  55. %% range between DataSize*4/3 and DataSize*8/3
  56. RangeStart = DataSize div 3 * 4,
  57. RangeEnd = DataSize div 3 * 8,
  58. EncodedSize >= RangeStart andalso EncodedSize =< RangeEnd;
  59. _Rem ->
  60. RangeStart = DataSize * 8 div 6 + 1,
  61. RangeEnd = DataSize * 8 div 6 * 2 + 1,
  62. EncodedSize >= RangeStart andalso EncodedSize =< RangeEnd
  63. end.
  64. %%--------------------------------------------------------------------
  65. %% Generators
  66. %%--------------------------------------------------------------------
  67. raw_data() ->
  68. oneof([integer(), string(), binary()]).