From 6c7c19e4378b9b9640dc0b250d09264f5cd99572 Mon Sep 17 00:00:00 2001
From: dzwdz
Date: Thu, 15 Sep 2022 22:43:39 +0200
Subject: shared/printf: string precision

---
 src/shared/printf.c                | 8 +++++++-
 src/user/app/tests/shared/printf.c | 3 +++
 2 files changed, 10 insertions(+), 1 deletion(-)

(limited to 'src')

diff --git a/src/shared/printf.c b/src/shared/printf.c
index 9ab4606..a9cd355 100644
--- a/src/shared/printf.c
+++ b/src/shared/printf.c
@@ -131,7 +131,11 @@ int __printf_internal(const char *fmt, va_list argp,
 
 		if (c == '.') {
 			c = *fmt++;
-			while ('0' <= c && c <= '9') {
+			if (c == '*') {
+				// TODO handle negative precision
+				m.precision = va_arg(argp, int);
+				c = *fmt++;
+			} else while ('0' <= c && c <= '9') {
 				m.precision *= 10;
 				m.precision += c - '0';
 				c = *fmt++;
@@ -166,6 +170,8 @@ int __printf_internal(const char *fmt, va_list argp,
 				const char *s = va_arg(argp, char*);
 				if (s == NULL) s = "(null)";
 				len = strlen(s);
+				if (len > m.precision && m.precision != 0)
+					len = m.precision;
 				pad(&os, &m, len);
 				output(&os, s, len);
 				break;
diff --git a/src/user/app/tests/shared/printf.c b/src/user/app/tests/shared/printf.c
index 37b9679..71122f5 100644
--- a/src/user/app/tests/shared/printf.c
+++ b/src/user/app/tests/shared/printf.c
@@ -43,6 +43,9 @@ static void test_printf(void) {
 	test(!strcmp(buf, " -001"));
 	snprintf(buf, sizeof buf, "%.5d", 123);
 	test(!strcmp(buf, "00123"));
+
+	snprintf(buf, sizeof buf, "%.1s,%.10s,%.*s", "hello", "hello", 3, "hello");
+	test(!strcmp(buf, "h,hello,hel"));
 }
 
 void r_s_printf(void) {
-- 
cgit v1.2.3