diff options
author | Duncan P. N. Exon Smith <dexonsmith@apple.com> | 2021-12-07 16:20:18 -0800 |
---|---|---|
committer | Duncan P. N. Exon Smith <dexonsmith@apple.com> | 2021-12-08 13:57:48 -0800 |
commit | ca451d3fa40ebbd35c702ba698e9e5f29e8ed69b (patch) | |
tree | d51b6a792bb057aef2a3ff2f953636de08ea559c /llvm/unittests/ADT/SmallVectorTest.cpp | |
parent | 1225c8a06103e029a4b2ebb782a175ab1e011cbe (diff) | |
download | llvm-ca451d3fa40ebbd35c702ba698e9e5f29e8ed69b.zip llvm-ca451d3fa40ebbd35c702ba698e9e5f29e8ed69b.tar.gz llvm-ca451d3fa40ebbd35c702ba698e9e5f29e8ed69b.tar.bz2 |
ADT: Add SmallVectorImpl::truncate() to replace uses of set_size()
Add `SmallVectorImpl::truncate()`, a variant of `resize()` that cannot
increase the size.
- Compared to `resize()`, this has no code path for growing the
allocation and can be better optimized.
- Compared to `set_size()`, this formally calls destructors, and does
not skip any constructors.
- Compared to `pop_back_n()`, this takes the new desired size, which in
many contexts is more intuitive than the number of elements to remove.
The immediate motivation is to pair this with `resize_for_overwrite()`
to remove uses of `set_size()`, which can then be made private.
Differential Revision: https://reviews.llvm.org/D115383
Diffstat (limited to 'llvm/unittests/ADT/SmallVectorTest.cpp')
-rw-r--r-- | llvm/unittests/ADT/SmallVectorTest.cpp | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/llvm/unittests/ADT/SmallVectorTest.cpp b/llvm/unittests/ADT/SmallVectorTest.cpp index 06b98ef..3fbea52 100644 --- a/llvm/unittests/ADT/SmallVectorTest.cpp +++ b/llvm/unittests/ADT/SmallVectorTest.cpp @@ -309,6 +309,32 @@ TYPED_TEST(SmallVectorTest, ResizeShrinkTest) { EXPECT_EQ(5, Constructable::getNumDestructorCalls()); } +// Truncate test. +TYPED_TEST(SmallVectorTest, TruncateTest) { + SCOPED_TRACE("TruncateTest"); + + this->theVector.reserve(3); + this->makeSequence(this->theVector, 1, 3); + this->theVector.truncate(1); + + this->assertValuesInOrder(this->theVector, 1u, 1); + EXPECT_EQ(6, Constructable::getNumConstructorCalls()); + EXPECT_EQ(5, Constructable::getNumDestructorCalls()); + +#if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST + EXPECT_DEATH(this->theVector.truncate(2), "Cannot increase size"); +#endif + this->theVector.truncate(1); + this->assertValuesInOrder(this->theVector, 1u, 1); + EXPECT_EQ(6, Constructable::getNumConstructorCalls()); + EXPECT_EQ(5, Constructable::getNumDestructorCalls()); + + this->theVector.truncate(0); + this->assertEmpty(this->theVector); + EXPECT_EQ(6, Constructable::getNumConstructorCalls()); + EXPECT_EQ(6, Constructable::getNumDestructorCalls()); +} + // Resize bigger test. TYPED_TEST(SmallVectorTest, ResizeGrowTest) { SCOPED_TRACE("ResizeGrowTest"); |