AK: Simplify String::from_stream by leveraging StringBase helpers

This commit is contained in:
Dan Klishch 2023-10-28 17:11:55 -04:00 committed by Andrew Kaster
parent 7506736869
commit 7dbe357e9f
Notes: sideshowbarker 2024-07-16 23:08:48 +09:00
2 changed files with 8 additions and 32 deletions

View file

@ -64,28 +64,6 @@ ErrorOr<NonnullRefPtr<StringData>> StringData::create_uninitialized(size_t byte_
return new_string_data;
}
static ErrorOr<void> read_stream_into_buffer(Stream& stream, Bytes buffer)
{
TRY(stream.read_until_filled(buffer));
if (!Utf8View { StringView { buffer } }.validate())
return Error::from_string_literal("String::from_stream: Input was not valid UTF-8");
return {};
}
ErrorOr<NonnullRefPtr<StringData>> StringData::from_stream(Stream& stream, size_t byte_count)
{
// Strings of MAX_SHORT_STRING_BYTE_COUNT bytes or less should be handled by the String short string optimization.
VERIFY(byte_count > String::MAX_SHORT_STRING_BYTE_COUNT);
u8* buffer = nullptr;
auto new_string_data = TRY(create_uninitialized(byte_count, buffer));
TRY(read_stream_into_buffer(stream, { buffer, byte_count }));
return new_string_data;
}
ErrorOr<NonnullRefPtr<StringData>> StringData::create_substring(StringData const& superstring, size_t start, size_t byte_count)
{
// Strings of MAX_SHORT_STRING_BYTE_COUNT bytes or less should be handled by the String short string optimization.
@ -135,15 +113,14 @@ ErrorOr<String> String::from_utf8(StringView view)
ErrorOr<String> String::from_stream(Stream& stream, size_t byte_count)
{
if (byte_count <= MAX_SHORT_STRING_BYTE_COUNT) {
ShortString short_string;
if (byte_count > 0)
TRY(Detail::read_stream_into_buffer(stream, { short_string.storage, byte_count }));
short_string.byte_count_and_short_string_flag = (byte_count << 1) | SHORT_STRING_FLAG;
return String { short_string };
}
auto data = TRY(Detail::StringData::from_stream(stream, byte_count));
return String { move(data) };
String result;
TRY(result.replace_with_new_string(byte_count, [&](Bytes buffer) -> ErrorOr<void> {
TRY(stream.read_until_filled(buffer));
if (!Utf8View { StringView { buffer } }.validate())
return Error::from_string_literal("String::from_stream: Input was not valid UTF-8");
return {};
}));
return result;
}
ErrorOr<String> String::repeated(u32 code_point, size_t count)

View file

@ -17,7 +17,6 @@ class StringData final : public RefCounted<StringData> {
public:
static ErrorOr<NonnullRefPtr<StringData>> create_uninitialized(size_t, u8*& buffer);
static ErrorOr<NonnullRefPtr<StringData>> create_substring(StringData const& superstring, size_t start, size_t byte_count);
static ErrorOr<NonnullRefPtr<StringData>> from_stream(Stream&, size_t byte_count);
struct SubstringData {
StringData const* superstring { nullptr };