I want to convert a uuid to hex string in C99 and pass it to a log function which uses printf format under the hood. I want to avoid the separate allocation of local variable because if the log is disabled then the preprocessor removes the function call and the variable becomes unused so a warning is emitted.
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
typedef struct {
uint8_t data[8];
} uuid_64_t;
#define UID_64_STR_MAX_SIZE 24
#define UUID_64_TO_STRING(uuid_64, separator, uppercase) \
uuid_64_to_string((char[UID_64_STR_MAX_SIZE]){ 0 }, \
sizeof((char[UID_64_STR_MAX_SIZE]){ 0 }), \
uuid_64, \
separator, \
uppercase)
const char *bytes_to_hex(char *buffer,
uint32_t buffer_size,
const uint8_t *bytes,
uint32_t bytes_size,
char separator,
bool uppercase)
{
const char hex_char_uppercase[] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
const char hex_char_lowercase[] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
const char *hex_char = uppercase ? hex_char_uppercase : hex_char_lowercase;
uint32_t total_size, total_separator_size;
// If the separator is set the null character then no separator is used so
// the multiplication by zero results in zero total separator size.
// There is a separator after each two hex characters except for the last two.
total_separator_size = (bytes_size - 1) * (separator != '\0');
// One character shall be reserved for the terminating null character
total_size = 2 * bytes_size total_separator_size 1;
if ((buffer == NULL) || (bytes == NULL) || (buffer_size < total_size)) {
return "INVALID";
}
uint32_t out_idx = 0;
for (uint32_t in_idx = 0; in_idx < bytes_size; in_idx ) {
buffer[out_idx ] = hex_char[(bytes[in_idx] >> 4) & 0xF];
buffer[out_idx ] = hex_char[(bytes[in_idx] >> 0) & 0xF];
if (separator != '\0' && (in_idx 1) < bytes_size) {
buffer[out_idx ] = separator;
}
}
buffer[out_idx] = '\0';
return buffer;
}
const char *uuid_64_to_string(char *buffer,
uint32_t buffer_size,
const uuid_64_t *uuid_64,
char separator,
bool uppercase)
{
return bytes_to_hex(buffer,
buffer_size,
uuid_64->data,
sizeof(uuid_64->data),
separator,
uppercase);
}
int main(void)
{
printf("uuid=%s\r\n", UUID_64_TO_STRING(&uuid_64, ':', true));
}
The idea is to call a function through a macro which passes a compound literal as the buffer parameter. The compound literal allocates a local variable where the uuid_64_to_string function writes the hex characters through bytes_to_hex function. The uuid_64_to_string returns this passed compound literal in order to use it directly in a printf-like log call. The only problem can be the lifetime of the compound literal and I am a little be unsure about this. According to C99 standard:
The value of the compound literal is that of an unnamed object initialized by the initializer list. If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block
So as I interpret the standard this should be well-defined behavior because the printf call and uuid_64_to_string call are in the same block. What is you opinion?
CodePudding user response:
The macro UUID_64_TO_STRING
expands to a function call to uuid_64_to_string
passing a pointer to a compound literal (char[UID_64_STR_MAX_SIZE]){ 0 }
whose scope is the enclosing block in the main()
function.
The function uuid_64_to_string
returns its first argument, hence the pointer to the local array. It is OK to pass that to printf
as an argument because the object it points to is a C string and has a lifetime that covers the execution of the printf
call.
Conversely, it would be a mistake to return this pointer to the calling function or to store it into a pointer used outside the current scope:
int main() {
printf("uuid=%s\r\n", UUID_64_TO_STRING(&uuid_64, ':', true)); // OK
return 0;
}
This use is invalid:
char *hexify(uuid_64_t *id) {
return UUID_64_TO_STRING(id, ':', true); // NOT OK
}
int main() {
printf("uuid=%s\r\n", hexify(&uuid_64)); // NOT OK
return 0;
}
Note that the scoping issue may be subtle:
int main() {
const char *p = "invalid id";
if (isValidID(uuid_64))
p = UUID_64_TO_STRING(&uuid_64, ':', true);
printf("uuid=%s\r\n", p); // OK
return 0;
}
int main() {
const char *p = "invalid id";
if (isValidID(uuid_64)) {
p = UUID_64_TO_STRING(&uuid_64, ':', true);
}
printf("uuid=%s\r\n", p); // NOT OK
return 0;
}
While this macro seems useful, it should be used with care, probably only as a function argument.