about summary refs log tree commit diff
path: root/absl/strings
diff options
context:
space:
mode:
Diffstat (limited to 'absl/strings')
-rw-r--r--absl/strings/string_view.h12
-rw-r--r--absl/strings/string_view_test.cc23
2 files changed, 32 insertions, 3 deletions
diff --git a/absl/strings/string_view.h b/absl/strings/string_view.h
index 01965b0eb63f..418dbc809680 100644
--- a/absl/strings/string_view.h
+++ b/absl/strings/string_view.h
@@ -282,7 +282,9 @@ class string_view {
   //
   // Returns the ith element of the `string_view` using the array operator.
   // Note that this operator does not perform any bounds checking.
-  constexpr const_reference operator[](size_type i) const { return ptr_[i]; }
+  constexpr const_reference operator[](size_type i) const {
+    return ABSL_ASSERT(i < size()), ptr_[i];
+  }
 
   // string_view::at()
   //
@@ -300,12 +302,16 @@ class string_view {
   // string_view::front()
   //
   // Returns the first element of a `string_view`.
-  constexpr const_reference front() const { return ptr_[0]; }
+  constexpr const_reference front() const {
+    return ABSL_ASSERT(!empty()), ptr_[0];
+  }
 
   // string_view::back()
   //
   // Returns the last element of a `string_view`.
-  constexpr const_reference back() const { return ptr_[size() - 1]; }
+  constexpr const_reference back() const {
+    return ABSL_ASSERT(!empty()), ptr_[size() - 1];
+  }
 
   // string_view::data()
   //
diff --git a/absl/strings/string_view_test.cc b/absl/strings/string_view_test.cc
index c4fbd16c201a..7b1d56fac762 100644
--- a/absl/strings/string_view_test.cc
+++ b/absl/strings/string_view_test.cc
@@ -818,6 +818,18 @@ TEST(StringViewTest, FrontBackSingleChar) {
   EXPECT_EQ(&c, &csp.back());
 }
 
+TEST(StringViewTest, FrontBackEmpty) {
+#ifndef ABSL_USES_STD_STRING_VIEW
+#ifndef NDEBUG
+  // Abseil's string_view implementation has debug assertions that check that
+  // front() and back() are not called on an empty string_view.
+  absl::string_view sv;
+  ABSL_EXPECT_DEATH_IF_SUPPORTED(sv.front(), "");
+  ABSL_EXPECT_DEATH_IF_SUPPORTED(sv.back(), "");
+#endif
+#endif
+}
+
 // `std::string_view::string_view(const char*)` calls
 // `std::char_traits<char>::length(const char*)` to get the string length. In
 // libc++, it doesn't allow `nullptr` in the constexpr context, with the error
@@ -1108,6 +1120,17 @@ TEST(StringViewTest, Noexcept) {
   EXPECT_TRUE(noexcept(sp.find_last_not_of('f')));
 }
 
+TEST(StringViewTest, BoundsCheck) {
+#ifndef ABSL_USES_STD_STRING_VIEW
+#ifndef NDEBUG
+  // Abseil's string_view implementation has bounds-checking in debug mode.
+  absl::string_view h = "hello";
+  ABSL_EXPECT_DEATH_IF_SUPPORTED(h[5], "");
+  ABSL_EXPECT_DEATH_IF_SUPPORTED(h[-1], "");
+#endif
+#endif
+}
+
 TEST(ComparisonOpsTest, StringCompareNotAmbiguous) {
   EXPECT_EQ("hello", std::string("hello"));
   EXPECT_LT("hello", std::string("world"));