From 9face82309ae633ad23d28daf30737f085d1cd4c Mon Sep 17 00:00:00 2001 From: Dmitry Kobets <89153909+dmitrykobets-msft@users.noreply.github.com> Date: Tue, 9 May 2023 09:05:26 -0700 Subject: [PATCH] Remove unnecessary check from size_bytes() (#1105) `size_bytes()` returns the span's size in bytes. Assuming the span was constructed with an accurate size parameter, the check `size() < dynamic_extent / sizeof(element_type)` isn't required, since `size_t(-1)` (which is `dynamic_extent`) represents the size of the address space, so the number of bytes will never exceed it and in practice won't even come close. Otherwise, it is not actually feasible to detect cases when the size parameter does not correspond to the dimensions of the underlying data pointer. In these cases, the relationship `size() < dynamic_extent / sizeof(element_type)` is simply one of many ways in which the `size()` could be incorrect, and serves no necessary purpose. Resolves #1012 --- include/gsl/span | 6 +----- tests/span_tests.cpp | 12 ------------ 2 files changed, 1 insertion(+), 17 deletions(-) diff --git a/include/gsl/span b/include/gsl/span index 25e244f..f61fd11 100644 --- a/include/gsl/span +++ b/include/gsl/span @@ -624,11 +624,7 @@ public: // [span.obs], span observers constexpr size_type size() const noexcept { return storage_.size(); } - constexpr size_type size_bytes() const noexcept - { - Expects(size() < dynamic_extent / sizeof(element_type)); - return size() * sizeof(element_type); - } + constexpr size_type size_bytes() const noexcept { return size() * sizeof(element_type); } constexpr bool empty() const noexcept { return size() == 0; } diff --git a/tests/span_tests.cpp b/tests/span_tests.cpp index 5a9fc6e..44ae205 100644 --- a/tests/span_tests.cpp +++ b/tests/span_tests.cpp @@ -1116,12 +1116,6 @@ TEST(span_test, rbegin_rend) TEST(span_test, as_bytes) { - const auto terminateHandler = std::set_terminate([] { - std::cerr << "Expected Death. as_bytes"; - std::abort(); - }); - const auto expected = GetExpectedDeathString(terminateHandler); - int a[] = {1, 2, 3, 4}; { const span s = a; @@ -1147,12 +1141,6 @@ TEST(span_test, as_bytes) EXPECT_TRUE(static_cast(bs.data()) == static_cast(s.data())); EXPECT_TRUE(bs.size() == s.size_bytes()); } - - int b[5] = {1, 2, 3, 4, 5}; - { - span sp(std::begin(b), static_cast(-2)); - EXPECT_DEATH((void) sp.size_bytes(), expected); - } } TEST(span_test, as_writable_bytes)