diff --git a/libstdc++-v3/include/bits/ranges_base.h b/libstdc++-v3/include/bits/ranges_base.h index 08e99ebc5d3..3c5f4b1790a 100644 --- a/libstdc++-v3/include/bits/ranges_base.h +++ b/libstdc++-v3/include/bits/ranges_base.h @@ -756,20 +756,23 @@ namespace ranges { const auto __diff = __bound - __it; - // n and bound must not lead in opposite directions: - __glibcxx_assert(__n == 0 || __diff == 0 || (__n < 0 == __diff < 0)); - const auto __absdiff = __diff < 0 ? -__diff : __diff; - const auto __absn = __n < 0 ? -__n : __n;; - if (__absn >= __absdiff) + if (__diff == 0) + return __n; + else if (__diff > 0 ? __n >= __diff : __n <= __diff) { (*this)(__it, __bound); return __n - __diff; } - else + else if (__n != 0) [[likely]] { + // n and bound must not lead in opposite directions: + __glibcxx_assert(__n < 0 == __diff < 0); + (*this)(__it, __n); return 0; } + else + return 0; } else if (__it == __bound || __n == 0) return __n; diff --git a/libstdc++-v3/testsuite/24_iterators/range_operations/advance_overflow.cc b/libstdc++-v3/testsuite/24_iterators/range_operations/advance_overflow.cc new file mode 100644 index 00000000000..0fadcd6e99a --- /dev/null +++ b/libstdc++-v3/testsuite/24_iterators/range_operations/advance_overflow.cc @@ -0,0 +1,37 @@ +// { dg-options "-std=gnu++20" } +// { dg-do compile { target c++20 } } + +// Public domain testcase from Casey Carter, send to LWG list on 2021-07-24. +// +// Here's a compile-only test case for which n is INT_MIN, which will overflow +// if simply negated to get |n|: https://godbolt.org/z/M7Wz1nW58. + +#include +#include +#include + +struct I { + using difference_type = int; + using value_type = int; + + int x; + + constexpr int operator*() const { return x; } + constexpr I& operator++() { ++x; return *this; } + constexpr I operator++(int) { ++x; return {x - 1}; } + constexpr bool operator==(const I&) const = default; + + constexpr int operator-(const I& that) const { return x - that.x; } + + constexpr I& operator--() { --x; return *this; } + constexpr I operator--(int) { --x; return {x - 1}; } +}; +static_assert(std::bidirectional_iterator); +static_assert(std::sized_sentinel_for); + +constexpr bool test() { + using L = std::numeric_limits; + I i{-2}; + return std::ranges::advance(i, L::min(), I{-4}) == L::min() + 2; +} +static_assert(test());