Skip to content

Commit

Permalink
Remove unnecessary check from size_bytes() (#1105)
Browse files Browse the repository at this point in the history
`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
  • Loading branch information
dmitrykobets-msft committed May 9, 2023
1 parent 1d03658 commit 9face82
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 17 deletions.
6 changes: 1 addition & 5 deletions include/gsl/span
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

Expand Down
12 changes: 0 additions & 12 deletions tests/span_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<const int> s = a;
Expand All @@ -1147,12 +1141,6 @@ TEST(span_test, as_bytes)
EXPECT_TRUE(static_cast<const void*>(bs.data()) == static_cast<const void*>(s.data()));
EXPECT_TRUE(bs.size() == s.size_bytes());
}

int b[5] = {1, 2, 3, 4, 5};
{
span<int> sp(std::begin(b), static_cast<size_t>(-2));
EXPECT_DEATH((void) sp.size_bytes(), expected);
}
}

TEST(span_test, as_writable_bytes)
Expand Down

0 comments on commit 9face82

Please sign in to comment.