[libcxx-commits] [libcxx] [libc++] Fix search_n with an invalid count (PR #223747)
A. Jiang via libcxx-commits
libcxx-commits at lists.llvm.org
Tue Oct 13 02:02:31 PDT 2026
================
@@ -79,14 +80,19 @@ __find_longest_suffix(_RAIter __first, _RAIter __last, const _ValueT& __value, _
template <class _AlgPolicy, class _Pred, class _Iter, class _SizeT, class _Type, class _Proj, class _DiffT>
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 std::pair<_Iter, _Iter> __search_n_random_access_impl(
_Iter __first, _SizeT __count_in, const _Type& __value, _Pred& __pred, _Proj& __proj, _DiffT __size) {
- auto __last = __first + __size;
- auto __count = static_cast<_DiffT>(__count_in);
-
- if (__count == 0)
+ // Trivially match if count is non-positive. This must be checked before we perform arithmetic on the count.
+ if (__count_in <= 0)
return std::make_pair(__first, __first);
- if (__size < __count)
+
+ auto __last = __first + __size;
+
+ // If count is larger than the sequence size, no match is possible. Compare as unsigned to prevent
+ // truncation between _DiffT and _SizeT.
+ if (std::__to_unsigned_like(__size) < std::__to_unsigned_like(__count_in))
----------------
frederick-vs-ja wrote:
IIUC we've obtained an integer per the `__convert_to_integral` call in `search_n`, so it should be fine to use `__to_unsigned_like` here.
Also, `_DiffT` is the difference type of the iterator, so `__to_unsigned_like` is also fine for it.
https://github.com/llvm/llvm-project/pull/223747
More information about the libcxx-commits
mailing list