AK: Make StringBuilder::try_append_code_point actually fallible
It currently uses the non-fallible `append` method to append each UTF-8 encoded byte of the code point.
This commit is contained in:
parent
aee7c44064
commit
39bda0073e
Notes:
sideshowbarker
2024-07-17 08:59:18 +09:00
Author: https://github.com/trflynn89 Commit: https://github.com/SerenityOS/serenity/commit/39bda0073e Pull-request: https://github.com/SerenityOS/serenity/pull/16895 Reviewed-by: https://github.com/linusg
2 changed files with 31 additions and 1 deletions
|
@ -141,7 +141,7 @@ void StringBuilder::clear()
|
|||
|
||||
ErrorOr<void> StringBuilder::try_append_code_point(u32 code_point)
|
||||
{
|
||||
auto nwritten = AK::UnicodeUtils::code_point_to_utf8(code_point, [this](char c) { append(c); });
|
||||
auto nwritten = TRY(AK::UnicodeUtils::try_code_point_to_utf8(code_point, [this](char c) { return try_append(c); }));
|
||||
if (nwritten < 0) {
|
||||
TRY(try_append(0xef));
|
||||
TRY(try_append(0xbf));
|
||||
|
|
|
@ -6,6 +6,8 @@
|
|||
|
||||
#pragma once
|
||||
|
||||
#include <AK/Concepts.h>
|
||||
#include <AK/Error.h>
|
||||
#include <AK/Forward.h>
|
||||
|
||||
namespace AK::UnicodeUtils {
|
||||
|
@ -35,4 +37,32 @@ template<typename Callback>
|
|||
return -1;
|
||||
}
|
||||
|
||||
template<FallibleFunction<char> Callback>
|
||||
[[nodiscard]] ErrorOr<int> try_code_point_to_utf8(u32 code_point, Callback&& callback)
|
||||
{
|
||||
if (code_point <= 0x7f) {
|
||||
TRY(callback(static_cast<char>(code_point)));
|
||||
return 1;
|
||||
}
|
||||
if (code_point <= 0x07ff) {
|
||||
TRY(callback(static_cast<char>((((code_point >> 6) & 0x1f) | 0xc0))));
|
||||
TRY(callback(static_cast<char>((((code_point >> 0) & 0x3f) | 0x80))));
|
||||
return 2;
|
||||
}
|
||||
if (code_point <= 0xffff) {
|
||||
TRY(callback(static_cast<char>((((code_point >> 12) & 0x0f) | 0xe0))));
|
||||
TRY(callback(static_cast<char>((((code_point >> 6) & 0x3f) | 0x80))));
|
||||
TRY(callback(static_cast<char>((((code_point >> 0) & 0x3f) | 0x80))));
|
||||
return 3;
|
||||
}
|
||||
if (code_point <= 0x10ffff) {
|
||||
TRY(callback(static_cast<char>((((code_point >> 18) & 0x07) | 0xf0))));
|
||||
TRY(callback(static_cast<char>((((code_point >> 12) & 0x3f) | 0x80))));
|
||||
TRY(callback(static_cast<char>((((code_point >> 6) & 0x3f) | 0x80))));
|
||||
TRY(callback(static_cast<char>((((code_point >> 0) & 0x3f) | 0x80))));
|
||||
return 4;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue