Skip to content

[libc++] Optimize string operator[] for known large inputs #69500

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions libcxx/include/string
Original file line number Diff line number Diff line change
Expand Up @@ -1198,11 +1198,17 @@ public:

_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 const_reference operator[](size_type __pos) const _NOEXCEPT {
_LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__pos <= size(), "string index out of bounds");
if (__builtin_constant_p(__pos) && !__fits_in_sso(__pos)) {
return *(__get_long_pointer() + __pos);
}
return *(data() + __pos);
}

_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 reference operator[](size_type __pos) _NOEXCEPT {
_LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__pos <= size(), "string index out of bounds");
if (__builtin_constant_p(__pos) && !__fits_in_sso(__pos)) {
return *(__get_long_pointer() + __pos);
}
return *(__get_pointer() + __pos);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,31 @@ TEST_CONSTEXPR_CXX20 void test_string() {
assert(s2[0] == '\0');
}

// Same, but for the string that doesn't fit into SSO.
template <class S>
TEST_CONSTEXPR_CXX20 void test_string_long() {
S s("0123456789012345678901234567890123456789");
const S& cs = s;
ASSERT_SAME_TYPE(decltype(s[0]), typename S::reference);
ASSERT_SAME_TYPE(decltype(cs[0]), typename S::const_reference);
LIBCPP_ASSERT_NOEXCEPT(s[0]);
LIBCPP_ASSERT_NOEXCEPT(cs[0]);
for (typename S::size_type i = 0; i < cs.size(); ++i) {
assert(s[i] == static_cast<char>('0' + (i % 10)));
assert(cs[i] == s[i]);
}
assert(s[33] == static_cast<char>('0' + (33 % 10)));
assert(cs[34] == s[34]);
assert(cs[cs.size()] == '\0');
const S s2 = S();
assert(s2[0] == '\0');
}

TEST_CONSTEXPR_CXX20 bool test() {
test_string<std::string>();
#if TEST_STD_VER >= 11
test_string<std::basic_string<char, std::char_traits<char>, min_allocator<char>>>();
test_string_long<std::basic_string<char, std::char_traits<char>, min_allocator<char>>>();
#endif

return true;
Expand Down