AK: Use new Formatter for each element in Formatter<Vector<T>>

The state of the formatter for the previous element should be thrown
away for each iteration. This showed up when trying to format a
Vector<String>, since Formatter<StringView> was unhappy about some state
that gets set when it's called. Add a test for Formatter<Vector>.
This commit is contained in:
Andrew Kaster 2021-07-17 16:27:12 -06:00 committed by Ali Mohammad Pur
parent 4842c8c902
commit 64aac345d3
Notes: sideshowbarker 2024-07-18 08:46:18 +09:00
2 changed files with 20 additions and 1 deletions

View file

@ -354,8 +354,10 @@ requires(HasFormatter<T>) struct Formatter<Vector<T>> : StandardFormatter {
builder.put_literal("[ "sv);
bool first = true;
for (auto& content : value) {
if (!first)
if (!first) {
builder.put_literal(", "sv);
content_fmt = Formatter<T> {};
}
first = false;
content_fmt.format(builder, content);
}

View file

@ -8,6 +8,7 @@
#include <AK/String.h>
#include <AK/StringBuilder.h>
#include <AK/Vector.h>
TEST_CASE(is_integral_works_properly)
{
@ -306,3 +307,19 @@ TEST_CASE(hex_dump)
EXPECT_EQ(String::formatted("{:>2hex-dump}", "0000"), "3030 00\n3030 00");
EXPECT_EQ(String::formatted("{:*>4hex-dump}", "0000"), "30303030****0000");
}
TEST_CASE(vector_format)
{
{
Vector<int> v { 1, 2, 3, 4 };
EXPECT_EQ(String::formatted("{}", v), "[ 1, 2, 3, 4 ]");
}
{
Vector<StringView> v { "1"sv, "2"sv, "3"sv, "4"sv };
EXPECT_EQ(String::formatted("{}", v), "[ 1, 2, 3, 4 ]");
}
{
Vector<Vector<String>> v { { "1"sv, "2"sv }, { "3"sv, "4"sv } };
EXPECT_EQ(String::formatted("{}", v), "[ [ 1, 2 ], [ 3, 4 ] ]");
}
}