| 1 |
// Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 |
// SPDX-License-Identifier: LGPL-2.1-or-later |
| 3 |
|
| 4 |
/** |
| 5 |
* @file |
| 6 |
* |
| 7 |
* Hexadecimal encoding/decoding. |
| 8 |
* |
| 9 |
* See @ref Hexlify. |
| 10 |
*/ |
| 11 |
|
| 12 |
#ifndef DRGN_HEXLIFY_H |
| 13 |
#define DRGN_HEXLIFY_H |
| 14 |
|
| 15 |
#include <stdbool.h> |
| 16 |
#include <stddef.h> |
| 17 |
#include <stdint.h> |
| 18 |
|
| 19 |
/** |
| 20 |
* @ingroup Internals |
| 21 |
* |
| 22 |
* @defgroup Hexlify Hexlify |
| 23 |
* |
| 24 |
* Hexadecimal encoding/decoding. |
| 25 |
* |
| 26 |
* @{ |
| 27 |
*/ |
| 28 |
|
| 29 |
/** |
| 30 |
* Encode binary data to a hexadecimal string. |
| 31 |
* |
| 32 |
* The output string is an even number of lowercase hexadecimal characters with |
| 33 |
* no separators. It is not null-terminated. |
| 34 |
* |
| 35 |
* @param[in] in Input binary data. |
| 36 |
* @param[in] in_len Size of @p in in bytes. |
| 37 |
* @param[out] out Output hexadecimal string of size `2 * in_len` characters. |
| 38 |
* Not null-terminated. |
| 39 |
*/ |
| 40 |
void hexlify(const void *in, size_t in_len, char *out); |
| 41 |
|
| 42 |
/** |
| 43 |
* Allocate and encode binary data to a hexadecimal string. |
| 44 |
* |
| 45 |
* This is like @ref hexlify(), but it allocates the output string, including a |
| 46 |
* terminating null byte. |
| 47 |
* |
| 48 |
* @param[in] in Input binary data. |
| 49 |
* @param[in] in_len Size of @p in in bytes. |
| 50 |
* @return Output hexadecimal string, or `NULL` on failure to allocate memory. |
| 51 |
* Unlike @ref hexlify(), this *is* null-terminated. On success, it must be |
| 52 |
* freed with `free()`. |
| 53 |
*/ |
| 54 |
char *ahexlify(const void *in, size_t in_len); |
| 55 |
|
| 56 |
/** |
| 57 |
* Decode hexadecimal string to binary data. |
| 58 |
* |
| 59 |
* The input string must be an even number of hexadecimal characters (either |
| 60 |
* lowercase or uppercase) with no separators. |
| 61 |
* |
| 62 |
* @param[in] in Input hexadecimal string. Does not need to be null-terminated. |
| 63 |
* @param[in] in_len Number of characters in @p in. |
| 64 |
* @param[out] out Returned binary data of size `in_len / 2` bytes. |
| 65 |
* @return `true` if data was successfully decoded, `false` if not (either |
| 66 |
* because @p in_len was odd or @p in contained non-hexadecimal characters). |
| 67 |
*/ |
| 68 |
bool unhexlify(const char *in, size_t in_len, void *out); |
| 69 |
|
| 70 |
static inline bool hex_digit_to_nibble(char c, uint8_t *ret) |
| 71 |
{ |
| 72 |
if ('0' <= c && c <= '9') |
| 73 |
*ret = c - '0'; |
| 74 |
else if ('a' <= c && c <= 'f') |
| 75 |
*ret = c - 'a' + 10; |
| 76 |
else if ('A' <= c && c <= 'F') |
| 77 |
*ret = c - 'A' + 10; |
| 78 |
else |
| 79 |
return false; |
| 80 |
return true; |
| 81 |
} |
| 82 |
|
| 83 |
/** @} */ |
| 84 |
|
| 85 |
#endif /* DRGN_HEXLIFY_H */ |