text
stringlengths
0
357
{
char* out = malloc(bytes+1);
if (out==NULL) {
exit(45);
}
if (in && bytes > 0) {
strncpy(out, in, bytes);
}
out[bytes] = 0;
return out;
}
/**
* Converts a byte-buffer to a string with hexadecimal,
* upper-case digits.
*
* This function is used eg. to create readable fingerprints, however, it may
* be used for other purposes as well.
*
* @param buf The buffer to convert to an hexadecimal string. If this is NULL,
* the functions returns NULL.
* @param bytes The number of bytes in buf. buf may or may not be null-terminated
* If this is <=0, the function returns NULL.
* @return Returns a null-terminated string, must be free()'d when no longer
* needed. For errors, NULL is returned.
*/
char* dc_binary_to_uc_hex(const uint8_t* buf, size_t bytes)
{
char* hex = NULL;
int i = 0;
if (buf==NULL || bytes<=0) {
goto cleanup;
}
if ((hex=calloc(sizeof(char), bytes*2+1))==NULL) {
goto cleanup;
}
for (i = 0; i < bytes; i++) {
snprintf(&hex[i*2], 3, "%02X", (int)buf[i]);
}
cleanup:
return hex;
}
char* dc_mprintf(const char* format, ...)
{
char testbuf[1];
char* buf = NULL;
int char_cnt_without_zero = 0;
va_list argp;
va_list argp_copy;
va_start(argp, format);
va_copy(argp_copy, argp);
char_cnt_without_zero = vsnprintf(testbuf, 0, format, argp);
va_end(argp);
if (char_cnt_without_zero < 0) {
va_end(argp_copy);
return dc_strdup("ErrFmt");
}
buf = malloc(char_cnt_without_zero+2 /* +1 would be enough, however, protect against off-by-one-errors */);
if (buf==NULL) {
va_end(argp_copy);
return dc_strdup("ErrMem");
}
vsnprintf(buf, char_cnt_without_zero+1, format, argp_copy);
va_end(argp_copy);
return buf;
#if 0 /* old implementation based upon sqlite3 */
char *sqlite_str, *c_string;
va_list argp;
va_start(argp, format); /* expects the last non-variable argument as the second parameter */
sqlite_str = sqlite3_vmprintf(format, argp);
va_end(argp);
if (sqlite_str==NULL) {
return dc_strdup("ErrFmt"); /* error - the result must be free()'d */
}
/* as sqlite-strings must be freed using sqlite3_free() instead of a simple free(), convert it to a normal c-string */
c_string = dc_strdup(sqlite_str); /* exists on errors */
sqlite3_free(sqlite_str);
return c_string; /* success - the result must be free()'d */
#endif /* /old implementation based upon sqlite3 */
}
/**
* Remove all `\r` characters from the given buffer.