Add clear() method for InlinedVector<>.

pull/14146/head
Mark D. Roth 7 years ago
parent ac0808b107
commit 19688bf7a8
  1. 33
      src/core/lib/gprpp/inlined_vector.h
  2. 22
      test/core/gprpp/inlined_vector_test.cc

@ -46,18 +46,7 @@ template <typename T, size_t N>
class InlinedVector {
public:
InlinedVector() {}
~InlinedVector() {
for (size_t i = 0; i < size_ && i < N; ++i) {
T& value = *reinterpret_cast<T*>(inline_ + i);
value.~T();
}
if (size_ > N) { // Avoid subtracting two signed values.
for (size_t i = 0; i < size_ - N; ++i) {
dynamic_[i].~T();
}
}
gpr_free(dynamic_);
}
~InlinedVector() { destroy_elements(); }
// For now, we do not support copying.
InlinedVector(const InlinedVector&) = delete;
@ -100,7 +89,27 @@ class InlinedVector {
size_t size() const { return size_; }
void clear() {
destroy_elements();
dynamic_ = nullptr;
size_ = 0;
dynamic_capacity_ = 0;
}
private:
void destroy_elements() {
for (size_t i = 0; i < size_ && i < N; ++i) {
T& value = *reinterpret_cast<T*>(inline_ + i);
value.~T();
}
if (size_ > N) { // Avoid subtracting two signed values.
for (size_t i = 0; i < size_ - N; ++i) {
dynamic_[i].~T();
}
}
gpr_free(dynamic_);
}
typename std::aligned_storage<sizeof(T)>::type inline_[N];
T* dynamic_ = nullptr;
size_t size_ = 0;

@ -64,6 +64,28 @@ TEST(InlinedVectorTest, EmplaceBack) {
EXPECT_EQ(3, *v[0]);
}
TEST(InlinedVectorTest, ClearAndRepopulate) {
const int kNumElements = 10;
InlinedVector<int, 5> v;
EXPECT_EQ(0, v.size());
for (int i = 0; i < kNumElements; ++i) {
v.push_back(i);
EXPECT_EQ(i + 1, v.size());
}
for (int i = 0; i < kNumElements; ++i) {
EXPECT_EQ(i, v[i]);
}
v.clear();
EXPECT_EQ(0, v.size());
for (int i = 0; i < kNumElements; ++i) {
v.push_back(kNumElements + i);
EXPECT_EQ(i + 1, v.size());
}
for (int i = 0; i < kNumElements; ++i) {
EXPECT_EQ(kNumElements + i, v[i]);
}
}
} // namespace testing
} // namespace grpc_core

Loading…
Cancel
Save