diff --git a/ccan/ccan/str/hex/hex.c b/ccan/ccan/str/hex/hex.c index 6e031779f..e2acb27b7 100644 --- a/ccan/ccan/str/hex/hex.c +++ b/ccan/ccan/str/hex/hex.c @@ -64,3 +64,21 @@ bool hex_encode(const void *buf, size_t bufsize, char *dest, size_t destsize) return true; } + +bool hex_encode_reversed(const void *buf, size_t bufsize, char *dest, size_t destsize) +{ + size_t i; + + if (destsize < hex_str_size(bufsize)) + return false; + + // Start at end of data, go to index 0. + for (i = bufsize; i--;) { + unsigned int c = ((const unsigned char *)buf)[i]; + *(dest++) = hexchar(c >> 4); + *(dest++) = hexchar(c & 0xF); + } + *dest = '\0'; + + return true; +} diff --git a/ccan/ccan/str/hex/hex.h b/ccan/ccan/str/hex/hex.h index 624a77b10..8fb6ab523 100644 --- a/ccan/ccan/str/hex/hex.h +++ b/ccan/ccan/str/hex/hex.h @@ -41,6 +41,24 @@ bool hex_decode(const char *str, size_t slen, void *buf, size_t bufsize); */ bool hex_encode(const void *buf, size_t bufsize, char *dest, size_t destsize); +/** + * hex_encode_reversed - Create a nul-terminated reversed hex string + * @buf: the buffer to read the data from + * @bufsize: the length of @buf + * @dest: the string to fill + * @destsize: the max size of the string + * + * Returns true if the string, including terminator, fit in @destsize; + * + * Example: + * unsigned char buf[] = { 0x1F, 0x2F }; + * char str[5]; + * + * if (!hex_encode(buf, sizeof(buf), str, sizeof(str))) + * abort(); + */ +bool hex_encode_reversed(const void *buf, size_t bufsize, char *dest, size_t destsize); + /** * hex_str_size - Calculate how big a nul-terminated hex string is * @bytes: bytes of data to represent diff --git a/common/json.c b/common/json.c index 899f65fdc..f81f2a027 100644 --- a/common/json.c +++ b/common/json.c @@ -471,6 +471,15 @@ void json_add_hex(struct json_result *result, const char *fieldname, json_add_string(result, fieldname, hex); } +void json_add_hex_reversed(struct json_result *result, const char *fieldname, + const void *data, size_t len) +{ + char hex[hex_str_size(len)]; + + hex_encode_reversed(data, len, hex, sizeof(hex)); + json_add_string(result, fieldname, hex); +} + void json_add_object(struct json_result *result, ...) { va_list ap; diff --git a/common/json.h b/common/json.h index b0501b6d0..7deaa6693 100644 --- a/common/json.h +++ b/common/json.h @@ -102,6 +102,9 @@ void json_add_null(struct json_result *result, const char *fieldname); /* '"fieldname" : "0189abcdef..."' or "0189abcdef..." if fieldname is NULL */ void json_add_hex(struct json_result *result, const char *fieldname, const void *data, size_t len); +/* '"fieldname" : "0189abcdef..."' or "0189abcdef..." if fieldname is NULL */ +void json_add_hex_reversed(struct json_result *result, const char *fieldname, + const void *data, size_t len); void json_add_object(struct json_result *result, ...); const char *json_result_string(const struct json_result *result);