diff --git a/gsl/gsl_util b/gsl/gsl_util index f0ac964..889414a 100644 --- a/gsl/gsl_util +++ b/gsl/gsl_util @@ -135,30 +135,30 @@ inline T narrow(U u) // at() - Bounds-checked way of accessing static arrays, std::array, std::vector // template -constexpr T& at(T (&arr)[N], size_t index) +constexpr T& at(T (&arr)[N], std::ptrdiff_t index) { - Expects(index < N); - return arr[index]; + Expects(index >= 0 && index < narrow_cast(N)); + return arr[static_cast(index)]; } template -constexpr T& at(std::array& arr, size_t index) +constexpr T& at(std::array& arr, std::ptrdiff_t index) { - Expects(index < N); - return arr[index]; + Expects(index >= 0 && index < narrow_cast(N)); + return arr[static_cast(index)]; } template -constexpr typename Cont::value_type& at(Cont& cont, size_t index) +constexpr typename Cont::value_type& at(Cont& cont, std::ptrdiff_t index) { - Expects(index < cont.size()); - return cont[index]; + Expects(index >= 0 && index < narrow_cast(cont.size())); + return cont[static_cast(index)]; } template -constexpr const T& at(std::initializer_list cont, size_t index) +constexpr const T& at(std::initializer_list cont, std::ptrdiff_t index) { - Expects(index < cont.size()); + Expects(index >= 0 && index < narrow_cast(cont.size())); return *(cont.begin() + index); } diff --git a/gsl/span b/gsl/span index cf90e86..07c59c5 100644 --- a/gsl/span +++ b/gsl/span @@ -627,7 +627,7 @@ as_writeable_bytes(span s) noexcept // Specialization of gsl::at for span template -constexpr ElementType& at(const span& s, size_t index) +constexpr ElementType& at(const span& s, std::ptrdiff_t index) { // No bounds checking here because it is done in span::operator[] called below return s[index]; diff --git a/tests/at_tests.cpp b/tests/at_tests.cpp index 008fddf..166eb9b 100644 --- a/tests/at_tests.cpp +++ b/tests/at_tests.cpp @@ -31,6 +31,7 @@ SUITE(at_tests) for (int i = 0; i < 4; ++i) CHECK(at(a, i) == i+1); + CHECK_THROW(at(a, -1), fail_fast); CHECK_THROW(at(a, 4), fail_fast); } @@ -41,6 +42,7 @@ SUITE(at_tests) for (int i = 0; i < 4; ++i) CHECK(at(a, i) == i+1); + CHECK_THROW(at(a, -1), fail_fast); CHECK_THROW(at(a, 4), fail_fast); } @@ -51,6 +53,7 @@ SUITE(at_tests) for (int i = 0; i < 4; ++i) CHECK(at(a, i) == i+1); + CHECK_THROW(at(a, -1), fail_fast); CHECK_THROW(at(a, 4), fail_fast); } @@ -61,6 +64,7 @@ SUITE(at_tests) for (int i = 0; i < 4; ++i) CHECK(at(a, i) == i+1); + CHECK_THROW(at(a, -1), fail_fast); CHECK_THROW(at(a, 4), fail_fast); } }