From 7981c5043b3b77b87847148ea0df81e9ec59aa56 Mon Sep 17 00:00:00 2001 From: Heyi Guo Date: Wed, 20 Jan 2021 13:55:25 +0800 Subject: [PATCH] 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 Change-Id: I2add6b4bd6c24ea3c0d2499a44924e3e8db0f4d1 --- lib/libc/snprintf.c | 36 ++++++++++++++---------------------- 1 file 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 #include +#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) { -- GitLab