Skip to content

Commit 7dc8f4e

Browse files

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

absl/strings/string_view.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@
3434
#include <iosfwd>
3535
#include <iterator>
3636
#include <limits>
37+
#include <memory>
3738
#include <string>
39+
#include <type_traits>
3840

3941
#include "absl/base/attributes.h"
4042
#include "absl/base/nullability.h"
@@ -208,6 +210,16 @@ class ABSL_ATTRIBUTE_VIEW string_view {
208210
ABSL_ASSERT(data != nullptr || len == 0);
209211
}
210212

213+
#if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
214+
template <std::contiguous_iterator It, std::sized_sentinel_for<It> End>
215+
requires(std::is_same_v<std::iter_value_t<It>, value_type> &&
216+
!std::is_convertible_v<End, size_type>)
217+
constexpr string_view(It begin, End end)
218+
: ptr_(std::to_address(begin)), length_(end - begin) {
219+
ABSL_HARDENING_ASSERT(end >= begin);
220+
}
221+
#endif // ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
222+
211223
constexpr string_view(const string_view&) noexcept = default;
212224
string_view& operator=(const string_view&) noexcept = default;
213225

absl/strings/string_view_test.cc

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
#include <stdlib.h>
1818

19+
#include <array>
1920
#include <cstddef>
2021
#include <cstdlib>
2122
#include <cstring>
@@ -131,6 +132,23 @@ TEST(StringViewTest, Ctor) {
131132
EXPECT_EQ(8u, s31.length());
132133
}
133134

135+
#if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
136+
{
137+
// Iterator constructor
138+
std::string str = "hello";
139+
absl::string_view s1(str.begin(), str.end());
140+
EXPECT_EQ(s1, "hello");
141+
142+
std::array<char, 3> arr = { '1', '2', '3' };
143+
absl::string_view s2(arr.begin(), arr.end());
144+
EXPECT_EQ(s2, "123");
145+
146+
const char carr[] = "carr";
147+
absl::string_view s3(carr, carr + strlen(carr));
148+
EXPECT_EQ(s3, "carr");
149+
}
150+
#endif // ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
151+
134152
{
135153
using mstring =
136154
std::basic_string<char, std::char_traits<char>, Mallocator<char>>;
@@ -1154,6 +1172,18 @@ TEST(StringViewTest, ConstexprCompiles) {
11541172

11551173
constexpr size_t sp_npos = sp.npos;
11561174
EXPECT_EQ(sp_npos, static_cast<size_t>(-1));
1175+
1176+
#if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
1177+
{
1178+
static constexpr std::array<char, 3> arr = { '1', '2', '3' };
1179+
constexpr absl::string_view s2(arr.begin(), arr.end());
1180+
EXPECT_EQ(s2, "123");
1181+
1182+
static constexpr char carr[] = "carr";
1183+
constexpr absl::string_view s3(carr, carr + 4);
1184+
EXPECT_EQ(s3, "carr");
1185+
}
1186+
#endif // ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
11571187
}
11581188

11591189
constexpr char ConstexprMethodsHelper() {

0 commit comments

Comments
 (0)