From 4708e3271f96fc0d0e5e545aae3bba43ddd0cdca Mon Sep 17 00:00:00 2001 From: ILYA Khlopotov Date: Mon, 27 Jul 2015 10:13:45 -0700 Subject: [PATCH] Avoid arithmetic in `to_hex` function --- src/couch_util.erl | 31 +++++++++++++++++++++++-------- test/couch_util_tests.erl | 8 ++++++++ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/src/couch_util.erl b/src/couch_util.erl index 742ab70c..20152442 100644 --- a/src/couch_util.erl +++ b/src/couch_util.erl @@ -133,15 +133,30 @@ validate_utf8_fast(B, O) -> false end. -to_hex([]) -> - []; -to_hex(Bin) when is_binary(Bin) -> - to_hex(binary_to_list(Bin)); -to_hex([H|T]) -> - [to_digit(H div 16), to_digit(H rem 16) | to_hex(T)]. -to_digit(N) when N < 10 -> $0 + N; -to_digit(N) -> $a + N-10. +to_hex(<>) -> + [nibble_to_hex(Hi), nibble_to_hex(Lo) | to_hex(Rest)]; +to_hex(<<>>) -> + []; +to_hex(List) when is_list(List) -> + to_hex(list_to_binary(List)). + +nibble_to_hex(0) -> $0; +nibble_to_hex(1) -> $1; +nibble_to_hex(2) -> $2; +nibble_to_hex(3) -> $3; +nibble_to_hex(4) -> $4; +nibble_to_hex(5) -> $5; +nibble_to_hex(6) -> $6; +nibble_to_hex(7) -> $7; +nibble_to_hex(8) -> $8; +nibble_to_hex(9) -> $9; +nibble_to_hex(10) -> $a; +nibble_to_hex(11) -> $b; +nibble_to_hex(12) -> $c; +nibble_to_hex(13) -> $d; +nibble_to_hex(14) -> $e; +nibble_to_hex(15) -> $f. parse_term(Bin) when is_binary(Bin) -> diff --git a/test/couch_util_tests.erl b/test/couch_util_tests.erl index b3c07026..a0e92387 100644 --- a/test/couch_util_tests.erl +++ b/test/couch_util_tests.erl @@ -160,3 +160,11 @@ should_fail_for_missing_cb() -> {error, {undefined_callback, Name, MFA}}, couch_util:validate_callback_exists(M, F, A))} end, Cases). + +to_hex_test_() -> + [ + ?_assertEqual("", couch_util:to_hex([])), + ?_assertEqual("010203faff", couch_util:to_hex([1, 2, 3, 250, 255])), + ?_assertEqual("", couch_util:to_hex(<<>>)), + ?_assertEqual("010203faff", couch_util:to_hex(<<1, 2, 3, 250, 255>>)) + ].