Skip to content

Commit c46ba7e

Browse files
trflynn89awesomekling
authored andcommitted
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.
1 parent e163455 commit c46ba7e

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

AK/Utf16View.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,14 @@ class Utf16View {
7171
{
7272
}
7373

74+
template<size_t Size>
75+
Utf16View(char16_t const (&code_units)[Size])
76+
: m_code_units(
77+
reinterpret_cast<u16 const*>(&code_units[0]),
78+
code_units[Size - 1] == u'\0' ? Size - 1 : Size)
79+
{
80+
}
81+
7482
bool operator==(Utf16View const& other) const { return m_code_units == other.m_code_units; }
7583

7684
enum class AllowInvalidCodeUnits {

Tests/AK/TestUtf16.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,36 @@ TEST_CASE(decode_utf16)
8989
EXPECT_EQ(i, expected.size());
9090
}
9191

92+
TEST_CASE(utf16_literal)
93+
{
94+
{
95+
Utf16View view { u"" };
96+
EXPECT(view.validate());
97+
EXPECT_EQ(view.length_in_code_units(), 0u);
98+
}
99+
{
100+
Utf16View view { u"a" };
101+
EXPECT(view.validate());
102+
EXPECT_EQ(view.length_in_code_units(), 1u);
103+
EXPECT_EQ(view.code_unit_at(0), 0x61u);
104+
}
105+
{
106+
Utf16View view { u"abc" };
107+
EXPECT(view.validate());
108+
EXPECT_EQ(view.length_in_code_units(), 3u);
109+
EXPECT_EQ(view.code_unit_at(0), 0x61u);
110+
EXPECT_EQ(view.code_unit_at(1), 0x62u);
111+
EXPECT_EQ(view.code_unit_at(2), 0x63u);
112+
}
113+
{
114+
Utf16View view { u"🙃" };
115+
EXPECT(view.validate());
116+
EXPECT_EQ(view.length_in_code_units(), 2u);
117+
EXPECT_EQ(view.code_unit_at(0), 0xd83du);
118+
EXPECT_EQ(view.code_unit_at(1), 0xde43u);
119+
}
120+
}
121+
92122
TEST_CASE(iterate_utf16)
93123
{
94124
auto string = MUST(AK::utf8_to_utf16("Привет 😀"sv));

0 commit comments

Comments
 (0)