From f7499ccf45315a57b65f7c176ba23a8265ae01cf Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Fri, 3 Nov 2023 20:27:41 +1100 Subject: Add support for 0-padding in format and replace uses of sprintf --- src/string_utils.cc | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) (limited to 'src/string_utils.cc') diff --git a/src/string_utils.cc b/src/string_utils.cc index bc368978..53d2d455 100644 --- a/src/string_utils.cc +++ b/src/string_utils.cc @@ -215,7 +215,7 @@ InplaceString<23> to_string(float val) return to_string_impl<23>(val, std::chars_format::general); #else InplaceString<23> res; - res.m_length = sprintf(res.m_data, "%f", val); + res.m_length = snprintf(res.m_data, 23, "%f", val); return res; #endif } @@ -360,9 +360,15 @@ void format_impl(StringView fmt, ArrayView params, AppendFunc if (format != closing) { - for (ColumnCount width = str_to_int({format+1, closing}), len = params[index].column_length(); + char padding = ' '; + if (*(++format) == '0') + { + padding = '0'; + ++format; + } + for (ColumnCount width = str_to_int({format, closing}), len = params[index].column_length(); width > len; --width) - append(' '); + append(padding); } append(params[index]); @@ -475,7 +481,7 @@ UnitTest test_string{[]() kak_assert(subsequence_match("tchou kanaky", "tchou kanaky")); kak_assert(not subsequence_match("tchou kanaky", "tchou kanaky")); - kak_assert(format("Youhou {1} {} '{0:4}' \\{}", 10, "hehe", 5) == "Youhou hehe 5 ' 10' {}"); + kak_assert(format("Youhou {1} {} '{0:4}' {2:04} \\{}", 10, "hehe", 5) == "Youhou hehe 5 ' 10' 0005 {}"); char buffer[20]; kak_assert(format_to(buffer, "Hey {}", 15) == "Hey 15"); -- cgit v1.2.3