Commit 7981c504 authored by Heyi Guo's avatar Heyi Guo
Browse files

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: default avatarHeyi Guo <guoheyi@linux.alibaba.com>
Change-Id: I2add6b4bd6c24ea3c0d2499a44924e3e8db0f4d1
parent c6546154
......@@ -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) {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment