From d8aa2a6997800779cd2dc4303cb2256a32ffc2f3 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Fri, 15 May 2020 13:36:50 +0200 Subject: [PATCH] AK: StringBuilder with 0 initial capacity shouldn't build null String With 0 initial capacity, we don't allocate an underlying ByteBuffer for the StringBuilder, which would then lead to a null String() being returned from to_string(). This patch makes sure we always build a valid String. --- AK/StringBuilder.cpp | 2 ++ AK/Tests/TestString.cpp | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/AK/StringBuilder.cpp b/AK/StringBuilder.cpp index 17be5972a9..ffae4e76da 100644 --- a/AK/StringBuilder.cpp +++ b/AK/StringBuilder.cpp @@ -91,6 +91,8 @@ ByteBuffer StringBuilder::to_byte_buffer() const String StringBuilder::to_string() const { + if (is_empty()) + return String::empty(); return String((const char*)m_buffer.data(), m_length); } diff --git a/AK/Tests/TestString.cpp b/AK/Tests/TestString.cpp index bd9a8fbc73..5576bcec90 100644 --- a/AK/Tests/TestString.cpp +++ b/AK/Tests/TestString.cpp @@ -199,4 +199,13 @@ TEST_CASE(split) EXPECT_EQ(parts[2].characters()[3], '\0'); } +TEST_CASE(builder_zero_initial_capacity) +{ + StringBuilder builder(0); + builder.append(""); + auto built = builder.build(); + EXPECT_EQ(built.is_null(), false); + EXPECT_EQ(built.length(), 0u); +} + TEST_MAIN(String)