1 //===- llvm/unittest/ADT/StringMapMap.cpp - StringMap unit tests ----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/ADT/StringMap.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/Twine.h"
12 #include "llvm/Support/DataTypes.h"
13 #include "gtest/gtest.h"
20 static_assert(sizeof(StringMap
<uint32_t>) <
21 sizeof(StringMap
<uint32_t, MallocAllocator
&>),
22 "Ensure empty base optimization happens with default allocator");
25 class StringMapTest
: public testing::Test
{
27 StringMap
<uint32_t> testMap
;
29 static const char testKey
[];
30 static const uint32_t testValue
;
31 static const char *testKeyFirst
;
32 static size_t testKeyLength
;
33 static const std::string testKeyStr
;
35 void assertEmptyMap() {
37 EXPECT_EQ(0u, testMap
.size());
38 EXPECT_TRUE(testMap
.empty());
41 EXPECT_TRUE(testMap
.begin() == testMap
.end());
44 EXPECT_FALSE(testMap
.contains(testKey
));
45 EXPECT_EQ(0u, testMap
.count(testKey
));
46 EXPECT_EQ(0u, testMap
.count(StringRef(testKeyFirst
, testKeyLength
)));
47 EXPECT_EQ(0u, testMap
.count(testKeyStr
));
48 EXPECT_TRUE(testMap
.find(testKey
) == testMap
.end());
49 EXPECT_TRUE(testMap
.find(StringRef(testKeyFirst
, testKeyLength
)) ==
51 EXPECT_TRUE(testMap
.find(testKeyStr
) == testMap
.end());
54 void assertSingleItemMap() {
56 EXPECT_EQ(1u, testMap
.size());
57 EXPECT_FALSE(testMap
.begin() == testMap
.end());
58 EXPECT_FALSE(testMap
.empty());
61 StringMap
<uint32_t>::iterator it
= testMap
.begin();
62 EXPECT_STREQ(testKey
, it
->first().data());
63 EXPECT_EQ(testValue
, it
->second
);
65 EXPECT_TRUE(it
== testMap
.end());
68 EXPECT_TRUE(testMap
.contains(testKey
));
69 EXPECT_EQ(1u, testMap
.count(testKey
));
70 EXPECT_EQ(1u, testMap
.count(StringRef(testKeyFirst
, testKeyLength
)));
71 EXPECT_EQ(1u, testMap
.count(testKeyStr
));
72 EXPECT_TRUE(testMap
.find(testKey
) == testMap
.begin());
73 EXPECT_TRUE(testMap
.find(StringRef(testKeyFirst
, testKeyLength
)) ==
75 EXPECT_TRUE(testMap
.find(testKeyStr
) == testMap
.begin());
79 const char StringMapTest::testKey
[] = "key";
80 const uint32_t StringMapTest::testValue
= 1u;
81 const char *StringMapTest::testKeyFirst
= testKey
;
82 size_t StringMapTest::testKeyLength
= sizeof(testKey
) - 1;
83 const std::string
StringMapTest::testKeyStr(testKey
);
85 struct CountCopyAndMove
{
86 CountCopyAndMove() = default;
87 CountCopyAndMove(const CountCopyAndMove
&) { copy
= 1; }
88 CountCopyAndMove(CountCopyAndMove
&&) { move
= 1; }
89 void operator=(const CountCopyAndMove
&) { ++copy
; }
90 void operator=(CountCopyAndMove
&&) { ++move
; }
96 TEST_F(StringMapTest
, EmptyMapTest
) { assertEmptyMap(); }
98 // Constant map tests.
99 TEST_F(StringMapTest
, ConstEmptyMapTest
) {
100 const StringMap
<uint32_t> &constTestMap
= testMap
;
103 EXPECT_EQ(0u, constTestMap
.size());
104 EXPECT_TRUE(constTestMap
.empty());
107 EXPECT_TRUE(constTestMap
.begin() == constTestMap
.end());
110 EXPECT_EQ(0u, constTestMap
.count(testKey
));
111 EXPECT_EQ(0u, constTestMap
.count(StringRef(testKeyFirst
, testKeyLength
)));
112 EXPECT_EQ(0u, constTestMap
.count(testKeyStr
));
113 EXPECT_TRUE(constTestMap
.find(testKey
) == constTestMap
.end());
114 EXPECT_TRUE(constTestMap
.find(StringRef(testKeyFirst
, testKeyLength
)) ==
116 EXPECT_TRUE(constTestMap
.find(testKeyStr
) == constTestMap
.end());
119 // initializer_list ctor test; also implicitly tests initializer_list and
120 // iterator overloads of insert().
121 TEST_F(StringMapTest
, InitializerListCtor
) {
122 testMap
= StringMap
<uint32_t>({{"key", 1}});
123 assertSingleItemMap();
126 // A map with a single entry.
127 TEST_F(StringMapTest
, SingleEntryMapTest
) {
128 testMap
[testKey
] = testValue
;
129 assertSingleItemMap();
132 // Test clear() method.
133 TEST_F(StringMapTest
, ClearTest
) {
134 testMap
[testKey
] = testValue
;
139 // Test erase(iterator) method.
140 TEST_F(StringMapTest
, EraseIteratorTest
) {
141 testMap
[testKey
] = testValue
;
142 testMap
.erase(testMap
.begin());
146 // Test erase(value) method.
147 TEST_F(StringMapTest
, EraseValueTest
) {
148 testMap
[testKey
] = testValue
;
149 testMap
.erase(testKey
);
153 // Test inserting two values and erasing one.
154 TEST_F(StringMapTest
, InsertAndEraseTest
) {
155 testMap
[testKey
] = testValue
;
156 testMap
["otherKey"] = 2;
157 testMap
.erase("otherKey");
158 assertSingleItemMap();
161 TEST_F(StringMapTest
, SmallFullMapTest
) {
162 // StringMap has a tricky corner case when the map is small (<8 buckets) and
163 // it fills up through a balanced pattern of inserts and erases. This can
164 // lead to inf-loops in some cases (PR13148) so we test it explicitly here.
165 llvm::StringMap
<int> Map(2);
175 EXPECT_EQ(3u, Map
.size());
176 EXPECT_EQ(0, Map
.lookup("eins"));
177 EXPECT_EQ(2, Map
.lookup("zwei"));
178 EXPECT_EQ(0, Map
.lookup("drei"));
179 EXPECT_EQ(4, Map
.lookup("veir"));
180 EXPECT_EQ(5, Map
.lookup("funf"));
183 TEST_F(StringMapTest
, CopyCtorTest
) {
184 llvm::StringMap
<int> Map
;
194 EXPECT_EQ(3u, Map
.size());
195 EXPECT_EQ(0, Map
.lookup("eins"));
196 EXPECT_EQ(2, Map
.lookup("zwei"));
197 EXPECT_EQ(0, Map
.lookup("drei"));
198 EXPECT_EQ(4, Map
.lookup("veir"));
199 EXPECT_EQ(5, Map
.lookup("funf"));
201 llvm::StringMap
<int> Map2(Map
);
202 EXPECT_EQ(3u, Map2
.size());
203 EXPECT_EQ(0, Map2
.lookup("eins"));
204 EXPECT_EQ(2, Map2
.lookup("zwei"));
205 EXPECT_EQ(0, Map2
.lookup("drei"));
206 EXPECT_EQ(4, Map2
.lookup("veir"));
207 EXPECT_EQ(5, Map2
.lookup("funf"));
210 TEST_F(StringMapTest
, AtTest
) {
211 llvm::StringMap
<int> Map
;
213 // keys both found and not found on non-empty map
217 EXPECT_EQ(1, Map
.at("a"));
218 EXPECT_EQ(2, Map
.at("b"));
219 EXPECT_EQ(3, Map
.at("c"));
222 // A more complex iteration test.
223 TEST_F(StringMapTest
, IterationTest
) {
226 // Insert 100 numbers into the map
227 for (int i
= 0; i
< 100; ++i
) {
228 std::stringstream ss
;
230 testMap
[ss
.str()] = i
;
234 // Iterate over all numbers and mark each one found.
235 for (StringMap
<uint32_t>::iterator it
= testMap
.begin(); it
!= testMap
.end();
237 std::stringstream ss
;
238 ss
<< "key_" << it
->second
;
239 ASSERT_STREQ(ss
.str().c_str(), it
->first().data());
240 visited
[it
->second
] = true;
243 // Ensure every number was visited.
244 for (int i
= 0; i
< 100; ++i
) {
245 ASSERT_TRUE(visited
[i
]) << "Entry #" << i
<< " was never visited";
249 // Test StringMapEntry::Create() method.
250 TEST_F(StringMapTest
, StringMapEntryTest
) {
251 MallocAllocator Allocator
;
252 StringMap
<uint32_t>::value_type
*entry
=
253 StringMap
<uint32_t>::value_type::create(
254 StringRef(testKeyFirst
, testKeyLength
), Allocator
, 1u);
255 EXPECT_STREQ(testKey
, entry
->first().data());
256 EXPECT_EQ(1u, entry
->second
);
257 entry
->Destroy(Allocator
);
260 // Test insert() method.
261 TEST_F(StringMapTest
, InsertTest
) {
262 SCOPED_TRACE("InsertTest");
263 testMap
.insert(StringMap
<uint32_t>::value_type::create(
264 StringRef(testKeyFirst
, testKeyLength
), testMap
.getAllocator(), 1u));
265 assertSingleItemMap();
268 // Test insert(pair<K, V>) method
269 TEST_F(StringMapTest
, InsertPairTest
) {
271 StringMap
<uint32_t>::iterator NewIt
;
272 std::tie(NewIt
, Inserted
) =
273 testMap
.insert(std::make_pair(testKeyFirst
, testValue
));
274 EXPECT_EQ(1u, testMap
.size());
275 EXPECT_EQ(testValue
, testMap
[testKeyFirst
]);
276 EXPECT_EQ(testKeyFirst
, NewIt
->first());
277 EXPECT_EQ(testValue
, NewIt
->second
);
278 EXPECT_TRUE(Inserted
);
280 StringMap
<uint32_t>::iterator ExistingIt
;
281 std::tie(ExistingIt
, Inserted
) =
282 testMap
.insert(std::make_pair(testKeyFirst
, testValue
+ 1));
283 EXPECT_EQ(1u, testMap
.size());
284 EXPECT_EQ(testValue
, testMap
[testKeyFirst
]);
285 EXPECT_FALSE(Inserted
);
286 EXPECT_EQ(NewIt
, ExistingIt
);
289 // Test insert(pair<K, V>) method when rehashing occurs
290 TEST_F(StringMapTest
, InsertRehashingPairTest
) {
291 // Check that the correct iterator is returned when the inserted element is
292 // moved to a different bucket during internal rehashing. This depends on
293 // the particular key, and the implementation of StringMap and HashString.
294 // Changes to those might result in this test not actually checking that.
295 StringMap
<uint32_t> t(0);
296 EXPECT_EQ(0u, t
.getNumBuckets());
298 StringMap
<uint32_t>::iterator It
=
299 t
.insert(std::make_pair("abcdef", 42)).first
;
300 EXPECT_EQ(16u, t
.getNumBuckets());
301 EXPECT_EQ("abcdef", It
->first());
302 EXPECT_EQ(42u, It
->second
);
305 TEST_F(StringMapTest
, InsertOrAssignTest
) {
306 struct A
: CountCopyAndMove
{
312 auto try1
= t
.insert_or_assign("A", A(1));
313 EXPECT_TRUE(try1
.second
);
314 EXPECT_EQ(1, try1
.first
->second
.v
);
315 EXPECT_EQ(1, try1
.first
->second
.move
);
317 auto try2
= t
.insert_or_assign("A", A(2));
318 EXPECT_FALSE(try2
.second
);
319 EXPECT_EQ(2, try2
.first
->second
.v
);
320 EXPECT_EQ(2, try1
.first
->second
.move
);
322 EXPECT_EQ(try1
.first
, try2
.first
);
323 EXPECT_EQ(0, try1
.first
->second
.copy
);
326 TEST_F(StringMapTest
, IterMapKeysVector
) {
333 std::vector
<StringRef
> Keys
{Map
.keys().begin(), Map
.keys().end()};
336 std::vector
<StringRef
> Expected
{{"A", "B", "C", "D"}};
337 EXPECT_EQ(Expected
, Keys
);
340 TEST_F(StringMapTest
, IterMapKeysSmallVector
) {
347 auto Keys
= to_vector
<4>(Map
.keys());
350 SmallVector
<StringRef
, 4> Expected
= {"A", "B", "C", "D"};
351 EXPECT_EQ(Expected
, Keys
);
354 // Create a non-default constructable value
355 struct StringMapTestStruct
{
356 StringMapTestStruct(int i
) : i(i
) {}
357 StringMapTestStruct() = delete;
361 TEST_F(StringMapTest
, NonDefaultConstructable
) {
362 StringMap
<StringMapTestStruct
> t
;
363 t
.insert(std::make_pair("Test", StringMapTestStruct(123)));
364 StringMap
<StringMapTestStruct
>::iterator iter
= t
.find("Test");
365 ASSERT_NE(iter
, t
.end());
366 ASSERT_EQ(iter
->second
.i
, 123);
371 Immovable(Immovable
&&) = delete; // will disable the other special members
376 MoveOnly(int i
) : i(i
) {}
377 MoveOnly(const Immovable
&) : i(0) {}
378 MoveOnly(MoveOnly
&&RHS
) : i(RHS
.i
) {}
379 MoveOnly
&operator=(MoveOnly
&&RHS
) {
385 MoveOnly(const MoveOnly
&) = delete;
386 MoveOnly
&operator=(const MoveOnly
&) = delete;
389 TEST_F(StringMapTest
, MoveOnly
) {
390 StringMap
<MoveOnly
> t
;
391 t
.insert(std::make_pair("Test", MoveOnly(42)));
392 StringRef Key
= "Test";
393 StringMapEntry
<MoveOnly
>::create(Key
, t
.getAllocator(), MoveOnly(42))
394 ->Destroy(t
.getAllocator());
397 TEST_F(StringMapTest
, CtorArg
) {
398 StringRef Key
= "Test";
399 MallocAllocator Allocator
;
400 StringMapEntry
<MoveOnly
>::create(Key
, Allocator
, Immovable())
401 ->Destroy(Allocator
);
404 TEST_F(StringMapTest
, MoveConstruct
) {
407 StringMap
<int> B
= std::move(A
);
408 ASSERT_EQ(A
.size(), 0u);
409 ASSERT_EQ(B
.size(), 1u);
410 ASSERT_EQ(B
["x"], 42);
411 ASSERT_EQ(B
.count("y"), 0u);
414 TEST_F(StringMapTest
, MoveAssignment
) {
420 ASSERT_EQ(A
.size(), 1u);
421 ASSERT_EQ(B
.size(), 0u);
422 ASSERT_EQ(A
["y"], 117);
423 ASSERT_EQ(B
.count("x"), 0u);
426 TEST_F(StringMapTest
, EqualEmpty
) {
430 ASSERT_FALSE(A
!= B
);
431 ASSERT_TRUE(A
== A
); // self check
434 TEST_F(StringMapTest
, EqualWithValues
) {
449 ASSERT_FALSE(A
!= B
);
450 ASSERT_FALSE(B
!= A
);
451 ASSERT_TRUE(A
== A
); // self check
454 TEST_F(StringMapTest
, NotEqualMissingKeys
) {
465 ASSERT_FALSE(A
== B
);
466 ASSERT_FALSE(B
== A
);
471 TEST_F(StringMapTest
, NotEqualWithDifferentValues
) {
484 ASSERT_FALSE(A
== B
);
485 ASSERT_FALSE(B
== A
);
493 Countable(int Number
, int &InstanceCount
)
494 : InstanceCount(InstanceCount
), Number(Number
) {
497 Countable(Countable
&&C
) : InstanceCount(C
.InstanceCount
), Number(C
.Number
) {
501 Countable(const Countable
&C
)
502 : InstanceCount(C
.InstanceCount
), Number(C
.Number
) {
505 Countable
&operator=(Countable C
) {
509 ~Countable() { --InstanceCount
; }
512 TEST_F(StringMapTest
, MoveDtor
) {
513 int InstanceCount
= 0;
514 StringMap
<Countable
> A
;
515 A
.insert(std::make_pair("x", Countable(42, InstanceCount
)));
516 ASSERT_EQ(InstanceCount
, 1);
517 auto I
= A
.find("x");
518 ASSERT_NE(I
, A
.end());
519 ASSERT_EQ(I
->second
.Number
, 42);
521 StringMap
<Countable
> B
;
523 ASSERT_EQ(InstanceCount
, 1);
524 ASSERT_TRUE(A
.empty());
526 ASSERT_NE(I
, B
.end());
527 ASSERT_EQ(I
->second
.Number
, 42);
529 B
= StringMap
<Countable
>();
530 ASSERT_EQ(InstanceCount
, 0);
531 ASSERT_TRUE(B
.empty());
534 TEST_F(StringMapTest
, StructuredBindings
) {
538 for (auto &[Key
, Value
] : A
) {
540 EXPECT_EQ(42, Value
);
545 // Simple class that counts how many moves and copy happens when growing a map
546 struct CountCtorCopyAndMove
{
547 static unsigned Ctor
;
548 static unsigned Move
;
549 static unsigned Copy
;
551 CountCtorCopyAndMove(int Data
) : Data(Data
) { Ctor
++; }
552 CountCtorCopyAndMove() { Ctor
++; }
554 CountCtorCopyAndMove(const CountCtorCopyAndMove
&) { Copy
++; }
555 CountCtorCopyAndMove
&operator=(const CountCtorCopyAndMove
&) {
559 CountCtorCopyAndMove(CountCtorCopyAndMove
&&) { Move
++; }
560 CountCtorCopyAndMove
&operator=(const CountCtorCopyAndMove
&&) {
565 unsigned CountCtorCopyAndMove::Copy
= 0;
566 unsigned CountCtorCopyAndMove::Move
= 0;
567 unsigned CountCtorCopyAndMove::Ctor
= 0;
569 } // anonymous namespace
571 // Make sure creating the map with an initial size of N actually gives us enough
572 // buckets to insert N items without increasing allocation size.
573 TEST(StringMapCustomTest
, InitialSizeTest
) {
574 // 1 is an "edge value", 32 is an arbitrary power of two, and 67 is an
575 // arbitrary prime, picked without any good reason.
576 for (auto Size
: {1, 32, 67}) {
577 StringMap
<CountCtorCopyAndMove
> Map(Size
);
578 auto NumBuckets
= Map
.getNumBuckets();
579 CountCtorCopyAndMove::Move
= 0;
580 CountCtorCopyAndMove::Copy
= 0;
581 for (int i
= 0; i
< Size
; ++i
)
582 Map
.insert(std::pair
<std::string
, CountCtorCopyAndMove
>(
583 std::piecewise_construct
, std::forward_as_tuple(Twine(i
).str()),
584 std::forward_as_tuple(i
)));
585 // After the initial move, the map will move the Elts in the Entry.
586 EXPECT_EQ((unsigned)Size
* 2, CountCtorCopyAndMove::Move
);
587 // We copy once the pair from the Elts vector
588 EXPECT_EQ(0u, CountCtorCopyAndMove::Copy
);
589 // Check that the map didn't grow
590 EXPECT_EQ(Map
.getNumBuckets(), NumBuckets
);
594 TEST(StringMapCustomTest
, BracketOperatorCtor
) {
595 StringMap
<CountCtorCopyAndMove
> Map
;
596 CountCtorCopyAndMove::Ctor
= 0;
598 EXPECT_EQ(1u, CountCtorCopyAndMove::Ctor
);
599 // Test that operator[] does not create a value when it is already in the map
600 CountCtorCopyAndMove::Ctor
= 0;
602 EXPECT_EQ(0u, CountCtorCopyAndMove::Ctor
);
606 struct NonMoveableNonCopyableType
{
608 NonMoveableNonCopyableType() = default;
609 NonMoveableNonCopyableType(int Data
) : Data(Data
) {}
610 NonMoveableNonCopyableType(const NonMoveableNonCopyableType
&) = delete;
611 NonMoveableNonCopyableType(NonMoveableNonCopyableType
&&) = delete;
615 // Test that we can "emplace" an element in the map without involving map/move
616 TEST(StringMapCustomTest
, EmplaceTest
) {
617 StringMap
<NonMoveableNonCopyableType
> Map
;
618 Map
.try_emplace("abcd", 42);
619 EXPECT_EQ(1u, Map
.count("abcd"));
620 EXPECT_EQ(42, Map
["abcd"].Data
);
623 // Test that StringMapEntryBase can handle size_t wide sizes.
624 TEST(StringMapCustomTest
, StringMapEntryBaseSize
) {
627 // Test that the entry can represent max-unsigned.
628 if (sizeof(size_t) <= sizeof(unsigned))
629 LargeValue
= std::numeric_limits
<unsigned>::max();
631 LargeValue
= std::numeric_limits
<unsigned>::max() + 1ULL;
632 StringMapEntryBase
LargeBase(LargeValue
);
633 EXPECT_EQ(LargeValue
, LargeBase
.getKeyLength());
635 // Test that the entry can hold at least max size_t.
636 LargeValue
= std::numeric_limits
<size_t>::max();
637 StringMapEntryBase
LargerBase(LargeValue
);
638 LargeValue
= std::numeric_limits
<size_t>::max();
639 EXPECT_EQ(LargeValue
, LargerBase
.getKeyLength());
642 // Test that StringMapEntry can handle size_t wide sizes.
643 TEST(StringMapCustomTest
, StringMapEntrySize
) {
646 // Test that the entry can represent max-unsigned.
647 if (sizeof(size_t) <= sizeof(unsigned))
648 LargeValue
= std::numeric_limits
<unsigned>::max();
650 LargeValue
= std::numeric_limits
<unsigned>::max() + 1ULL;
651 StringMapEntry
<int> LargeEntry(LargeValue
);
652 StringRef Key
= LargeEntry
.getKey();
653 EXPECT_EQ(LargeValue
, Key
.size());
655 // Test that the entry can hold at least max size_t.
656 LargeValue
= std::numeric_limits
<size_t>::max();
657 StringMapEntry
<int> LargerEntry(LargeValue
);
658 Key
= LargerEntry
.getKey();
659 EXPECT_EQ(LargeValue
, Key
.size());
662 } // end anonymous namespace