From f8fa9a057ef6d550fda17ae16664c6caeaf2fc46 Mon Sep 17 00:00:00 2001 From: Pierre Curto Date: Tue, 5 Sep 2023 14:39:51 +0200 Subject: [PATCH] lib/std/io: support . string format speficier (#970) Signed-off-by: Pierre Curto --- lib/std/io/formatter.c3 | 27 ++++++++++++++++++++------- test/unit/stdlib/io/printf.c3 | 4 ++++ 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/lib/std/io/formatter.c3 b/lib/std/io/formatter.c3 index d0273fa58..f3f54a4ee 100644 --- a/lib/std/io/formatter.c3 +++ b/lib/std/io/formatter.c3 @@ -49,13 +49,13 @@ struct Formatter bitstruct PrintFlags : uint { - bool zeropad : 0; - bool left : 1; - bool plus : 2; - bool space : 3; - bool hash : 4; - bool uppercase : 5; - bool precision : 6; + bool zeropad; + bool left; + bool plus; + bool space; + bool hash; + bool uppercase; + bool precision; } fn void Formatter.init(&self, OutputFn out_fn, void* data = null) @@ -349,6 +349,19 @@ fn usz! Formatter.vprintf(&self, String format, any[] anys) case 's': PrintFlags flags = self.flags; uint width = self.width; + String str; + if (flags.precision) + { + switch (s = current) + { + case String: + if (s.len > self.prec) + { + str = (*s)[:self.prec]; + current = &str; + } + } + } defer { self.flags = flags; self.width = width; diff --git a/test/unit/stdlib/io/printf.c3 b/test/unit/stdlib/io/printf.c3 index 2234a782c..302bb03c9 100644 --- a/test/unit/stdlib/io/printf.c3 +++ b/test/unit/stdlib/io/printf.c3 @@ -46,4 +46,8 @@ fn void printf_a() assert(s == "[<12, 23>] ", "got '%s'; want '[<12, 23>] '", s); s = string::printf("%20s", vec); assert(s == " [<12, 23>]", "got '%s'; want ' [<12, 23>]'", s); + + String ss = "hello world"; + s = string::printf("%.4s %.5s", ss, ss); + assert(s == "hell hello", "got '%s'; want 'hell hello'", s); } \ No newline at end of file