bare-buffer 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,66 @@
1
+ #include <stdbool.h>
2
+ #include <stddef.h>
3
+ #include <stdint.h>
4
+
5
+ #include "../include/hex.h"
6
+
7
+ static const char hex_alphabet[16] = "0123456789abcdef";
8
+
9
+ static const char hex_inverse_alphabet[256] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
10
+
11
+ int
12
+ hex_encode (const uint8_t *buffer, size_t buffer_len, char *string, size_t *string_len) {
13
+ size_t len = buffer_len * 2;
14
+
15
+ if (string == NULL) {
16
+ *string_len = len;
17
+ return 0;
18
+ }
19
+
20
+ if (*string_len < len) return -1;
21
+
22
+ bool terminate = *string_len > len;
23
+
24
+ *string_len = len;
25
+
26
+ size_t k = 0;
27
+
28
+ for (size_t i = 0, n = buffer_len; i < n; i++) {
29
+ string[k++] = hex_alphabet[buffer[i] >> 4];
30
+ string[k++] = hex_alphabet[buffer[i] & 0x0f];
31
+ }
32
+
33
+ if (terminate) string[k] = '\0';
34
+
35
+ return 0;
36
+ }
37
+
38
+ int
39
+ hex_decode (const char *string, size_t string_len, uint8_t *buffer, size_t *buffer_len) {
40
+ size_t len = string_len >> 1;
41
+
42
+ if (buffer == NULL) {
43
+ *buffer_len = len;
44
+ return 0;
45
+ }
46
+
47
+ if (*buffer_len < len) return -1;
48
+
49
+ *buffer_len = len;
50
+
51
+ size_t k = 0;
52
+
53
+ for (size_t i = 0, n = string_len; i < n; i += 2) {
54
+ char chunk[2];
55
+
56
+ for (size_t j = 0; j < 2; j++) {
57
+ chunk[j] = i + j < n ? hex_inverse_alphabet[string[i + j]] : 0;
58
+
59
+ if (chunk[j] == -1) return -1;
60
+ }
61
+
62
+ buffer[k++] = (chunk[0] << 4) | chunk[1];
63
+ }
64
+
65
+ return 0;
66
+ }