pw_containers: pw::Vector::resize takes size_t
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 <ianloic@google.com>
Reviewed-by: Keir Mierle <keir@google.com>
diff --git a/pw_containers/public/pw_containers/vector.h b/pw_containers/public/pw_containers/vector.h
index 1acffff..e3cefbf 100644
--- a/pw_containers/public/pw_containers/vector.h
+++ b/pw_containers/public/pw_containers/vector.h
@@ -358,9 +358,9 @@
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,
@@ -476,13 +476,12 @@
}
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();