Skip to content

Commit

Permalink
Add MakeStringViewWithNulChars().
Browse files Browse the repository at this point in the history
This new function can be used to construct an instance of a
string view from a string literal that contains NUL characters
internally.

Change-Id: I35555934922c00684263d143bbd63a5b08279c8e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5691499
Reviewed-by: danakj <[email protected]>
Commit-Queue: Patrick Monette <[email protected]>
Cr-Commit-Position: refs/heads/main@{#1326367}
  • Loading branch information
plmonette-zz authored and Chromium LUCI CQ committed Jul 11, 2024
1 parent c678392 commit b612c20
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
10 changes: 10 additions & 0 deletions base/strings/string_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,16 @@ BASE_EXPORT std::u16string ReplaceStringPlaceholders(
const std::u16string& a,
size_t* offset);

// Helper function for creating a std::string_view from a string literal that
// preserves internal NUL characters.
template <class CharT, size_t N>
std::basic_string_view<CharT> MakeStringViewWithNulChars(
const CharT (&lit LIFETIME_BOUND)[N])
ENABLE_IF_ATTR(lit[N - 1u] == CharT{0},
"requires string literal as input") {
return std::basic_string_view<CharT>(lit, N - 1u);
}

} // namespace base

#if BUILDFLAG(IS_WIN)
Expand Down
28 changes: 28 additions & 0 deletions base/strings/string_util_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1571,6 +1571,34 @@ TEST(StringUtilTest, IsUnicodeWhitespace) {
EXPECT_TRUE(IsUnicodeWhitespace(L'\n'));
}

// Tests that MakeStringViewWithNulChars preserves internal NUL characters.
TEST(StringUtilTest, MakeStringViewWithNulChars) {
{
const char kTestString[] = "abd\0def";
auto s = MakeStringViewWithNulChars(kTestString);
EXPECT_EQ(s.size(), 7u);
EXPECT_EQ(base::span(s), base::span_from_cstring(kTestString));
}
{
const wchar_t kTestString[] = L"abd\0def";
auto s = MakeStringViewWithNulChars(kTestString);
EXPECT_EQ(s.size(), 7u);
ASSERT_TRUE(base::span(s) == base::span_from_cstring(kTestString));
}
{
const char16_t kTestString[] = u"abd\0def";
auto s = MakeStringViewWithNulChars(kTestString);
EXPECT_EQ(s.size(), 7u);
EXPECT_TRUE(base::span(s) == base::span_from_cstring(kTestString));
}
{
const char32_t kTestString[] = U"abd\0def";
auto s = MakeStringViewWithNulChars(kTestString);
EXPECT_EQ(s.size(), 7u);
EXPECT_TRUE(base::span(s) == base::span_from_cstring(kTestString));
}
}

class WriteIntoTest : public testing::Test {
protected:
static void WritesCorrectly(size_t num_chars) {
Expand Down

0 comments on commit b612c20

Please sign in to comment.