AK: Allow constructing a UTF-16 view from a UTF-16 string literal

UTF-16 string literals are a language-level feature. It is convenient to
be able to construct a Utf16View from these strings.
This commit is contained in:
Timothy Flynn 2024-01-03 13:16:37 -05:00 committed by Andreas Kling
parent e16345555b
commit c46ba7e68d
2 changed files with 38 additions and 0 deletions

View file

@ -71,6 +71,14 @@ public:
{
}
template<size_t Size>
Utf16View(char16_t const (&code_units)[Size])
: m_code_units(
reinterpret_cast<u16 const*>(&code_units[0]),
code_units[Size - 1] == u'\0' ? Size - 1 : Size)
{
}
bool operator==(Utf16View const& other) const { return m_code_units == other.m_code_units; }
enum class AllowInvalidCodeUnits {

View file

@ -89,6 +89,36 @@ TEST_CASE(decode_utf16)
EXPECT_EQ(i, expected.size());
}
TEST_CASE(utf16_literal)
{
{
Utf16View view { u"" };
EXPECT(view.validate());
EXPECT_EQ(view.length_in_code_units(), 0u);
}
{
Utf16View view { u"a" };
EXPECT(view.validate());
EXPECT_EQ(view.length_in_code_units(), 1u);
EXPECT_EQ(view.code_unit_at(0), 0x61u);
}
{
Utf16View view { u"abc" };
EXPECT(view.validate());
EXPECT_EQ(view.length_in_code_units(), 3u);
EXPECT_EQ(view.code_unit_at(0), 0x61u);
EXPECT_EQ(view.code_unit_at(1), 0x62u);
EXPECT_EQ(view.code_unit_at(2), 0x63u);
}
{
Utf16View view { u"🙃" };
EXPECT(view.validate());
EXPECT_EQ(view.length_in_code_units(), 2u);
EXPECT_EQ(view.code_unit_at(0), 0xd83du);
EXPECT_EQ(view.code_unit_at(1), 0xde43u);
}
}
TEST_CASE(iterate_utf16)
{
auto string = MUST(AK::utf8_to_utf16("Привет 😀"sv));