diff options
author | Gilbert <gilbertwong96@icloud.com> | 2022-09-14 11:55:30 +0800 |
---|---|---|
committer | Gilbert <gilbertwong96@icloud.com> | 2022-12-13 17:09:59 +0800 |
commit | a30a54d4ec5e18501868995bb965242d5d2f5072 (patch) | |
tree | bcb0d169a86fedfcfaddfa381546548ad856e6ef /lib/stdlib/test/property_test | |
parent | 9a89bb04676171d70c62a8d1a61cbe967597555f (diff) | |
download | erlang-a30a54d4ec5e18501868995bb965242d5d2f5072.tar.gz |
stdlib: add `binary:encode_hex/2`
The `binary` module only exposes `encode_hex/1` which encodes binary to a
hex-encoded binary. The output as the number in hexadecimal, with a
through f is in the upper case by default. This change allows the user to
decide to use upper case or lower case.
Diffstat (limited to 'lib/stdlib/test/property_test')
-rw-r--r-- | lib/stdlib/test/property_test/binary_prop.erl | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/lib/stdlib/test/property_test/binary_prop.erl b/lib/stdlib/test/property_test/binary_prop.erl new file mode 100644 index 0000000000..00efa77b8c --- /dev/null +++ b/lib/stdlib/test/property_test/binary_prop.erl @@ -0,0 +1,37 @@ +-module(binary_prop). + +-export([prop_hex_encode_2/0]). + +-compile([export_all, nowarn_export_all]). + +-include_lib("common_test/include/ct_property_test.hrl"). + +prop_hex_encode_2() -> + ?FORALL(Data, data(), + begin + UpperHex = binary:encode_hex(Data, uppercase), + LowerHex = binary:encode_hex(Data, lowercase), + binary:decode_hex(LowerHex) =:= Data andalso + binary:decode_hex(UpperHex) =:= Data andalso + check_hex_encoded(Data, UpperHex, LowerHex) + end). + +data() -> + ?SIZED(Size, resize(Size * 2, binary())). + + +%% @doc Credit to the <a href="https://github.com/erlang/otp/pull/6297#discussion_r1034771450">comment</a> of @Maria-12648430 +-spec check_hex_encoded(Data :: binary(), UpperHex :: binary(), LoweHex :: binary()) -> boolean(). +check_hex_encoded(<<I1:4, I2:4, Ins/binary>>, <<U1:8, U2:8, UCs/binary>>, <<L1:8, L2:8, LCs/binary>>) -> + check_hex_chars_match(I1, U1, L1) andalso + check_hex_chars_match(I2, U2, L2) andalso + check_hex_encoded(Ins, UCs, LCs); +check_hex_encoded(<<>>, <<>>, <<>>) -> + true; +check_hex_encoded(_, _, _) -> + false. + +check_hex_chars_match(X, U, L) when X < 10 -> + (U =:= $0 + X) andalso (L =:= $0 + X); +check_hex_chars_match(X, U, L) -> + (U =:= $A + X -10) andalso (L =:= $a + X -10). |