[libcxx-commits] [PATCH] D108827: [libc++] Add an assertion in the subrange constructors with a size hint

Louis Dionne via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Fri Aug 27 09:14:15 PDT 2021


ldionne created this revision.
ldionne added a reviewer: zoecarver.
ldionne requested review of this revision.
Herald added a project: libc++.
Herald added a subscriber: libcxx-commits.
Herald added a reviewer: libc++.

Those constructors are very easy to misuse -- one could easily think that
the size passed to the constructor is the size of the range to exhibit
from the subrange. Instead, it's a size hint and it's UB to get it wrong.
Hence, when it's cheap to compute the real size of the range, it's cheap
to make sure that the user didn't get it wrong.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D108827

Files:
  libcxx/include/__ranges/subrange.h


Index: libcxx/include/__ranges/subrange.h
===================================================================
--- libcxx/include/__ranges/subrange.h
+++ libcxx/include/__ranges/subrange.h
@@ -118,7 +118,11 @@
     constexpr subrange(__convertible_to_non_slicing<_Iter> auto __iter, _Sent __sent,
                        make_unsigned_t<iter_difference_t<_Iter>> __n)
       requires (_Kind == subrange_kind::sized)
-      : _Base(_VSTD::move(__iter), __sent, __n) { }
+      : _Base(_VSTD::move(__iter), __sent, __n)
+    {
+      if constexpr (sized_sentinel_for<_Sent, decltype(__iter)>)
+        _LIBCPP_ASSERT(ranges::distance(this->__begin_, this->__end_) == __n, "std::ranges::subrange was passed an invalid size hint");
+    }
 
     template<__different_from<subrange> _Range>
       requires borrowed_range<_Range> &&


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D108827.369120.patch
Type: text/x-patch
Size: 827 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libcxx-commits/attachments/20210827/a8fcce8c/attachment.bin>


More information about the libcxx-commits mailing list