pw_containers: Add asserts
Check the index with PW_ASSERT in at() and PW_DASSERT in operator[].
Change-Id: Ib10883847224b652e7536adad68c79c5b049eab7
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/39380
Pigweed-Auto-Submit: Wyatt Hepler <hepler@google.com>
Reviewed-by: Armando Montanez <amontanez@google.com>
Commit-Queue: Wyatt Hepler <hepler@google.com>
diff --git a/pw_containers/BUILD.gn b/pw_containers/BUILD.gn
index bf839ea..d59ba21 100644
--- a/pw_containers/BUILD.gn
+++ b/pw_containers/BUILD.gn
@@ -37,6 +37,7 @@
pw_source_set("vector") {
public_configs = [ ":default_config" ]
+ public_deps = [ dir_pw_assert ]
public = [ "public/pw_containers/vector.h" ]
}
diff --git a/pw_containers/public/pw_containers/vector.h b/pw_containers/public/pw_containers/vector.h
index 3ab452b..b629aa4 100644
--- a/pw_containers/public/pw_containers/vector.h
+++ b/pw_containers/public/pw_containers/vector.h
@@ -23,6 +23,7 @@
#include <type_traits>
#include <utility>
+#include "pw_assert/assert.h"
#include "pw_polyfill/language_feature_macros.h"
namespace pw {
@@ -236,12 +237,23 @@
// Access
- // TODO(hepler): Add an assert for bounds checking in at.
- reference at(size_type index) { return data()[index]; }
- const_reference at(size_type index) const { return data()[index]; }
+ reference at(size_type index) {
+ PW_ASSERT(index < size());
+ return data()[index];
+ }
+ const_reference at(size_type index) const {
+ PW_ASSERT(index < size());
+ return data()[index];
+ }
- reference operator[](size_type index) { return data()[index]; }
- const_reference operator[](size_type index) const { return data()[index]; }
+ reference operator[](size_type index) {
+ PW_DASSERT(index < size());
+ return data()[index];
+ }
+ const_reference operator[](size_type index) const {
+ PW_DASSERT(index < size());
+ return data()[index];
+ }
reference front() { return data()[0]; }
const_reference front() const { return data()[0]; }
@@ -338,7 +350,8 @@
protected:
// Vectors without an explicit size cannot be constructed directly. Instead,
// the maximum size must be provided.
- explicit Vector(size_type max_size) noexcept : max_size_(max_size) {}
+ explicit constexpr Vector(size_type max_size) noexcept
+ : max_size_(max_size) {}
Vector(size_type max_size, size_type count, const T& value)
: Vector(max_size) {