Debian Codegraph @

src/bluetooth_data_tools/utils_wrapper.h

raw symbols SCIP
1 #include <stddef.h>
2 #include <stdint.h>
3
4 /**
5 * Sentinel returned by _bdaddr_to_uint64 to signal a parse failure.
6 */
7 #define BDADDR_PARSE_ERROR UINT64_MAX
8
9 /**
10 * Decode one hex character to its 4-bit value, or 0xFF on invalid input.
11 */
12 static inline uint8_t _hex_nibble(char c) {
13 if (c >= '0' && c <= '9') return (uint8_t)(c - '0');
14 if (c >= 'A' && c <= 'F') return (uint8_t)(c - 'A' + 10);
15 if (c >= 'a' && c <= 'f') return (uint8_t)(c - 'a' + 10);
16 return 0xFF;
17 }
18
19 /**
20 * Parse a bluetooth address string into a uint64_t.
21 *
22 * Accepts either the 17-byte separated form ("AA:BB:CC:DD:EE:FF" — also
23 * the "AA-BB-CC-DD-EE-FF" Windows form) or the 12-byte unseparated form
24 * ("AABBCCDDEEFF"). Returns BDADDR_PARSE_ERROR on any parse error.
25 */
26 static inline uint64_t _bdaddr_to_uint64(const char *bdaddr, size_t length) {
27 size_t step;
28 if (length == 17) {
29 step = 3;
30 } else if (length == 12) {
31 step = 2;
32 } else {
33 return BDADDR_PARSE_ERROR;
34 }
35 uint64_t result = 0;
36 for (size_t i = 0; i < 6; ++i) {
37 size_t pos = i * step;
38 uint8_t hi = _hex_nibble(bdaddr[pos]);
39 uint8_t lo = _hex_nibble(bdaddr[pos + 1]);
40 if (hi == 0xFF || lo == 0xFF) {
41 return BDADDR_PARSE_ERROR;
42 }
43 result = (result << 8) | (uint64_t)((hi << 4) | lo);
44 if (step == 3 && i < 5) {
45 char sep = bdaddr[pos + 2];
46 if (sep != ':' && sep != '-') {
47 return BDADDR_PARSE_ERROR;
48 }
49 }
50 }
51 return result;
52 }
53
54 /**
55 * Convert the given integer bluetooth address to its hexadecimal string representation.
56 * The buffer passed in must accept at least 17 bytes. It will NOT be null-terminated.
57 */
58 void _uint64_to_bdaddr(uint64_t address, char bdaddr[17]) {
59 static const char hex_table[] = "0123456789ABCDEF";
60 bdaddr[0] = hex_table[(address >> 44) & 0x0F];
61 bdaddr[1] = hex_table[(address >> 40) & 0x0F];
62 bdaddr[2] = ':';
63 bdaddr[3] = hex_table[(address >> 36) & 0x0F];
64 bdaddr[4] = hex_table[(address >> 32) & 0x0F];
65 bdaddr[5] = ':';
66 bdaddr[6] = hex_table[(address >> 28) & 0x0F];
67 bdaddr[7] = hex_table[(address >> 24) & 0x0F];
68 bdaddr[8] = ':';
69 bdaddr[9] = hex_table[(address >> 20) & 0x0F];
70 bdaddr[10] = hex_table[(address >> 16) & 0x0F];
71 bdaddr[11] = ':';
72 bdaddr[12] = hex_table[(address >> 12) & 0x0F];
73 bdaddr[13] = hex_table[(address >> 8) & 0x0F];
74 bdaddr[14] = ':';
75 bdaddr[15] = hex_table[(address >> 4) & 0x0F];
76 bdaddr[16] = hex_table[address & 0x0F];
77 }