Skip to content

Commit 8011baf

Browse files
ChALkeRanonrig
andauthored
fix: use arithmetic HexEncode instead of lookups (#12)
* src: use arithmetic HexEncode instead of lookups * fixup!: lint * fixup!: constexpr Co-authored-by: Yagiz Nizipli <yagiz@nizipli.com> * fixup!: more clear code * fixup!: lint --------- Co-authored-by: Yagiz Nizipli <yagiz@nizipli.com>
1 parent 512d762 commit 8011baf

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

src/nbytes.cpp

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,17 +157,21 @@ const int8_t unhex_table[256] = {
157157
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
158158
-1, -1, -1, -1, -1, -1, -1, -1, -1};
159159

160+
inline constexpr char nibble(uint8_t x) {
161+
uint8_t add = (x >= 10) ? ('a' - 10) : '0';
162+
return x + add;
163+
}
164+
160165
size_t HexEncode(const char *src, size_t slen, char *dst, size_t dlen) {
161166
// We know how much we'll write, just make sure that there's space.
162167
NBYTES_ASSERT_TRUE(dlen >= MultiplyWithOverflowCheck<size_t>(slen, 2u) &&
163168
"not enough space provided for hex encode");
164169

165170
dlen = slen * 2;
166171
for (size_t i = 0, k = 0; k < dlen; i += 1, k += 2) {
167-
static const char hex[] = "0123456789abcdef";
168172
uint8_t val = static_cast<uint8_t>(src[i]);
169-
dst[k + 0] = hex[val >> 4];
170-
dst[k + 1] = hex[val & 15];
173+
dst[k + 0] = nibble(val >> 4);
174+
dst[k + 1] = nibble(val & 15);
171175
}
172176

173177
return dlen;

0 commit comments

Comments
 (0)