mirror of
https://github.com/ARM-software/arm-trusted-firmware.git
synced 2025-04-16 17:44:19 +00:00
libc/snprintf: use macro to reduce duplicated code
Add macro CHECK_AND_PUT_CHAR to check buffer capacity, save one character to buffer, and then increase character counter by one in one single statement, so that 4 similar code pieces can be cleaned. Signed-off-by: Heyi Guo <guoheyi@linux.alibaba.com> Change-Id: I2add6b4bd6c24ea3c0d2499a44924e3e8db0f4d1
This commit is contained in:
parent
c654615466
commit
7981c5043b
1 changed files with 14 additions and 22 deletions
|
@ -10,16 +10,20 @@
|
|||
#include <common/debug.h>
|
||||
#include <plat/common/platform.h>
|
||||
|
||||
#define CHECK_AND_PUT_CHAR(buf, size, chars_printed, ch) \
|
||||
do { \
|
||||
if ((chars_printed) < (size)) { \
|
||||
*(buf) = (ch); \
|
||||
(buf)++; \
|
||||
} \
|
||||
(chars_printed)++; \
|
||||
} while (false)
|
||||
|
||||
static void string_print(char **s, size_t n, size_t *chars_printed,
|
||||
const char *str)
|
||||
{
|
||||
while (*str != '\0') {
|
||||
if (*chars_printed < n) {
|
||||
*(*s) = *str;
|
||||
(*s)++;
|
||||
}
|
||||
|
||||
(*chars_printed)++;
|
||||
CHECK_AND_PUT_CHAR(*s, n, *chars_printed, *str);
|
||||
str++;
|
||||
}
|
||||
}
|
||||
|
@ -131,11 +135,7 @@ int vsnprintf(char *s, size_t n, const char *fmt, va_list args)
|
|||
loop:
|
||||
switch (*fmt) {
|
||||
case '%':
|
||||
if (chars_printed < n) {
|
||||
*s = '%';
|
||||
s++;
|
||||
}
|
||||
chars_printed++;
|
||||
CHECK_AND_PUT_CHAR(s, n, chars_printed, '%');
|
||||
break;
|
||||
case '0':
|
||||
case '1':
|
||||
|
@ -165,12 +165,8 @@ loop:
|
|||
num = va_arg(args, int);
|
||||
|
||||
if (num < 0) {
|
||||
if (chars_printed < n) {
|
||||
*s = '-';
|
||||
s++;
|
||||
}
|
||||
chars_printed++;
|
||||
|
||||
CHECK_AND_PUT_CHAR(s, n, chars_printed,
|
||||
'-');
|
||||
unum = (unsigned int)-num;
|
||||
} else {
|
||||
unum = (unsigned int)num;
|
||||
|
@ -217,13 +213,9 @@ loop:
|
|||
continue;
|
||||
}
|
||||
|
||||
if (chars_printed < n) {
|
||||
*s = *fmt;
|
||||
s++;
|
||||
}
|
||||
CHECK_AND_PUT_CHAR(s, n, chars_printed, *fmt);
|
||||
|
||||
fmt++;
|
||||
chars_printed++;
|
||||
}
|
||||
|
||||
if (n > 0U) {
|
||||
|
|
Loading…
Add table
Reference in a new issue