summaryrefslogtreecommitdiff
path: root/utils.hpp
blob: 930ae023a9814e0ff7b5a9f29cc2a122bae41154 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* SPDX-License-Identifier: Unlicense
 */

#pragma once

#if defined(NDEBUG)
#ifdef __clang__
#   define UNREACHABLE (__builtin_unreachable())
#elif __GNUC__
#   define UNREACHABLE (__builtin_unreachable())
#else
#   define UNREACHABLE
#endif
#else
#include <cassert>
#include <cstdlib>
#define UNREACHABLE (assert((void*)0 == "Unreachable code reached"), abort(), 1)
#endif

#include <stdint.h>

namespace Utils {

static inline uint8_t ParseByteFromHexChars(uint8_t first, uint8_t second)
{
    // Assume, that given bytes are valid hex digits in ASCII
    first = ((first & 0x40) ? (first + 9) : first) & 0x0f;
    second = ((second & 0x40) ? (second + 9) : second) & 0x0f;
    return ((first << 4) | second) & 0xff;
}

static inline void ConvertByteToHex(uint8_t byte, char* out)
{
    const uint8_t c1 = (byte >> 4) & 0x0f;
    const uint8_t c2 = byte& 0x0f;
    out[0] = static_cast<char>(c1 < 0xa ? c1 + '0' : c1 + ('a' - 0xa));
    out[1] = static_cast<char>(c2 < 0xa ? c2 + '0' : c2 + ('a' - 0xa));
}

}