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 @@ ...@@ -10,16 +10,20 @@
#include <common/debug.h> #include <common/debug.h>
#include <plat/common/platform.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, static void string_print(char **s, size_t n, size_t *chars_printed,
const char *str) const char *str)
{ {
while (*str != '\0') { while (*str != '\0') {
if (*chars_printed < n) { CHECK_AND_PUT_CHAR(*s, n, *chars_printed, *str);
*(*s) = *str;
(*s)++;
}
(*chars_printed)++;
str++; str++;
} }
} }
...@@ -131,11 +135,7 @@ int vsnprintf(char *s, size_t n, const char *fmt, va_list args) ...@@ -131,11 +135,7 @@ int vsnprintf(char *s, size_t n, const char *fmt, va_list args)
loop: loop:
switch (*fmt) { switch (*fmt) {
case '%': case '%':
if (chars_printed < n) { CHECK_AND_PUT_CHAR(s, n, chars_printed, '%');
*s = '%';
s++;
}
chars_printed++;
break; break;
case '0': case '0':
case '1': case '1':
...@@ -165,12 +165,8 @@ loop: ...@@ -165,12 +165,8 @@ loop:
num = va_arg(args, int); num = va_arg(args, int);
if (num < 0) { if (num < 0) {
if (chars_printed < n) { CHECK_AND_PUT_CHAR(s, n, chars_printed,
*s = '-'; '-');
s++;
}
chars_printed++;
unum = (unsigned int)-num; unum = (unsigned int)-num;
} else { } else {
unum = (unsigned int)num; unum = (unsigned int)num;
...@@ -217,13 +213,9 @@ loop: ...@@ -217,13 +213,9 @@ loop:
continue; continue;
} }
if (chars_printed < n) { CHECK_AND_PUT_CHAR(s, n, chars_printed, *fmt);
*s = *fmt;
s++;
}
fmt++; fmt++;
chars_printed++;
} }
if (n > 0U) { 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