[PATCH 13/15] print_integer, printf: rewrite num_to_str() via print_integer()
From: Alexey Dobriyan
Date: Mon Apr 20 2020 - 16:58:44 EST
In my opinion, num_to_str() is more understandable this way.
Signed-off-by: Alexey Dobriyan <adobriyan@xxxxxxxxx>
---
lib/vsprintf.c | 30 +++++++++++-------------------
1 file changed, 11 insertions(+), 19 deletions(-)
diff --git a/lib/vsprintf.c b/lib/vsprintf.c
index 7c488a1ce318..df2b5ce08fe9 100644
--- a/lib/vsprintf.c
+++ b/lib/vsprintf.c
@@ -51,6 +51,7 @@
#include <linux/string_helpers.h>
#include "kstrtox.h"
+#include "print-integer.h"
/**
* simple_strtoull - convert a string to an unsigned long long
@@ -343,33 +344,24 @@ char *put_dec(char *buf, unsigned long long n)
*/
int num_to_str(char *buf, int size, unsigned long long num, unsigned int width)
{
- /* put_dec requires 2-byte alignment of the buffer. */
- char tmp[sizeof(num) * 3] __aligned(2);
- int idx, len;
+ char tmp[20];
+ char *p = tmp + sizeof(tmp);
+ ptrdiff_t len;
- /* put_dec() may work incorrectly for num = 0 (generate "", not "0") */
- if (num <= 9) {
- tmp[0] = '0' + num;
- len = 1;
- } else {
- len = put_dec(tmp, num) - tmp;
- }
+ p = _print_integer_u64(p, num);
+ len = tmp + sizeof(tmp) - p;
if (len > size || width > size)
return 0;
if (width > len) {
- width = width - len;
- for (idx = 0; idx < width; idx++)
- buf[idx] = ' ';
+ memset(buf, ' ', width - len);
+ memcpy(buf + width - len, p, len);
+ return width;
} else {
- width = 0;
+ memcpy(buf, p, len);
+ return len;
}
-
- for (idx = 0; idx < len; ++idx)
- buf[idx + width] = tmp[len - idx - 1];
-
- return len + width;
}
#define SIGN 1 /* unsigned/signed, must be 1 */
--
2.24.1