From af7453a67363bb4fbfc94d889e16cc595940d2a1 Mon Sep 17 00:00:00 2001 From: Igor Canadi Date: Thu, 8 May 2014 13:50:49 -0700 Subject: [PATCH] autovector::resize Summary: Resize the autovector! Test Plan: test Reviewers: sdong Reviewed By: sdong CC: leveldb Differential Revision: https://reviews.facebook.net/D18543 --- util/autovector.h | 14 +++++++++++++- util/autovector_test.cc | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/util/autovector.h b/util/autovector.h index 212073e78..b57cedfc1 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 88744cf17..25ebaa24b 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) {