Add DStr sprintf
This commit is contained in:
+54
-1
@@ -1,5 +1,7 @@
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include "ucore/dstr.h"
|
||||
#include "ucore/utils.h"
|
||||
|
||||
@@ -26,7 +28,7 @@ int uc_dstr_ensure(struct DStr *str, size_t len)
|
||||
//allocate a minimum no. of bytes, and one
|
||||
//additional for the common case of nul terminating
|
||||
//the string
|
||||
size_t new_len = str->len + UC_MAX(7U, len) + 1;
|
||||
size_t new_len = UC_MAX(7U, len) + 1;
|
||||
char *new_str = realloc(str->str, new_len);
|
||||
|
||||
if (new_str == NULL) {
|
||||
@@ -204,4 +206,55 @@ void uc_dstr_trim(struct DStr *str)
|
||||
}
|
||||
}
|
||||
|
||||
int uc_dstr_sprintf(struct DStr *str, const char *fmt, ...)
|
||||
{
|
||||
va_list ap;
|
||||
int rc;
|
||||
|
||||
va_start(ap, fmt);
|
||||
rc = uc_dstr_vsprintf(str, fmt, ap);
|
||||
va_end(ap);
|
||||
|
||||
return rc;
|
||||
}
|
||||
|
||||
int uc_dstr_vsprintf(struct DStr *str, const char *fmt, va_list ap_)
|
||||
{
|
||||
va_list ap;
|
||||
int rc;
|
||||
int available;
|
||||
int needed;
|
||||
|
||||
rc = uc_dstr_ensure(str, str->len + 1);
|
||||
if (rc != 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
available = uc_dstr_available(str);
|
||||
|
||||
va_copy(ap, ap_);
|
||||
needed = vsnprintf(str->str + str->len, available, fmt, ap);
|
||||
va_end(ap);
|
||||
|
||||
if (needed <= 0) {
|
||||
return needed;
|
||||
}
|
||||
|
||||
if (needed >= available) {
|
||||
rc = uc_dstr_ensure(str, str->len + needed);
|
||||
if (rc != 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
available = uc_dstr_available(str);
|
||||
|
||||
va_copy(ap, ap_);
|
||||
needed = vsnprintf(str->str + str->len, available, fmt, ap);
|
||||
va_end(ap);
|
||||
}
|
||||
|
||||
str->len += needed;
|
||||
|
||||
return needed;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user