AK: Format char as unsigned char on non-x86

`char` isn't signed in the AArch64 and RISC-V ABIs.
This commit is contained in:
Sönke Holz
2026-03-19 11:14:13 +01:00
committed by Sönke Holz
parent 644659c3c1
commit ae51627668
2 changed files with 18 additions and 2 deletions

View File

@@ -949,8 +949,13 @@ ErrorOr<void> Formatter<char>::format(FormatBuilder& builder, char value)
{
if (m_mode == Mode::Binary || m_mode == Mode::BinaryUppercase || m_mode == Mode::Decimal || m_mode == Mode::Octal || m_mode == Mode::Hexadecimal || m_mode == Mode::HexadecimalUppercase) {
// Trick: signed char != char. (Sometimes weird features are actually helpful.)
Formatter<signed char> formatter { *this };
return formatter.format(builder, static_cast<signed char>(value));
if constexpr (IsSigned<char>) {
Formatter<signed char> formatter { *this };
return formatter.format(builder, static_cast<signed char>(value));
} else {
Formatter<unsigned char> formatter { *this };
return formatter.format(builder, static_cast<unsigned char>(value));
}
} else {
Formatter<StringView> formatter { *this };
return formatter.format(builder, { &value, 1 });

View File

@@ -223,6 +223,17 @@ struct AK::Formatter<B> : Formatter<StringView> {
}
};
TEST_CASE(format_character_as_integer)
{
EXPECT_EQ(ByteString::formatted("{:x}", 'A'), "41");
if constexpr (IsSigned<char>) {
EXPECT_EQ(ByteString::formatted("{:x}", '\x86'), "-7a");
} else {
EXPECT_EQ(ByteString::formatted("{:x}", '\x86'), "86");
}
}
TEST_CASE(format_if_supported)
{
EXPECT_EQ(ByteString::formatted("{}", FormatIfSupported { A {} }), "?");