1
0
mirror of https://github.com/SerenityOS/serenity synced 2024-07-05 22:54:55 +00:00

AK: Add formatters for Span<T> and Span<T const>

This generalizes the formatter currently used for Vector to be usable
for any Span.
This commit is contained in:
Timothy Flynn 2022-12-08 08:08:08 -05:00 committed by Andreas Kling
parent c372012842
commit 949f5460fb
2 changed files with 42 additions and 4 deletions

View File

@ -329,15 +329,16 @@ struct Formatter<StringView> : StandardFormatter {
ErrorOr<void> format(FormatBuilder&, StringView);
};
template<typename T, size_t inline_capacity>
requires(HasFormatter<T>) struct Formatter<Vector<T, inline_capacity>> : StandardFormatter {
template<typename T>
requires(HasFormatter<T>)
struct Formatter<Span<T const>> : StandardFormatter {
Formatter() = default;
explicit Formatter(StandardFormatter formatter)
: StandardFormatter(move(formatter))
{
}
ErrorOr<void> format(FormatBuilder& builder, Vector<T> value)
ErrorOr<void> format(FormatBuilder& builder, Span<T const> value)
{
if (m_mode == Mode::Pointer) {
Formatter<FlatPtr> formatter { *this };
@ -375,6 +376,24 @@ requires(HasFormatter<T>) struct Formatter<Vector<T, inline_capacity>> : Standar
}
};
template<typename T>
requires(HasFormatter<T>)
struct Formatter<Span<T>> : Formatter<Span<T const>> {
ErrorOr<void> format(FormatBuilder& builder, Span<T> value)
{
return Formatter<Span<T const>>::format(builder, value);
}
};
template<typename T, size_t inline_capacity>
requires(HasFormatter<T>)
struct Formatter<Vector<T, inline_capacity>> : Formatter<Span<T const>> {
ErrorOr<void> format(FormatBuilder& builder, Vector<T, inline_capacity> const& value)
{
return Formatter<Span<T const>>::format(builder, value.span());
}
};
template<>
struct Formatter<ReadonlyBytes> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder& builder, ReadonlyBytes value)

View File

@ -316,6 +316,25 @@ TEST_CASE(hex_dump)
EXPECT_EQ(DeprecatedString::formatted("{:*>4hex-dump}", "0000"), "30303030****0000");
}
TEST_CASE(span_format)
{
{
Vector<int> v { 1, 2, 3, 4 };
EXPECT_EQ(DeprecatedString::formatted("{}", v.span()), "[ 1, 2, 3, 4 ]");
EXPECT_EQ(DeprecatedString::formatted("{}", const_cast<AddConst<decltype(v)>&>(v).span()), "[ 1, 2, 3, 4 ]");
}
{
Vector<StringView> v { "1"sv, "2"sv, "3"sv, "4"sv };
EXPECT_EQ(DeprecatedString::formatted("{}", v.span()), "[ 1, 2, 3, 4 ]");
EXPECT_EQ(DeprecatedString::formatted("{}", const_cast<AddConst<decltype(v)>&>(v).span()), "[ 1, 2, 3, 4 ]");
}
{
Vector<Vector<DeprecatedString>> v { { "1"sv, "2"sv }, { "3"sv, "4"sv } };
EXPECT_EQ(DeprecatedString::formatted("{}", v.span()), "[ [ 1, 2 ], [ 3, 4 ] ]");
EXPECT_EQ(DeprecatedString::formatted("{}", const_cast<AddConst<decltype(v)>&>(v).span()), "[ [ 1, 2 ], [ 3, 4 ] ]");
}
}
TEST_CASE(vector_format)
{
{