| 1 |
//===----------------------------------------------------------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
|
| 9 |
// <string> |
| 10 |
|
| 11 |
// const_reference operator[](size_type pos) const; // constexpr since C++20 |
| 12 |
// reference operator[](size_type pos); // constexpr since C++20 |
| 13 |
|
| 14 |
#include <string> |
| 15 |
#include <cassert> |
| 16 |
|
| 17 |
#include "test_macros.h" |
| 18 |
#include "min_allocator.h" |
| 19 |
|
| 20 |
template <class S> |
| 21 |
TEST_CONSTEXPR_CXX20 void test_string() { |
| 22 |
S s("0123456789"); |
| 23 |
const S& cs = s; |
| 24 |
ASSERT_SAME_TYPE(decltype(s[0]), typename S::reference); |
| 25 |
ASSERT_SAME_TYPE(decltype(cs[0]), typename S::const_reference); |
| 26 |
LIBCPP_ASSERT_NOEXCEPT(s[0]); |
| 27 |
LIBCPP_ASSERT_NOEXCEPT(cs[0]); |
| 28 |
for (typename S::size_type i = 0; i < cs.size(); ++i) { |
| 29 |
assert(s[i] == static_cast<char>('0' + i)); |
| 30 |
assert(cs[i] == s[i]); |
| 31 |
} |
| 32 |
assert(cs[cs.size()] == '\0'); |
| 33 |
const S s2 = S(); |
| 34 |
assert(s2[0] == '\0'); |
| 35 |
} |
| 36 |
|
| 37 |
// Same, but for the string that doesn't fit into SSO. |
| 38 |
template <class S> |
| 39 |
TEST_CONSTEXPR_CXX20 void test_string_long() { |
| 40 |
S s("0123456789012345678901234567890123456789"); |
| 41 |
const S& cs = s; |
| 42 |
ASSERT_SAME_TYPE(decltype(s[0]), typename S::reference); |
| 43 |
ASSERT_SAME_TYPE(decltype(cs[0]), typename S::const_reference); |
| 44 |
LIBCPP_ASSERT_NOEXCEPT(s[0]); |
| 45 |
LIBCPP_ASSERT_NOEXCEPT(cs[0]); |
| 46 |
for (typename S::size_type i = 0; i < cs.size(); ++i) { |
| 47 |
assert(s[i] == static_cast<char>('0' + (i % 10))); |
| 48 |
assert(cs[i] == s[i]); |
| 49 |
} |
| 50 |
assert(s[33] == static_cast<char>('0' + (33 % 10))); |
| 51 |
assert(cs[34] == s[34]); |
| 52 |
assert(cs[cs.size()] == '\0'); |
| 53 |
const S s2 = S(); |
| 54 |
assert(s2[0] == '\0'); |
| 55 |
} |
| 56 |
|
| 57 |
TEST_CONSTEXPR_CXX20 bool test() { |
| 58 |
test_string<std::string>(); |
| 59 |
#if TEST_STD_VER >= 11 |
| 60 |
test_string<std::basic_string<char, std::char_traits<char>, min_allocator<char>>>(); |
| 61 |
test_string_long<std::basic_string<char, std::char_traits<char>, min_allocator<char>>>(); |
| 62 |
#endif |
| 63 |
|
| 64 |
return true; |
| 65 |
} |
| 66 |
|
| 67 |
int main(int, char**) { |
| 68 |
test(); |
| 69 |
#if TEST_STD_VER > 17 |
| 70 |
static_assert(test()); |
| 71 |
#endif |
| 72 |
|
| 73 |
return 0; |
| 74 |
} |