diff --git a/util/autovector.h b/util/autovector.h index 212073e78c..b57cedfc1b 100644 --- a/util/autovector.h +++ b/util/autovector.h @@ -24,7 +24,7 @@ class autovector : public std::vector {}; // full-fledged generic container. // // Currently we don't support: -// * reserve()/shrink_to_fit()/resize() +// * reserve()/shrink_to_fit() // If used correctly, in most cases, people should not touch the // underlying vector at all. // * random insert()/erase(), please only use push_back()/pop_back(). @@ -176,6 +176,18 @@ class autovector { size_type size() const { return num_stack_items_ + vect_.size(); } + // resize does not guarantee anything about the contents of the newly + // available elements + void resize(size_type n) { + if (n > kSize) { + vect_.resize(n - kSize); + num_stack_items_ = kSize; + } else { + vect_.clear(); + num_stack_items_ = n; + } + } + bool empty() const { return size() == 0; } // will not check boundry diff --git a/util/autovector_test.cc b/util/autovector_test.cc index 88744cf170..25ebaa24b5 100644 --- a/util/autovector_test.cc +++ b/util/autovector_test.cc @@ -70,6 +70,28 @@ TEST(AutoVectorTest, EmplaceBack) { ASSERT_TRUE(!vec.only_in_stack()); } +TEST(AutoVectorTest, Resize) { + autovector vec; + + vec.resize(kSize); + ASSERT_TRUE(vec.only_in_stack()); + for (size_t i = 0; i < kSize; ++i) { + vec[i] = i; + } + + vec.resize(kSize * 2); + ASSERT_TRUE(!vec.only_in_stack()); + for (size_t i = 0; i < kSize; ++i) { + ASSERT_EQ(vec[i], i); + } + for (size_t i = 0; i < kSize; ++i) { + vec[i + kSize] = i; + } + + vec.resize(1); + ASSERT_EQ(1U, vec.size()); +} + namespace { void AssertEqual( const autovector& a, const autovector& b) {