|
5 | 5 |
|
6 | 6 | #include <jansson.h> |
7 | 7 |
|
| 8 | +/* TODO: replace with json_add_len_and_hex() */ |
8 | 9 | static void |
9 | 10 | add_hex_ascii(json_t *dst, const uint8_t *buf, int n) { |
10 | 11 | json_object_set_new(dst, "len", json_integer(n)); |
@@ -45,3 +46,45 @@ json_print_or_pretty(json_t *o, int pretty) { |
45 | 46 |
|
46 | 47 | json_decref(o); |
47 | 48 | } |
| 49 | + |
| 50 | +int |
| 51 | +json_add_hex_ascii(json_t *dst, const char *key, const void *bufv, size_t n) { |
| 52 | + if (!dst || !key || (!bufv && n)) |
| 53 | + return -1; |
| 54 | + if (n > (SIZE_MAX / 2)) |
| 55 | + return -1; |
| 56 | + |
| 57 | + const uint8_t *buf = (const uint8_t *) bufv; |
| 58 | + size_t outlen = n * 2; |
| 59 | + |
| 60 | + char *hex = (char *) malloc(outlen + 1); |
| 61 | + if (!hex) |
| 62 | + return -1; |
| 63 | + |
| 64 | + static const char *HD = "0123456789ABCDEF"; |
| 65 | + /* avoid using sprintf() */ |
| 66 | + for (size_t i = 0; i < n; ++i) { |
| 67 | + hex[(i << 1)] = HD[(buf[i] >> 4) & 0xF]; |
| 68 | + hex[(i << 1) + 1] = HD[buf[i] & 0xF]; |
| 69 | + } |
| 70 | + hex[outlen] = '\0'; |
| 71 | + |
| 72 | + json_t *s = json_stringn(hex, outlen); |
| 73 | + free(hex); |
| 74 | + |
| 75 | + if (!s) |
| 76 | + return -1; |
| 77 | + |
| 78 | + return json_object_set_new(dst, key, s); |
| 79 | +} |
| 80 | + |
| 81 | +int |
| 82 | +json_add_len_and_hex(json_t *dst, const char *key, const void *buf, size_t n) { |
| 83 | + if (!dst) |
| 84 | + return -1; |
| 85 | + |
| 86 | + if (json_object_set_new(dst, "len", json_integer((json_int_t) n)) != 0) |
| 87 | + return -1; |
| 88 | + |
| 89 | + return json_add_hex_ascii(dst, key, buf, n); |
| 90 | +} |
0 commit comments