1
0
mirror of https://github.com/SerenityOS/serenity synced 2024-07-01 11:55:37 +00:00

AK: Make FlyString::from_utf8*() avoid allocation if possible

If we already have a FlyString instantiated for the given string,
look that up and return it instead of making a temporary String just to
use as a key into the FlyString table.
This commit is contained in:
Andreas Kling 2024-03-23 20:03:38 +01:00
parent 8d7a1e5654
commit 3bdfca1119
2 changed files with 17 additions and 0 deletions

View File

@ -28,11 +28,23 @@ static auto& all_fly_strings()
ErrorOr<FlyString> FlyString::from_utf8(StringView string)
{
if (string.is_empty())
return FlyString {};
if (string.length() <= Detail::MAX_SHORT_STRING_BYTE_COUNT)
return FlyString { TRY(String::from_utf8(string)) };
if (auto it = all_fly_strings().find(string.hash(), [&](auto& entry) { return entry->bytes_as_string_view() == string; }); it != all_fly_strings().end())
return FlyString { Detail::StringBase(**it) };
return FlyString { TRY(String::from_utf8(string)) };
}
FlyString FlyString::from_utf8_without_validation(ReadonlyBytes string)
{
if (string.is_empty())
return FlyString {};
if (string.size() <= Detail::MAX_SHORT_STRING_BYTE_COUNT)
return FlyString { String::from_utf8_without_validation(string) };
if (auto it = all_fly_strings().find(StringView(string).hash(), [&](auto& entry) { return entry->bytes_as_string_view() == string; }); it != all_fly_strings().end())
return FlyString { Detail::StringBase(**it) };
return FlyString { String::from_utf8_without_validation(string) };
}

View File

@ -77,6 +77,11 @@ public:
}
private:
explicit FlyString(Detail::StringBase data)
: m_data(move(data))
{
}
Detail::StringBase m_data;
};