1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-14 08:14:58 +00:00

AK+Everywhere: Make UTF-8 and UTF-32 to UTF-16 converters fallible

These could fail to allocate the underlying storage needed to store the
UTF-16 data. Propagate these errors.
This commit is contained in:
Timothy Flynn 2023-01-06 13:19:34 -05:00 committed by Linus Groh
parent d8044c5358
commit 1edb96376b
13 changed files with 46 additions and 35 deletions

View file

@ -5,6 +5,7 @@
*/
#include <AK/CharacterTypes.h>
#include <AK/Concepts.h>
#include <AK/StringBuilder.h>
#include <AK/StringView.h>
#include <AK/Utf16View.h>
@ -20,45 +21,46 @@ static constexpr u16 low_surrogate_max = 0xdfff;
static constexpr u32 replacement_code_point = 0xfffd;
static constexpr u32 first_supplementary_plane_code_point = 0x10000;
template<typename UtfViewType>
static Utf16Data to_utf16_impl(UtfViewType const& view)
requires(IsSame<UtfViewType, Utf8View> || IsSame<UtfViewType, Utf32View>)
template<OneOf<Utf8View, Utf32View> UtfViewType>
static ErrorOr<Utf16Data> to_utf16_impl(UtfViewType const& view)
{
Utf16Data utf16_data;
utf16_data.ensure_capacity(view.length());
TRY(utf16_data.try_ensure_capacity(view.length()));
for (auto code_point : view)
code_point_to_utf16(utf16_data, code_point);
TRY(code_point_to_utf16(utf16_data, code_point));
return utf16_data;
}
Utf16Data utf8_to_utf16(StringView utf8_view)
ErrorOr<Utf16Data> utf8_to_utf16(StringView utf8_view)
{
return to_utf16_impl(Utf8View { utf8_view });
}
Utf16Data utf8_to_utf16(Utf8View const& utf8_view)
ErrorOr<Utf16Data> utf8_to_utf16(Utf8View const& utf8_view)
{
return to_utf16_impl(utf8_view);
}
Utf16Data utf32_to_utf16(Utf32View const& utf32_view)
ErrorOr<Utf16Data> utf32_to_utf16(Utf32View const& utf32_view)
{
return to_utf16_impl(utf32_view);
}
void code_point_to_utf16(Utf16Data& string, u32 code_point)
ErrorOr<void> code_point_to_utf16(Utf16Data& string, u32 code_point)
{
VERIFY(is_unicode(code_point));
if (code_point < first_supplementary_plane_code_point) {
string.append(static_cast<u16>(code_point));
TRY(string.try_append(static_cast<u16>(code_point)));
} else {
code_point -= first_supplementary_plane_code_point;
string.append(static_cast<u16>(high_surrogate_min | (code_point >> 10)));
string.append(static_cast<u16>(low_surrogate_min | (code_point & 0x3ff)));
TRY(string.try_append(static_cast<u16>(high_surrogate_min | (code_point >> 10))));
TRY(string.try_append(static_cast<u16>(low_surrogate_min | (code_point & 0x3ff))));
}
return {};
}
bool Utf16View::is_high_surrogate(u16 code_unit)