Skip to content

Commit

Permalink
pw_containers: pw::Vector::resize takes size_t
Browse files Browse the repository at this point in the history
For consistency with other container types, pw::Vector returns size_t
from size(), max_size() and capacity() member functions. The resize()
member functions take unsigned short new_size arguments. When we turn on
-Wconversion, code that resizes Vectors based on their current size, max
size or capacity becomes complex.

This changes the the resize calls to take a size_t with a debug
assertion that the size that's passed fits into an unsigned short.
Compilers seem to optimize away those assertions if resize() is called
with an unsigned short since they can statically determine that the
assertion will never fire.

Bug: b/259746255
Change-Id: I122f4e20a7eaed25f83621cb2e0a2c12b84e9094
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/146792
Commit-Queue: Ian McKellar <[email protected]>
Reviewed-by: Keir Mierle <[email protected]>
  • Loading branch information
ianloic authored and CQ Bot Account committed May 15, 2023
1 parent 45c67ca commit a50ae03
Showing 1 changed file with 7 additions and 8 deletions.
15 changes: 7 additions & 8 deletions pw_containers/public/pw_containers/vector.h
Original file line number Diff line number Diff line change
Expand Up @@ -358,9 +358,9 @@ class Vector<T, vector_impl::kGeneric>

void pop_back();

void resize(size_type new_size) { resize(new_size, T()); }
void resize(size_t new_size) { resize(new_size, T()); }

void resize(size_type new_size, const T& value);
void resize(size_t new_size, const T& value);

protected:
// Vectors without an explicit size cannot be constructed directly. Instead,
Expand Down Expand Up @@ -476,13 +476,12 @@ void Vector<T, vector_impl::kGeneric>::pop_back() {
}

template <typename T>
void Vector<T, vector_impl::kGeneric>::resize(size_type new_size,
const T& value) {
void Vector<T, vector_impl::kGeneric>::resize(size_t new_size, const T& value) {
PW_DASSERT(new_size <= std::numeric_limits<size_type>::max());
if (size() < new_size) {
// Note: max_size() & size() always return a value that fits in size_type.
Append(std::min(static_cast<size_type>(max_size()), new_size) -
static_cast<size_type>(size()),
value);
size_type count =
static_cast<size_type>(std::min(max_size(), new_size) - size());
Append(count, value);
} else {
while (size() > new_size) {
pop_back();
Expand Down

0 comments on commit a50ae03

Please sign in to comment.