commit 85a50fb4304dc4dd3a97c903c3a1b01956530438
parent d2ede0a6318f5ae822e25febc18244499be4a4d2
Author: William Casarin <jb55@jb55.com>
Date: Thu, 10 Aug 2023 15:38:32 -0700
perf: optimize hex_decode
This is a lot faster!
Diffstat:
M | hex.h | | | 23 | ++++++++++++----------- |
1 file changed, 12 insertions(+), 11 deletions(-)
diff --git a/hex.h b/hex.h
@@ -4,18 +4,19 @@
#include <stdlib.h>
-static inline int char_to_hex(unsigned char *val, char c)
+static const char hex_table[256] = {
+ ['0'] = 0, ['1'] = 1, ['2'] = 2, ['3'] = 3,
+ ['4'] = 4, ['5'] = 5, ['6'] = 6, ['7'] = 7,
+ ['8'] = 8, ['9'] = 9, ['a'] = 10, ['b'] = 11,
+ ['c'] = 12, ['d'] = 13, ['e'] = 14, ['f'] = 15,
+ ['A'] = 10, ['B'] = 11, ['C'] = 12, ['D'] = 13,
+ ['E'] = 14, ['F'] = 15
+};
+
+static inline int char_to_hex(unsigned char *val, int c)
{
- if (c >= '0' && c <= '9') {
- *val = c - '0';
- return 1;
- }
- if (c >= 'a' && c <= 'f') {
- *val = c - 'a' + 10;
- return 1;
- }
- if (c >= 'A' && c <= 'F') {
- *val = c - 'A' + 10;
+ if (hex_table[(int)c] || c == '0') {
+ *val = hex_table[c];
return 1;
}
return 0;