[libcxx-commits] [PATCH] D145981: [libc++] Assert that lengths fit in difference_type

David Benjamin via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Mon Mar 13 12:45:44 PDT 2023


davidben created this revision.
davidben added a reviewer: rsmith.
Herald added a project: All.
davidben requested review of this revision.
Herald added a project: libc++.
Herald added a subscriber: libcxx-commits.
Herald added a reviewer: libc++.

This can help flag accidentally passing in negative values into the  `string_view` constructor. This aligns with a similar check in `absl::string_view`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D145981

Files:
  libcxx/include/string_view
  libcxx/test/libcxx/strings/string.view/assert.ctor.length.pass.cpp


Index: libcxx/test/libcxx/strings/string.view/assert.ctor.length.pass.cpp
===================================================================
--- /dev/null
+++ libcxx/test/libcxx/strings/string.view/assert.ctor.length.pass.cpp
@@ -0,0 +1,25 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// REQUIRES: has-unix-headers
+// UNSUPPORTED: c++11, c++14
+
+// UNSUPPORTED: c++03
+// XFAIL: use_system_cxx_lib && target={{.+}}-apple-macosx{{10.9|10.10|10.11|10.12|10.13|10.14|10.15|11.0|12.0}}
+// ADDITIONAL_COMPILE_FLAGS: -D_LIBCPP_ENABLE_ASSERTIONS=1
+
+#include <string_view>
+
+#include "check_assertion.h"
+
+int main(int, char**) {
+  char c = 0;
+  TEST_LIBCPP_ASSERT_FAILURE(
+      std::string_view(&c, -1), "string_view::string_view(_CharT *, size_t): length does not fit in difference_type");
+  return 0;
+}
Index: libcxx/include/string_view
===================================================================
--- libcxx/include/string_view
+++ libcxx/include/string_view
@@ -304,6 +304,7 @@
     basic_string_view(const _CharT* __s, size_type __len) _NOEXCEPT
         : __data_(__s), __size_(__len)
     {
+    _LIBCPP_ASSERT(__len <= static_cast<size_type>(numeric_limits<difference_type>::max()), "string_view::string_view(_CharT *, size_t): length does not fit in difference_type");
 #if _LIBCPP_STD_VER >= 14
     _LIBCPP_ASSERT(__len == 0 || __s != nullptr, "string_view::string_view(_CharT *, size_t): received nullptr");
 #endif


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D145981.504811.patch
Type: text/x-patch
Size: 1779 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libcxx-commits/attachments/20230313/52f93982/attachment.bin>


More information about the libcxx-commits mailing list