aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorHeyi Guo <guoheyi@linux.alibaba.com>2021-01-20 13:55:25 +0800
committerHeyi Guo <guoheyi@linux.alibaba.com>2021-01-20 14:16:04 +0800
commit7981c5043b3b77b87847148ea0df81e9ec59aa56 (patch)
tree9c37d0283cc8410560a31f0568d0bbed46af02a9 /lib
parentc654615466465526290ea0b0ba909b5a010b8bef (diff)
downloadarm-trusted-firmware-7981c5043b3b77b87847148ea0df81e9ec59aa56.tar.gz
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
Diffstat (limited to 'lib')
-rw-r--r--lib/libc/snprintf.c36
1 files changed, 14 insertions, 22 deletions
diff --git a/lib/libc/snprintf.c b/lib/libc/snprintf.c
index 42faa269d..3b175ed6a 100644
--- a/lib/libc/snprintf.c
+++ b/lib/libc/snprintf.c
@@ -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) {