• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 // A hack to include windows.h first, which ensures the GetMessage macro can
32 // be undefined when we include <google/protobuf/stubs/common.h>
33 #if defined(_WIN32)
34 #define _WINSOCKAPI_  // to avoid re-definition in WinSock2.h
35 #define NOMINMAX      // to avoid defining min/max macros
36 #include <windows.h>
37 #endif  // _WIN32
38 
39 #include <algorithm>
40 #include <map>
41 #include <memory>
42 #include <random>
43 #include <set>
44 #include <sstream>
45 #include <unordered_map>
46 #include <unordered_set>
47 #include <vector>
48 
49 #include <google/protobuf/stubs/logging.h>
50 #include <google/protobuf/stubs/common.h>
51 #include <google/protobuf/stubs/stringprintf.h>
52 #include <google/protobuf/testing/file.h>
53 #include <google/protobuf/arena_test_util.h>
54 #include <google/protobuf/map_proto2_unittest.pb.h>
55 #include <google/protobuf/map_test_util.h>
56 #include <google/protobuf/map_unittest.pb.h>
57 #include <google/protobuf/test_util.h>
58 #include <google/protobuf/test_util2.h>
59 #include <google/protobuf/unittest.pb.h>
60 #include <google/protobuf/io/coded_stream.h>
61 #include <google/protobuf/io/tokenizer.h>
62 #include <google/protobuf/io/zero_copy_stream_impl.h>
63 #include <google/protobuf/descriptor.pb.h>
64 #include <google/protobuf/descriptor.h>
65 #include <google/protobuf/descriptor_database.h>
66 #include <google/protobuf/dynamic_message.h>
67 #include <google/protobuf/map.h>
68 #include <google/protobuf/map_field_inl.h>
69 #include <google/protobuf/message.h>
70 #include <google/protobuf/reflection.h>
71 #include <google/protobuf/reflection_ops.h>
72 #include <google/protobuf/text_format.h>
73 #include <google/protobuf/wire_format.h>
74 #include <google/protobuf/util/message_differencer.h>
75 #include <google/protobuf/util/time_util.h>
76 #include <gmock/gmock.h>
77 #include <google/protobuf/testing/googletest.h>
78 #include <gtest/gtest.h>
79 #include <google/protobuf/stubs/casts.h>
80 #include <google/protobuf/stubs/substitute.h>
81 
82 
83 // Must be included last.
84 #include <google/protobuf/port_def.inc>
85 
86 namespace google {
87 namespace protobuf {
88 
89 using unittest::ForeignMessage;
90 using unittest::TestAllTypes;
91 using unittest::TestMap;
92 using unittest::TestRecursiveMapMessage;
93 
94 namespace internal {
95 
MapTestForceDeterministic()96 void MapTestForceDeterministic() {
97   io::CodedOutputStream::SetDefaultSerializationDeterministic();
98 }
99 
100 namespace {
101 
102 // Map API Test =====================================================
103 
104 class MapImplTest : public ::testing::Test {
105  protected:
MapImplTest()106   MapImplTest()
107       : map_ptr_(new Map<int32, int32>()),
108         map_(*map_ptr_),
109         const_map_(*map_ptr_) {
110     EXPECT_TRUE(map_.empty());
111     EXPECT_EQ(0, map_.size());
112   }
113 
ExpectSingleElement(int32 key,int32 value)114   void ExpectSingleElement(int32 key, int32 value) {
115     EXPECT_FALSE(map_.empty());
116     EXPECT_EQ(1, map_.size());
117     ExpectElement(key, value);
118   }
119 
ExpectElements(const std::map<int32,int32> & map)120   void ExpectElements(const std::map<int32, int32>& map) {
121     EXPECT_FALSE(map_.empty());
122     EXPECT_EQ(map.size(), map_.size());
123     for (std::map<int32, int32>::const_iterator it = map.begin();
124          it != map.end(); ++it) {
125       ExpectElement(it->first, it->second);
126     }
127   }
128 
ExpectElement(int32 key,int32 value)129   void ExpectElement(int32 key, int32 value) {
130     // Test map size is correct.
131     EXPECT_EQ(value, map_[key]);
132     EXPECT_EQ(1, map_.count(key));
133     EXPECT_TRUE(map_.contains(key));
134 
135     // Check mutable at and find work correctly.
136     EXPECT_EQ(value, map_.at(key));
137     Map<int32, int32>::iterator it = map_.find(key);
138 
139     // iterator dereferenceable
140     EXPECT_EQ(key, (*it).first);
141     EXPECT_EQ(value, (*it).second);
142     EXPECT_EQ(key, it->first);
143     EXPECT_EQ(value, it->second);
144 
145     // iterator mutable
146     ((*it).second) = value + 1;
147     EXPECT_EQ(value + 1, map_[key]);
148     ((*it).second) = value;
149     EXPECT_EQ(value, map_[key]);
150 
151     it->second = value + 1;
152     EXPECT_EQ(value + 1, map_[key]);
153     it->second = value;
154     EXPECT_EQ(value, map_[key]);
155 
156     // copy constructor
157     Map<int32, int32>::iterator it_copy = it;
158     EXPECT_EQ(key, it_copy->first);
159     EXPECT_EQ(value, it_copy->second);
160 
161     // Immutable API ================================================
162 
163     // Check immutable at and find work correctly.
164     EXPECT_EQ(value, const_map_.at(key));
165     Map<int32, int32>::const_iterator const_it = const_map_.find(key);
166 
167     // iterator dereferenceable
168     EXPECT_EQ(key, (*const_it).first);
169     EXPECT_EQ(value, (*const_it).second);
170     EXPECT_EQ(key, const_it->first);
171     EXPECT_EQ(value, const_it->second);
172 
173     // copy constructor
174     Map<int32, int32>::const_iterator const_it_copy = const_it;
175     EXPECT_EQ(key, const_it_copy->first);
176     EXPECT_EQ(value, const_it_copy->second);
177   }
178 
179   std::unique_ptr<Map<int32, int32> > map_ptr_;
180   Map<int32, int32>& map_;
181   const Map<int32, int32>& const_map_;
182 };
183 
TEST_F(MapImplTest,OperatorBracket)184 TEST_F(MapImplTest, OperatorBracket) {
185   int32 key = 0;
186   int32 value1 = 100;
187   int32 value2 = 101;
188 
189   EXPECT_EQ(0, map_[key]);
190 
191   map_[key] = value1;
192   ExpectSingleElement(key, value1);
193 
194   map_[key] = value2;
195   ExpectSingleElement(key, value2);
196 }
197 
198 struct MoveTestKey {
MoveTestKeygoogle::protobuf::internal::__anonfd84ed360111::MoveTestKey199   MoveTestKey(int data, int* copies) : data(data), copies(copies) {}
200 
MoveTestKeygoogle::protobuf::internal::__anonfd84ed360111::MoveTestKey201   MoveTestKey(const MoveTestKey& other)
202       : data(other.data), copies(other.copies) {
203     ++*copies;
204   }
205 
MoveTestKeygoogle::protobuf::internal::__anonfd84ed360111::MoveTestKey206   MoveTestKey(MoveTestKey&& other) noexcept
207       : data(other.data), copies(other.copies) {}
208 
operator ==(const MoveTestKey & lhs,const MoveTestKey & rhs)209   friend bool operator==(const MoveTestKey& lhs, const MoveTestKey& rhs) {
210     return lhs.data == rhs.data;
211   }
operator <(const MoveTestKey & lhs,const MoveTestKey & rhs)212   friend bool operator<(const MoveTestKey& lhs, const MoveTestKey& rhs) {
213     return lhs.data < rhs.data;
214   }
215 
216   int data;
217   int* copies;
218 };
219 
220 }  // namespace
221 }  // namespace internal
222 }  // namespace protobuf
223 }  // namespace google
224 
225 namespace std {
226 
227 template <>  // NOLINT
228 struct hash<google::protobuf::internal::MoveTestKey> {
operator ()std::hash229   size_t operator()(const google::protobuf::internal::MoveTestKey& key) const {
230     return hash<int>{}(key.data);
231   }
232 };
233 }  // namespace std
234 
235 namespace google {
236 namespace protobuf {
237 namespace internal {
238 namespace {
239 
TEST_F(MapImplTest,OperatorBracketRValue)240 TEST_F(MapImplTest, OperatorBracketRValue) {
241   Arena arena;
242   for (Arena* arena_to_use : {&arena, static_cast<Arena*>(nullptr)}) {
243     int copies = 0;
244     Map<MoveTestKey, int> map(arena_to_use);
245     MoveTestKey key1(1, &copies);
246     EXPECT_EQ(copies, 0);
247     map[key1] = 0;
248     EXPECT_EQ(copies, 1);
249     map[MoveTestKey(2, &copies)] = 2;
250     EXPECT_EQ(copies, 1);
251   }
252 }
253 
TEST_F(MapImplTest,OperatorBracketNonExist)254 TEST_F(MapImplTest, OperatorBracketNonExist) {
255   int32 key = 0;
256   int32 default_value = 0;
257 
258   EXPECT_EQ(default_value, map_[key]);
259   ExpectSingleElement(key, default_value);
260 }
261 
TEST_F(MapImplTest,MutableAt)262 TEST_F(MapImplTest, MutableAt) {
263   int32 key = 0;
264   int32 value1 = 100;
265   int32 value2 = 101;
266 
267   map_[key] = value1;
268   ExpectSingleElement(key, value1);
269 
270   map_.at(key) = value2;
271   ExpectSingleElement(key, value2);
272 }
273 
274 #ifdef PROTOBUF_HAS_DEATH_TEST
275 
TEST_F(MapImplTest,MutableAtNonExistDeathTest)276 TEST_F(MapImplTest, MutableAtNonExistDeathTest) {
277   EXPECT_DEATH(map_.at(0), "");
278 }
279 
TEST_F(MapImplTest,ImmutableAtNonExistDeathTest)280 TEST_F(MapImplTest, ImmutableAtNonExistDeathTest) {
281   EXPECT_DEATH(const_map_.at(0), "");
282 }
283 
TEST_F(MapImplTest,UsageErrors)284 TEST_F(MapImplTest, UsageErrors) {
285   MapKey key;
286   key.SetInt64Value(1);
287   EXPECT_DEATH(key.GetUInt64Value(),
288                "Protocol Buffer map usage error:\n"
289                "MapKey::GetUInt64Value type does not match\n"
290                "  Expected : uint64\n"
291                "  Actual   : int64");
292 
293   MapValueRef value;
294   EXPECT_DEATH(
295       value.SetFloatValue(0.1),
296       "Protocol Buffer map usage error:\n"
297       "MapValue[Const]*Ref::type MapValue[Const]*Ref is not initialized.");
298 }
299 
300 #endif  // PROTOBUF_HAS_DEATH_TEST
301 
TEST_F(MapImplTest,MapKeyAssignment)302 TEST_F(MapImplTest, MapKeyAssignment) {
303   MapKey from, to;
304   from.SetStringValue("abc");
305   to = from;
306   EXPECT_EQ("abc", to.GetStringValue());
307 }
308 
TEST_F(MapImplTest,CountNonExist)309 TEST_F(MapImplTest, CountNonExist) { EXPECT_EQ(0, map_.count(0)); }
310 
TEST_F(MapImplTest,ContainNotExist)311 TEST_F(MapImplTest, ContainNotExist) { EXPECT_FALSE(map_.contains(0)); }
312 
TEST_F(MapImplTest,ImmutableContainNotExist)313 TEST_F(MapImplTest, ImmutableContainNotExist) {
314   EXPECT_FALSE(const_map_.contains(0));
315 }
316 
TEST_F(MapImplTest,MutableFindNonExist)317 TEST_F(MapImplTest, MutableFindNonExist) {
318   EXPECT_TRUE(map_.end() == map_.find(0));
319 }
320 
TEST_F(MapImplTest,ImmutableFindNonExist)321 TEST_F(MapImplTest, ImmutableFindNonExist) {
322   EXPECT_TRUE(const_map_.end() == const_map_.find(0));
323 }
324 
TEST_F(MapImplTest,ConstEnd)325 TEST_F(MapImplTest, ConstEnd) {
326   EXPECT_TRUE(const_map_.end() == const_map_.cend());
327 }
328 
TEST_F(MapImplTest,GetReferenceFromIterator)329 TEST_F(MapImplTest, GetReferenceFromIterator) {
330   for (int i = 0; i < 10; i++) {
331     map_[i] = i;
332   }
333 
334   for (Map<int32, int32>::const_iterator it = map_.cbegin();
335        it != map_.cend();) {
336     Map<int32, int32>::const_reference entry = *it++;
337     EXPECT_EQ(entry.first, entry.second);
338   }
339 
340   for (Map<int32, int32>::const_iterator it = const_map_.begin();
341        it != const_map_.end();) {
342     Map<int32, int32>::const_reference entry = *it++;
343     EXPECT_EQ(entry.first, entry.second);
344   }
345 
346   for (Map<int32, int32>::iterator it = map_.begin(); it != map_.end();) {
347     Map<int32, int32>::reference entry = *it++;
348     EXPECT_EQ(entry.first + 1, ++entry.second);
349   }
350 }
351 
TEST_F(MapImplTest,IteratorBasic)352 TEST_F(MapImplTest, IteratorBasic) {
353   map_[0] = 0;
354 
355   // Default constructible (per forward iterator requirements).
356   Map<int, int>::const_iterator cit;
357   Map<int, int>::iterator it;
358 
359   it = map_.begin();
360   cit = it;  // Converts to const_iterator
361 
362   // Can compare between them.
363   EXPECT_TRUE(it == cit);
364   EXPECT_FALSE(cit != it);
365 
366   // Pre increment.
367   EXPECT_FALSE(it == ++cit);
368 
369   // Post increment.
370   EXPECT_FALSE(it++ == cit);
371   EXPECT_TRUE(it == cit);
372 }
373 
374 template <typename Iterator>
median(Iterator i0,Iterator i1)375 static int64 median(Iterator i0, Iterator i1) {
376   std::vector<int64> v(i0, i1);
377   std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end());
378   return v[v.size() / 2];
379 }
380 
Now()381 static int64 Now() {
382   return util::TimeUtil::TimestampToNanoseconds(
383       util::TimeUtil::GetCurrentTime());
384 }
385 
386 // Arbitrary odd integers for creating test data.
387 static int k0 = 812398771;
388 static int k1 = 1312938717;
389 static int k2 = 1321555333;
390 
391 // A naive begin() implementation will cause begin() to get slower and slower
392 // if one erases elements at the "front" of the hash map, and we'd like to
393 // avoid that, as std::unordered_map does.
TEST_F(MapImplTest,BeginIsFast)394 TEST_F(MapImplTest, BeginIsFast) {
395   if (true) return;  // TODO(gpike): make this less flaky and re-enable it.
396   Map<int32, int32> map;
397   const int kTestSize = 250000;
398   // Create a random-looking map of size n.  Use non-negative integer keys.
399   uint32 frog = 123983;
400   int last_key = 0;
401   int counter = 0;
402   while (map.size() < kTestSize) {
403     frog *= static_cast<uint32>(k0);
404     frog ^= frog >> 17;
405     frog += counter++;
406     last_key =
407         static_cast<int>(frog) >= 0 ? static_cast<int>(frog) : last_key ^ 1;
408     GOOGLE_DCHECK_GE(last_key, 0);
409     map[last_key] = last_key ^ 1;
410   }
411   std::vector<int64> times;
412   // We're going to do map.erase(map.begin()) over and over again.  But,
413   // just in case one iteration is fast compared to the granularity of
414   // our time keeping, we measure kChunkSize iterations per outer-loop iter.
415   const int kChunkSize = 1000;
416   GOOGLE_CHECK_EQ(kTestSize % kChunkSize, 0);
417   do {
418     const int64 start = Now();
419     for (int i = 0; i < kChunkSize; i++) {
420       map.erase(map.begin());
421     }
422     const int64 end = Now();
423     if (end > start) {
424       times.push_back(end - start);
425     }
426   } while (!map.empty());
427   if (times.size() < .99 * kTestSize / kChunkSize) {
428     GOOGLE_LOG(WARNING) << "Now() isn't helping us measure time";
429     return;
430   }
431   int64 x0 = median(times.begin(), times.begin() + 9);
432   int64 x1 = median(times.begin() + times.size() - 9, times.end());
433   GOOGLE_LOG(INFO) << "x0=" << x0 << ", x1=" << x1;
434   // x1 will greatly exceed x0 if the code we just executed took O(n^2) time.
435   // And we'll probably time out and never get here.  So, this test is
436   // intentionally loose: we check that x0 and x1 are within a factor of 8.
437   EXPECT_GE(x1, x0 / 8);
438   EXPECT_GE(x0, x1 / 8);
439 }
440 
441 // Try to create kTestSize keys that will land in just a few buckets, and
442 // time the insertions, to get a rough estimate of whether an O(n^2) worst case
443 // was triggered.  This test is a hacky, but probably better than nothing.
TEST_F(MapImplTest,HashFlood)444 TEST_F(MapImplTest, HashFlood) {
445   const int kTestSize = 1024;  // must be a power of 2
446   std::set<int> s;
447   for (int i = 0; s.size() < kTestSize; i++) {
448     if ((map_.hash_function()(i) & (kTestSize - 1)) < 3) {
449       s.insert(i);
450     }
451   }
452   // Create hash table with kTestSize entries that hash flood a table with
453   // 1024 (or 512 or 2048 or ...) entries.  This assumes that map_ uses powers
454   // of 2 for table sizes, and that it's sufficient to "flood" with respect to
455   // the low bits of the output of map_.hash_function().
456   std::vector<int64> times;
457   std::set<int>::iterator it = s.begin();
458   int count = 0;
459   do {
460     const int64 start = Now();
461     map_[*it] = 0;
462     const int64 end = Now();
463     if (end > start) {
464       times.push_back(end - start);
465     }
466     ++count;
467     ++it;
468   } while (it != s.end());
469   if (times.size() < .99 * count) return;
470   int64 x0 = median(times.begin(), times.begin() + 9);
471   int64 x1 = median(times.begin() + times.size() - 9, times.end());
472   // x1 will greatly exceed x0 if the code we just executed took O(n^2) time.
473   // But we want to allow O(n log n).  A factor of 20 should be generous enough.
474   EXPECT_LE(x1, x0 * 20);
475 }
476 
TEST_F(MapImplTest,CopyIteratorStressTest)477 TEST_F(MapImplTest, CopyIteratorStressTest) {
478   std::vector<Map<int32, int32>::iterator> v;
479   const int kIters = 1e5;
480   for (uint32 i = 0; i < kIters; i++) {
481     int32 key = (3 + i * (5 + i * (-8 + i * (62 + i)))) & 0x77777777;
482     map_[key] = i;
483     v.push_back(map_.find(key));
484   }
485   for (std::vector<Map<int32, int32>::iterator>::const_iterator it = v.begin();
486        it != v.end(); it++) {
487     Map<int32, int32>::iterator i = *it;
488     ASSERT_EQ(i->first, (*it)->first);
489     ASSERT_EQ(i->second, (*it)->second);
490   }
491 }
492 
493 template <typename T, typename U>
TestValidityForAllKeysExcept(int key_to_avoid,const T & check_map,const U & map)494 static void TestValidityForAllKeysExcept(int key_to_avoid, const T& check_map,
495                                          const U& map) {
496   typedef typename U::value_type value_type;  // a key-value pair
497   for (typename U::const_iterator it = map.begin(); it != map.end(); ++it) {
498     const int key = it->first;
499     if (key == key_to_avoid) continue;
500     // All iterators relevant to this key, whether old (from check_map) or new,
501     // must point to the same memory.  So, test pointer equality here.
502     const value_type* check_val = &*check_map.find(key)->second;
503     EXPECT_EQ(check_val, &*it);
504     EXPECT_EQ(check_val, &*map.find(key));
505   }
506 }
507 
508 // EXPECT i0 and i1 to be the same.  Advancing them should have the same effect,
509 // too.
510 template <typename Iter>
TestEqualIterators(Iter i0,Iter i1,Iter end)511 static void TestEqualIterators(Iter i0, Iter i1, Iter end) {
512   const int kMaxAdvance = 10;
513   for (int i = 0; i < kMaxAdvance; i++) {
514     EXPECT_EQ(i0 == end, i1 == end);
515     if (i0 == end) return;
516     EXPECT_EQ(&*i0, &*i1) << "iter " << i;
517     ++i0;
518     ++i1;
519   }
520 }
521 
522 template <typename IteratorType>
TestOldVersusNewIterator(int skip,Map<int,int> * m)523 static void TestOldVersusNewIterator(int skip, Map<int, int>* m) {
524   const int initial_size = m->size();
525   IteratorType it = m->begin();
526   for (int i = 0; i < skip && it != m->end(); it++, i++) {
527   }
528   if (it == m->end()) return;
529   const IteratorType old = it;
530   GOOGLE_LOG(INFO) << "skip=" << skip << ", old->first=" << old->first;
531   const int target_size =
532       initial_size < 100 ? initial_size * 5 : initial_size * 5 / 4;
533   for (int i = 0; m->size() <= target_size; i++) {
534     (*m)[i] = 0;
535   }
536   // Iterator 'old' should still work just fine despite the growth of *m.
537   const IteratorType after_growth = m->find(old->first);
538   TestEqualIterators<IteratorType>(old, after_growth, m->end());
539 
540   // Now shrink the number of elements.  Do this with a mix of erases and
541   // inserts to increase the chance that the hashtable will resize to a lower
542   // number of buckets.  (But, in any case, the test is still useful.)
543   for (int i = 0; i < 2 * (target_size - initial_size); i++) {
544     if (i != old->first) {
545       m->erase(i);
546     }
547     if (((i ^ m->begin()->first) & 15) == 0) {
548       (*m)[i * 342] = i;
549     }
550   }
551   // Now, the table has grown and shrunk; test again.
552   TestEqualIterators<IteratorType>(old, m->find(old->first), m->end());
553   TestEqualIterators<IteratorType>(old, after_growth, m->end());
554 }
555 
556 // Create and test an n-element Map, with emphasis on iterator correctness.
StressTestIterators(int n)557 static void StressTestIterators(int n) {
558   GOOGLE_LOG(INFO) << "StressTestIterators " << n;
559   GOOGLE_CHECK_GT(n, 0);
560   // Create a random-looking map of size n.  Use non-negative integer keys.
561   Map<int, int> m;
562   uint32 frog = 123987 + n;
563   int last_key = 0;
564   int counter = 0;
565   while (m.size() < n) {
566     frog *= static_cast<uint32>(k0);
567     frog ^= frog >> 17;
568     frog += counter++;
569     last_key =
570         static_cast<int>(frog) >= 0 ? static_cast<int>(frog) : last_key ^ 1;
571     GOOGLE_DCHECK_GE(last_key, 0);
572     m[last_key] = last_key ^ 1;
573   }
574   // Test it.
575   ASSERT_EQ(n, m.size());
576   // Create maps of pointers and iterators.
577   // These should remain valid even if we modify m.
578   std::unordered_map<int, Map<int, int>::value_type*> mp(n);
579   std::unordered_map<int, Map<int, int>::iterator> mi(n);
580   for (Map<int, int>::iterator it = m.begin(); it != m.end(); ++it) {
581     mp[it->first] = &*it;
582     mi[it->first] = it;
583   }
584   ASSERT_EQ(m.size(), mi.size());
585   ASSERT_EQ(m.size(), mp.size());
586   m.erase(last_key);
587   ASSERT_EQ(n - 1, m.size());
588   TestValidityForAllKeysExcept(last_key, mp, m);
589   TestValidityForAllKeysExcept(last_key, mi, m);
590 
591   m[last_key] = 0;
592   ASSERT_EQ(n, m.size());
593   // Test old iterator vs new iterator, with table modification in between.
594   TestOldVersusNewIterator<Map<int, int>::const_iterator>(n % 3, &m);
595   TestOldVersusNewIterator<Map<int, int>::iterator>(n % (1 + (n / 40)), &m);
596   // Finally, ensure erase(iterator) doesn't reorder anything, because that is
597   // what its documentation says.
598   m[last_key] = m[last_key ^ 999] = 0;
599   std::vector<Map<int, int>::iterator> v;
600   v.reserve(m.size());
601   int position_of_last_key = 0;
602   for (Map<int, int>::iterator it = m.begin(); it != m.end(); ++it) {
603     if (it->first == last_key) {
604       position_of_last_key = v.size();
605     }
606     v.push_back(it);
607   }
608   ASSERT_EQ(m.size(), v.size());
609   const Map<int, int>::iterator erase_result = m.erase(m.find(last_key));
610   int index = 0;
611   for (Map<int, int>::iterator it = m.begin(); it != m.end(); ++it, ++index) {
612     if (index == position_of_last_key) {
613       EXPECT_EQ(&*erase_result, &*v[++index]);
614     }
615     ASSERT_EQ(&*it, &*v[index]);
616   }
617 }
618 
TEST_F(MapImplTest,IteratorInvalidation)619 TEST_F(MapImplTest, IteratorInvalidation) {
620   // Create a set of pseudo-random sizes to test.
621 #ifndef NDEBUG
622   const int kMaxSizeToTest = 100 * 1000;
623 #else
624   const int kMaxSizeToTest = 1000 * 1000;
625 #endif
626   std::set<int> s;
627   int n = kMaxSizeToTest;
628   unsigned int frog = k1 + n;
629   while (n > 1 && s.size() < 25) {
630     s.insert(n);
631     n = static_cast<int>(n * 100 / (101.0 + (frog & 63)));
632     frog *= k2;
633     frog ^= frog >> 17;
634   }
635   // Ensure we test a few small sizes.
636   s.insert(1);
637   s.insert(2);
638   s.insert(3);
639   // Now, the real work.
640   for (std::set<int>::iterator i = s.begin(); i != s.end(); ++i) {
641     StressTestIterators(*i);
642   }
643 }
644 
645 // Test that erase() revalidates iterators.
TEST_F(MapImplTest,EraseRevalidates)646 TEST_F(MapImplTest, EraseRevalidates) {
647   map_[3] = map_[13] = map_[20] = 0;
648   const int initial_size = map_.size();
649   EXPECT_EQ(3, initial_size);
650   std::vector<Map<int, int>::iterator> v;
651   for (Map<int, int>::iterator it = map_.begin(); it != map_.end(); ++it) {
652     v.push_back(it);
653   }
654   EXPECT_EQ(initial_size, v.size());
655   for (int i = 0; map_.size() <= initial_size * 20; i++) {
656     map_[i] = 0;
657   }
658   const int larger_size = map_.size();
659   // We've greatly increased the size of the map, so it is highly likely that
660   // the following will corrupt m if erase() doesn't properly revalidate
661   // iterators passed to it.  Finishing this routine without crashing indicates
662   // success.
663   for (int i = 0; i < v.size(); i++) {
664     map_.erase(v[i]);
665   }
666   EXPECT_EQ(larger_size - v.size(), map_.size());
667 }
668 
669 template <typename T>
IsConstHelper(T &)670 bool IsConstHelper(T& /*t*/) {  // NOLINT. We want to catch non-const refs here.
671   return false;
672 }
673 template <typename T>
IsConstHelper(const T &)674 bool IsConstHelper(const T& /*t*/) {
675   return true;
676 }
677 
TEST_F(MapImplTest,IteratorConstness)678 TEST_F(MapImplTest, IteratorConstness) {
679   map_[0] = 0;
680   EXPECT_TRUE(IsConstHelper(*map_.cbegin()));
681   EXPECT_TRUE(IsConstHelper(*const_map_.begin()));
682   EXPECT_FALSE(IsConstHelper(*map_.begin()));
683 }
684 
IsForwardIteratorHelper(std::forward_iterator_tag)685 bool IsForwardIteratorHelper(std::forward_iterator_tag /*tag*/) { return true; }
686 
TEST_F(MapImplTest,IteratorCategory)687 TEST_F(MapImplTest, IteratorCategory) {
688   EXPECT_TRUE(IsForwardIteratorHelper(
689       std::iterator_traits<Map<int, int>::iterator>::iterator_category()));
690   EXPECT_TRUE(IsForwardIteratorHelper(
691       std::iterator_traits<
692           Map<int, int>::const_iterator>::iterator_category()));
693 }
694 
TEST_F(MapImplTest,InsertSingle)695 TEST_F(MapImplTest, InsertSingle) {
696   int32 key = 0;
697   int32 value1 = 100;
698   int32 value2 = 101;
699 
700   // Insert a non-existed key.
701   std::pair<Map<int32, int32>::iterator, bool> result1 =
702       map_.insert(Map<int32, int32>::value_type(key, value1));
703   ExpectSingleElement(key, value1);
704 
705   Map<int32, int32>::iterator it1 = result1.first;
706   EXPECT_EQ(key, it1->first);
707   EXPECT_EQ(value1, it1->second);
708   EXPECT_TRUE(result1.second);
709 
710   // Insert an existed key.
711   std::pair<Map<int32, int32>::iterator, bool> result2 =
712       map_.insert(Map<int32, int32>::value_type(key, value2));
713   ExpectSingleElement(key, value1);
714 
715   Map<int32, int32>::iterator it2 = result2.first;
716   EXPECT_TRUE(it1 == it2);
717   EXPECT_FALSE(result2.second);
718 }
719 
TEST_F(MapImplTest,InsertByIterator)720 TEST_F(MapImplTest, InsertByIterator) {
721   int32 key1 = 0;
722   int32 key2 = 1;
723   int32 value1a = 100;
724   int32 value1b = 101;
725   int32 value2a = 200;
726   int32 value2b = 201;
727 
728   std::map<int32, int32> map1;
729   map1[key1] = value1a;
730   map1[key2] = value2a;
731 
732   map_.insert(map1.begin(), map1.end());
733   ExpectElements(map1);
734 
735   std::map<int32, int32> map2;
736   map2[key1] = value1b;
737   map2[key2] = value2b;
738 
739   map_.insert(map2.begin(), map2.end());
740   ExpectElements(map1);
741 }
742 
TEST_F(MapImplTest,InsertByInitializerList)743 TEST_F(MapImplTest, InsertByInitializerList) {
744   map_.insert({{1, 100}, {2, 200}});
745   ExpectElements({{1, 100}, {2, 200}});
746 
747   map_.insert({{2, 201}, {3, 301}});
748   ExpectElements({{1, 100}, {2, 200}, {3, 301}});
749 }
750 
TEST_F(MapImplTest,EraseSingleByKey)751 TEST_F(MapImplTest, EraseSingleByKey) {
752   int32 key = 0;
753   int32 value = 100;
754 
755   map_[key] = value;
756   ExpectSingleElement(key, value);
757 
758   // Erase an existing key.
759   EXPECT_EQ(1, map_.erase(key));
760   EXPECT_TRUE(map_.empty());
761   EXPECT_EQ(0, map_.size());
762   EXPECT_TRUE(map_.end() == map_.find(key));
763   EXPECT_TRUE(map_.begin() == map_.end());
764 
765   // Erase a non-existing key.
766   EXPECT_EQ(0, map_.erase(key));
767 }
768 
TEST_F(MapImplTest,EraseMutipleByKey)769 TEST_F(MapImplTest, EraseMutipleByKey) {
770   // erase in one specific order to trigger corner cases
771   for (int i = 0; i < 5; i++) {
772     map_[i] = i;
773   }
774 
775   map_.erase(0);
776   EXPECT_EQ(4, map_.size());
777   EXPECT_TRUE(map_.end() == map_.find(0));
778 
779   map_.erase(1);
780   EXPECT_EQ(3, map_.size());
781   EXPECT_TRUE(map_.end() == map_.find(1));
782 
783   map_.erase(3);
784   EXPECT_EQ(2, map_.size());
785   EXPECT_TRUE(map_.end() == map_.find(3));
786 
787   map_.erase(4);
788   EXPECT_EQ(1, map_.size());
789   EXPECT_TRUE(map_.end() == map_.find(4));
790 
791   map_.erase(2);
792   EXPECT_EQ(0, map_.size());
793   EXPECT_TRUE(map_.end() == map_.find(2));
794 }
795 
TEST_F(MapImplTest,EraseSingleByIterator)796 TEST_F(MapImplTest, EraseSingleByIterator) {
797   int32 key = 0;
798   int32 value = 100;
799 
800   map_[key] = value;
801   ExpectSingleElement(key, value);
802 
803   Map<int32, int32>::iterator it = map_.find(key);
804   map_.erase(it);
805   EXPECT_TRUE(map_.empty());
806   EXPECT_EQ(0, map_.size());
807   EXPECT_TRUE(map_.end() == map_.find(key));
808   EXPECT_TRUE(map_.begin() == map_.end());
809 }
810 
TEST_F(MapImplTest,ValidIteratorAfterErase)811 TEST_F(MapImplTest, ValidIteratorAfterErase) {
812   for (int i = 0; i < 10; i++) {
813     map_[i] = i;
814   }
815 
816   int count = 0;
817 
818   for (Map<int32, int32>::iterator it = map_.begin(); it != map_.end();) {
819     count++;
820     if (it->first % 2 == 1) {
821       map_.erase(it++);
822     } else {
823       ++it;
824     }
825   }
826 
827   EXPECT_EQ(10, count);
828   EXPECT_EQ(5, map_.size());
829 }
830 
TEST_F(MapImplTest,EraseByIterator)831 TEST_F(MapImplTest, EraseByIterator) {
832   int32 key1 = 0;
833   int32 key2 = 1;
834   int32 value1 = 100;
835   int32 value2 = 101;
836 
837   std::map<int32, int32> map;
838   map[key1] = value1;
839   map[key2] = value2;
840 
841   map_.insert(map.begin(), map.end());
842   ExpectElements(map);
843 
844   map_.erase(map_.begin(), map_.end());
845   EXPECT_TRUE(map_.empty());
846   EXPECT_EQ(0, map_.size());
847   EXPECT_TRUE(map_.end() == map_.find(key1));
848   EXPECT_TRUE(map_.end() == map_.find(key2));
849   EXPECT_TRUE(map_.begin() == map_.end());
850 }
851 
TEST_F(MapImplTest,Clear)852 TEST_F(MapImplTest, Clear) {
853   int32 key = 0;
854   int32 value = 100;
855 
856   map_[key] = value;
857   ExpectSingleElement(key, value);
858 
859   map_.clear();
860 
861   EXPECT_TRUE(map_.empty());
862   EXPECT_EQ(0, map_.size());
863   EXPECT_TRUE(map_.end() == map_.find(key));
864   EXPECT_TRUE(map_.begin() == map_.end());
865 }
866 
CopyConstructorHelper(Arena * arena,Map<int32,int32> * m)867 static void CopyConstructorHelper(Arena* arena, Map<int32, int32>* m) {
868   int32 key1 = 0;
869   int32 key2 = 1;
870   int32 value1 = 100;
871   int32 value2 = 101;
872 
873   std::map<int32, int32> map;
874   map[key1] = value1;
875   map[key2] = value2;
876 
877   m->insert(map.begin(), map.end());
878 
879   Map<int32, int32> other(*m);
880 
881   EXPECT_EQ(2, other.size());
882   EXPECT_EQ(value1, other.at(key1));
883   EXPECT_EQ(value2, other.at(key2));
884 }
885 
TEST_F(MapImplTest,CopyConstructorWithArena)886 TEST_F(MapImplTest, CopyConstructorWithArena) {
887   Arena a;
888   CopyConstructorHelper(&a, &map_);
889 }
890 
TEST_F(MapImplTest,CopyConstructorWithoutArena)891 TEST_F(MapImplTest, CopyConstructorWithoutArena) {
892   CopyConstructorHelper(NULL, &map_);
893 }
894 
TEST_F(MapImplTest,IterConstructor)895 TEST_F(MapImplTest, IterConstructor) {
896   int32 key1 = 0;
897   int32 key2 = 1;
898   int32 value1 = 100;
899   int32 value2 = 101;
900 
901   std::map<int32, int32> map;
902   map[key1] = value1;
903   map[key2] = value2;
904 
905   Map<int32, int32> new_map(map.begin(), map.end());
906 
907   EXPECT_EQ(2, new_map.size());
908   EXPECT_EQ(value1, new_map.at(key1));
909   EXPECT_EQ(value2, new_map.at(key2));
910 }
911 
TEST_F(MapImplTest,Assigner)912 TEST_F(MapImplTest, Assigner) {
913   int32 key1 = 0;
914   int32 key2 = 1;
915   int32 value1 = 100;
916   int32 value2 = 101;
917 
918   std::map<int32, int32> map;
919   map[key1] = value1;
920   map[key2] = value2;
921 
922   map_.insert(map.begin(), map.end());
923 
924   Map<int32, int32> other;
925   int32 key_other = 123;
926   int32 value_other = 321;
927   other[key_other] = value_other;
928   EXPECT_EQ(1, other.size());
929 
930   other = map_;
931 
932   EXPECT_EQ(2, other.size());
933   EXPECT_EQ(value1, other.at(key1));
934   EXPECT_EQ(value2, other.at(key2));
935   EXPECT_TRUE(other.find(key_other) == other.end());
936 
937   // Self assign
938   other = *&other;  // Avoid -Wself-assign.
939   EXPECT_EQ(2, other.size());
940   EXPECT_EQ(value1, other.at(key1));
941   EXPECT_EQ(value2, other.at(key2));
942 }
943 
TEST_F(MapImplTest,Rehash)944 TEST_F(MapImplTest, Rehash) {
945   const int test_size = 50;
946   std::map<int32, int32> reference_map;
947   for (int i = 0; i < test_size; i++) {
948     reference_map[i] = i;
949   }
950   for (int i = 0; i < test_size; i++) {
951     map_[i] = reference_map[i];
952     EXPECT_EQ(reference_map[i], map_[i]);
953   }
954   for (int i = 0; i < test_size; i++) {
955     map_.erase(i);
956     EXPECT_TRUE(map_.end() == map_.find(i));
957   }
958   EXPECT_TRUE(map_.empty());
959 }
960 
TEST_F(MapImplTest,EqualRange)961 TEST_F(MapImplTest, EqualRange) {
962   int key = 100, key_missing = 101;
963   map_[key] = 100;
964 
965   std::pair<Map<int32, int32>::iterator, Map<int32, int32>::iterator> range =
966       map_.equal_range(key);
967   EXPECT_TRUE(map_.find(key) == range.first);
968   EXPECT_TRUE(++map_.find(key) == range.second);
969 
970   range = map_.equal_range(key_missing);
971   EXPECT_TRUE(map_.end() == range.first);
972   EXPECT_TRUE(map_.end() == range.second);
973 
974   std::pair<Map<int32, int32>::const_iterator,
975             Map<int32, int32>::const_iterator>
976       const_range = const_map_.equal_range(key);
977   EXPECT_TRUE(const_map_.find(key) == const_range.first);
978   EXPECT_TRUE(++const_map_.find(key) == const_range.second);
979 
980   const_range = const_map_.equal_range(key_missing);
981   EXPECT_TRUE(const_map_.end() == const_range.first);
982   EXPECT_TRUE(const_map_.end() == const_range.second);
983 }
984 
TEST_F(MapImplTest,ConvertToStdMap)985 TEST_F(MapImplTest, ConvertToStdMap) {
986   map_[100] = 101;
987   std::map<int32, int32> std_map(map_.begin(), map_.end());
988   EXPECT_EQ(1, std_map.size());
989   EXPECT_EQ(101, std_map[100]);
990 }
991 
TEST_F(MapImplTest,ConvertToStdVectorOfPairs)992 TEST_F(MapImplTest, ConvertToStdVectorOfPairs) {
993   map_[100] = 101;
994   std::vector<std::pair<int32, int32> > std_vec(map_.begin(), map_.end());
995   EXPECT_EQ(1, std_vec.size());
996   EXPECT_EQ(100, std_vec[0].first);
997   EXPECT_EQ(101, std_vec[0].second);
998 }
999 
TEST_F(MapImplTest,SwapBasic)1000 TEST_F(MapImplTest, SwapBasic) {
1001   Map<int32, int32> another;
1002   map_[9398] = 41999;
1003   another[9398] = 41999;
1004   another[8070] = 42056;
1005   another.swap(map_);
1006   EXPECT_THAT(another,
1007               testing::UnorderedElementsAre(testing::Pair(9398, 41999)));
1008   EXPECT_THAT(map_, testing::UnorderedElementsAre(testing::Pair(8070, 42056),
1009                                                   testing::Pair(9398, 41999)));
1010 }
1011 
TEST_F(MapImplTest,SwapArena)1012 TEST_F(MapImplTest, SwapArena) {
1013   Arena arena1, arena2;
1014   Map<int32, int32> m1(&arena1);
1015   Map<int32, int32> m2(&arena2);
1016   map_[9398] = 41999;
1017   m1[9398] = 41999;
1018   m1[8070] = 42056;
1019   m2[10244] = 10247;
1020   m2[8070] = 42056;
1021   m1.swap(map_);
1022   EXPECT_THAT(m1, testing::UnorderedElementsAre(testing::Pair(9398, 41999)));
1023   EXPECT_THAT(map_, testing::UnorderedElementsAre(testing::Pair(8070, 42056),
1024                                                   testing::Pair(9398, 41999)));
1025   m2.swap(m1);
1026   EXPECT_THAT(m1, testing::UnorderedElementsAre(testing::Pair(8070, 42056),
1027                                                 testing::Pair(10244, 10247)));
1028   EXPECT_THAT(m2, testing::UnorderedElementsAre(testing::Pair(9398, 41999)));
1029 }
1030 
TEST_F(MapImplTest,CopyAssignMapIterator)1031 TEST_F(MapImplTest, CopyAssignMapIterator) {
1032   TestMap message;
1033   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
1034   reflection_tester.SetMapFieldsViaMapReflection(&message);
1035   MapIterator it1 = reflection_tester.MapBegin(&message, "map_int32_int32");
1036   MapIterator it2 = reflection_tester.MapEnd(&message, "map_int32_int32");
1037   it2 = it1;
1038   EXPECT_EQ(it1.GetKey().GetInt32Value(), it2.GetKey().GetInt32Value());
1039 }
1040 
TEST_F(MapImplTest,SpaceUsed)1041 TEST_F(MapImplTest, SpaceUsed) {
1042   constexpr size_t kMinCap = 8;
1043 
1044   Map<int32, int32> m;
1045   // An newly constructed map should have no space used.
1046   EXPECT_EQ(m.SpaceUsedExcludingSelfLong(), 0);
1047 
1048   size_t capacity = kMinCap;
1049   for (int i = 0; i < 100; ++i) {
1050     m[i];
1051     static constexpr double kMaxLoadFactor = .75;
1052     if (m.size() >= capacity * kMaxLoadFactor) {
1053       capacity *= 2;
1054     }
1055     EXPECT_EQ(m.SpaceUsedExcludingSelfLong(),
1056               sizeof(void*) * capacity +
1057                   m.size() * sizeof(std::pair<std::pair<int32, int32>, void*>));
1058   }
1059 
1060   // Test string, and non-scalar keys.
1061   Map<std::string, int32> m2;
1062   std::string str = "Some arbitrarily large string";
1063   m2[str] = 1;
1064   EXPECT_EQ(m2.SpaceUsedExcludingSelfLong(),
1065             sizeof(void*) * kMinCap +
1066                 sizeof(std::pair<std::pair<std::string, int32>, void*>) +
1067                 internal::StringSpaceUsedExcludingSelfLong(str));
1068 
1069   // Test messages, and non-scalar values.
1070   Map<int32, TestAllTypes> m3;
1071   m3[0].set_optional_string(str);
1072   EXPECT_EQ(m3.SpaceUsedExcludingSelfLong(),
1073             sizeof(void*) * kMinCap +
1074                 sizeof(std::pair<std::pair<int32, TestAllTypes>, void*>) +
1075                 m3[0].SpaceUsedLong() - sizeof(m3[0]));
1076 }
1077 
1078 // Attempts to verify that a map with keys a and b has a random ordering. This
1079 // function returns true if it succeeds in observing both possible orderings.
MapOrderingIsRandom(int a,int b)1080 bool MapOrderingIsRandom(int a, int b) {
1081   bool saw_a_first = false;
1082   bool saw_b_first = false;
1083 
1084   for (int i = 0; i < 50; ++i) {
1085     Map<int32, int32> m;
1086     m[a] = 0;
1087     m[b] = 0;
1088     int32 first_element = m.begin()->first;
1089     if (first_element == a) saw_a_first = true;
1090     if (first_element == b) saw_b_first = true;
1091     if (saw_a_first && saw_b_first) {
1092       return true;
1093     }
1094   }
1095 
1096   return false;
1097 }
1098 
1099 // This test verifies that the iteration order is reasonably random even for
1100 // small maps. Currently we only have sufficient randomness for debug builds and
1101 // builds where we can use the RDTSC instruction, so we only test for those
1102 // builds.
1103 #if defined(__x86_64__) && defined(__GNUC__) && \
1104     !defined(GOOGLE_PROTOBUF_NO_RDTSC)
TEST_F(MapImplTest,RandomOrdering)1105 TEST_F(MapImplTest, RandomOrdering) {
1106   for (int i = 0; i < 10; ++i) {
1107     for (int j = i + 1; j < 10; ++j) {
1108       EXPECT_TRUE(MapOrderingIsRandom(i, j))
1109           << "Map with keys " << i << " and " << j
1110           << " has deterministic ordering";
1111     }
1112   }
1113 }
1114 #endif
1115 
1116 template <typename Key>
TestTransparent(const Key & key,const Key & miss_key)1117 void TestTransparent(const Key& key, const Key& miss_key) {
1118   Map<std::string, int> m;
1119   const auto& cm = m;
1120 
1121   m.insert({"ABC", 1});
1122 
1123   const auto abc_it = m.begin();
1124 
1125   m.insert({"DEF", 2});
1126 
1127   using testing::Pair;
1128   using testing::UnorderedElementsAre;
1129 
1130   EXPECT_EQ(m.at(key), 1);
1131   EXPECT_EQ(cm.at(key), 1);
1132 
1133 #ifdef PROTOBUF_HAS_DEATH_TEST
1134   EXPECT_DEATH(m.at(miss_key), "");
1135   EXPECT_DEATH(cm.at(miss_key), "");
1136 #endif  // PROTOBUF_HAS_DEATH_TEST
1137 
1138   EXPECT_EQ(m.count(key), 1);
1139   EXPECT_EQ(cm.count(key), 1);
1140   EXPECT_EQ(m.count(miss_key), 0);
1141   EXPECT_EQ(cm.count(miss_key), 0);
1142 
1143   EXPECT_EQ(m.find(key), abc_it);
1144   EXPECT_EQ(cm.find(key), abc_it);
1145   EXPECT_EQ(m.find(miss_key), m.end());
1146   EXPECT_EQ(cm.find(miss_key), cm.end());
1147 
1148   EXPECT_TRUE(m.contains(key));
1149   EXPECT_TRUE(cm.contains(key));
1150   EXPECT_FALSE(m.contains(miss_key));
1151   EXPECT_FALSE(cm.contains(miss_key));
1152 
1153   EXPECT_THAT(m.equal_range(key), Pair(abc_it, std::next(abc_it)));
1154   EXPECT_THAT(cm.equal_range(key), Pair(abc_it, std::next(abc_it)));
1155   EXPECT_THAT(m.equal_range(miss_key), Pair(m.end(), m.end()));
1156   EXPECT_THAT(cm.equal_range(miss_key), Pair(m.end(), m.end()));
1157 
1158   EXPECT_THAT(m, UnorderedElementsAre(Pair("ABC", 1), Pair("DEF", 2)));
1159   EXPECT_EQ(m.erase(key), 1);
1160   EXPECT_THAT(m, UnorderedElementsAre(Pair("DEF", 2)));
1161   EXPECT_EQ(m.erase(key), 0);
1162   EXPECT_EQ(m.erase(miss_key), 0);
1163   EXPECT_THAT(m, UnorderedElementsAre(Pair("DEF", 2)));
1164 
1165   m[key];
1166   EXPECT_THAT(m, UnorderedElementsAre(Pair("ABC", 0), Pair("DEF", 2)));
1167   m[key] = 1;
1168   EXPECT_THAT(m, UnorderedElementsAre(Pair("ABC", 1), Pair("DEF", 2)));
1169 }
1170 
TEST_F(MapImplTest,TransparentLookupForString)1171 TEST_F(MapImplTest, TransparentLookupForString) {
1172   TestTransparent("ABC", "LKJ");
1173   TestTransparent(std::string("ABC"), std::string("LKJ"));
1174 #if defined(__cpp_lib_string_view)
1175   TestTransparent(std::string_view("ABC"), std::string_view("LKJ"));
1176 #endif  // defined(__cpp_lib_string_view)
1177 
1178   // std::reference_wrapper
1179   std::string abc = "ABC", lkj = "LKJ";
1180   TestTransparent(std::ref(abc), std::ref(lkj));
1181   TestTransparent(std::cref(abc), std::cref(lkj));
1182 }
1183 
TEST_F(MapImplTest,ConstInit)1184 TEST_F(MapImplTest, ConstInit) {
1185   PROTOBUF_CONSTINIT static Map<int, int> map;  // NOLINT
1186   EXPECT_TRUE(map.empty());
1187 }
1188 
1189 // Map Field Reflection Test ========================================
1190 
Func(int i,int j)1191 static int Func(int i, int j) { return i * j; }
1192 
StrFunc(int i,int j)1193 static std::string StrFunc(int i, int j) { return StrCat(Func(i, j)); }
1194 
Int(const std::string & value)1195 static int Int(const std::string& value) {
1196   int result = 0;
1197   std::istringstream(value) >> result;
1198   return result;
1199 }
1200 
1201 }  // namespace
1202 
1203 // This class is a friend, so no anonymous namespace.
1204 class MapFieldReflectionTest : public testing::Test {
1205  protected:
1206   typedef FieldDescriptor FD;
1207 
MapSize(const Reflection * reflection,const FieldDescriptor * field,const Message & message)1208   int MapSize(const Reflection* reflection, const FieldDescriptor* field,
1209               const Message& message) {
1210     return reflection->MapSize(message, field);
1211   }
1212 };
1213 
1214 namespace {
1215 
TEST_F(MapFieldReflectionTest,RegularFields)1216 TEST_F(MapFieldReflectionTest, RegularFields) {
1217   TestMap message;
1218   const Reflection* refl = message.GetReflection();
1219   const Descriptor* desc = message.GetDescriptor();
1220 
1221   Map<int32, int32>* map_int32_int32 = message.mutable_map_int32_int32();
1222   Map<int32, double>* map_int32_double = message.mutable_map_int32_double();
1223   Map<std::string, std::string>* map_string_string =
1224       message.mutable_map_string_string();
1225   Map<int32, ForeignMessage>* map_int32_foreign_message =
1226       message.mutable_map_int32_foreign_message();
1227 
1228   for (int i = 0; i < 10; ++i) {
1229     (*map_int32_int32)[i] = Func(i, 1);
1230     (*map_int32_double)[i] = Func(i, 2);
1231     (*map_string_string)[StrFunc(i, 1)] = StrFunc(i, 5);
1232     (*map_int32_foreign_message)[i].set_c(Func(i, 6));
1233   }
1234 
1235   // Get FieldDescriptors for all the fields of interest.
1236   const FieldDescriptor* fd_map_int32_int32 =
1237       desc->FindFieldByName("map_int32_int32");
1238   const FieldDescriptor* fd_map_int32_double =
1239       desc->FindFieldByName("map_int32_double");
1240   const FieldDescriptor* fd_map_string_string =
1241       desc->FindFieldByName("map_string_string");
1242   const FieldDescriptor* fd_map_int32_foreign_message =
1243       desc->FindFieldByName("map_int32_foreign_message");
1244 
1245   const FieldDescriptor* fd_map_int32_in32_key =
1246       fd_map_int32_int32->message_type()->FindFieldByName("key");
1247   const FieldDescriptor* fd_map_int32_in32_value =
1248       fd_map_int32_int32->message_type()->FindFieldByName("value");
1249   const FieldDescriptor* fd_map_int32_double_key =
1250       fd_map_int32_double->message_type()->FindFieldByName("key");
1251   const FieldDescriptor* fd_map_int32_double_value =
1252       fd_map_int32_double->message_type()->FindFieldByName("value");
1253   const FieldDescriptor* fd_map_string_string_key =
1254       fd_map_string_string->message_type()->FindFieldByName("key");
1255   const FieldDescriptor* fd_map_string_string_value =
1256       fd_map_string_string->message_type()->FindFieldByName("value");
1257   const FieldDescriptor* fd_map_int32_foreign_message_key =
1258       fd_map_int32_foreign_message->message_type()->FindFieldByName("key");
1259   const FieldDescriptor* fd_map_int32_foreign_message_value =
1260       fd_map_int32_foreign_message->message_type()->FindFieldByName("value");
1261 
1262   // Get RepeatedPtrField objects for all fields of interest.
1263   const RepeatedPtrField<Message>& mf_int32_int32 =
1264       refl->GetRepeatedPtrField<Message>(message, fd_map_int32_int32);
1265   const RepeatedPtrField<Message>& mf_int32_double =
1266       refl->GetRepeatedPtrField<Message>(message, fd_map_int32_double);
1267   const RepeatedPtrField<Message>& mf_string_string =
1268       refl->GetRepeatedPtrField<Message>(message, fd_map_string_string);
1269   const RepeatedPtrField<Message>& mf_int32_foreign_message =
1270       refl->GetRepeatedPtrField<Message>(message, fd_map_int32_foreign_message);
1271 
1272   // Get mutable RepeatedPtrField objects for all fields of interest.
1273   RepeatedPtrField<Message>* mmf_int32_int32 =
1274       refl->MutableRepeatedPtrField<Message>(&message, fd_map_int32_int32);
1275   RepeatedPtrField<Message>* mmf_int32_double =
1276       refl->MutableRepeatedPtrField<Message>(&message, fd_map_int32_double);
1277   RepeatedPtrField<Message>* mmf_string_string =
1278       refl->MutableRepeatedPtrField<Message>(&message, fd_map_string_string);
1279   RepeatedPtrField<Message>* mmf_int32_foreign_message =
1280       refl->MutableRepeatedPtrField<Message>(&message,
1281                                              fd_map_int32_foreign_message);
1282 
1283   // Make sure we can do gets through the RepeatedPtrField objects.
1284   for (int i = 0; i < 10; ++i) {
1285     {
1286       // Check gets through const objects.
1287       const Message& message_int32_int32 = mf_int32_int32.Get(i);
1288       int32 key_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1289           message_int32_int32, fd_map_int32_in32_key);
1290       int32 value_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1291           message_int32_int32, fd_map_int32_in32_value);
1292       EXPECT_EQ(value_int32_int32, Func(key_int32_int32, 1));
1293 
1294       const Message& message_int32_double = mf_int32_double.Get(i);
1295       int32 key_int32_double = message_int32_double.GetReflection()->GetInt32(
1296           message_int32_double, fd_map_int32_double_key);
1297       double value_int32_double =
1298           message_int32_double.GetReflection()->GetDouble(
1299               message_int32_double, fd_map_int32_double_value);
1300       EXPECT_EQ(value_int32_double, Func(key_int32_double, 2));
1301 
1302       const Message& message_string_string = mf_string_string.Get(i);
1303       std::string key_string_string =
1304           message_string_string.GetReflection()->GetString(
1305               message_string_string, fd_map_string_string_key);
1306       std::string value_string_string =
1307           message_string_string.GetReflection()->GetString(
1308               message_string_string, fd_map_string_string_value);
1309       EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5));
1310 
1311       const Message& message_int32_message = mf_int32_foreign_message.Get(i);
1312       int32 key_int32_message = message_int32_message.GetReflection()->GetInt32(
1313           message_int32_message, fd_map_int32_foreign_message_key);
1314       const ForeignMessage& value_int32_message =
1315           down_cast<const ForeignMessage&>(
1316               message_int32_message.GetReflection()->GetMessage(
1317                   message_int32_message, fd_map_int32_foreign_message_value));
1318       EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6));
1319     }
1320 
1321     {
1322       // Check gets through mutable objects.
1323       const Message& message_int32_int32 = mmf_int32_int32->Get(i);
1324       int32 key_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1325           message_int32_int32, fd_map_int32_in32_key);
1326       int32 value_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1327           message_int32_int32, fd_map_int32_in32_value);
1328       EXPECT_EQ(value_int32_int32, Func(key_int32_int32, 1));
1329 
1330       const Message& message_int32_double = mmf_int32_double->Get(i);
1331       int32 key_int32_double = message_int32_double.GetReflection()->GetInt32(
1332           message_int32_double, fd_map_int32_double_key);
1333       double value_int32_double =
1334           message_int32_double.GetReflection()->GetDouble(
1335               message_int32_double, fd_map_int32_double_value);
1336       EXPECT_EQ(value_int32_double, Func(key_int32_double, 2));
1337 
1338       const Message& message_string_string = mmf_string_string->Get(i);
1339       std::string key_string_string =
1340           message_string_string.GetReflection()->GetString(
1341               message_string_string, fd_map_string_string_key);
1342       std::string value_string_string =
1343           message_string_string.GetReflection()->GetString(
1344               message_string_string, fd_map_string_string_value);
1345       EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5));
1346 
1347       const Message& message_int32_message = mmf_int32_foreign_message->Get(i);
1348       int32 key_int32_message = message_int32_message.GetReflection()->GetInt32(
1349           message_int32_message, fd_map_int32_foreign_message_key);
1350       const ForeignMessage& value_int32_message =
1351           down_cast<const ForeignMessage&>(
1352               message_int32_message.GetReflection()->GetMessage(
1353                   message_int32_message, fd_map_int32_foreign_message_value));
1354       EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6));
1355     }
1356   }
1357 
1358   // Do sets through the RepeatedPtrField objects.
1359   for (int i = 0; i < 10; i++) {
1360     {
1361       Message* message_int32_int32 = mmf_int32_int32->Mutable(i);
1362       int32 key_int32_int32 = message_int32_int32->GetReflection()->GetInt32(
1363           *message_int32_int32, fd_map_int32_in32_key);
1364       message_int32_int32->GetReflection()->SetInt32(message_int32_int32,
1365                                                      fd_map_int32_in32_value,
1366                                                      Func(key_int32_int32, -1));
1367 
1368       Message* message_int32_double = mmf_int32_double->Mutable(i);
1369       int32 key_int32_double = message_int32_double->GetReflection()->GetInt32(
1370           *message_int32_double, fd_map_int32_double_key);
1371       message_int32_double->GetReflection()->SetDouble(
1372           message_int32_double, fd_map_int32_double_value,
1373           Func(key_int32_double, -2));
1374 
1375       Message* message_string_string = mmf_string_string->Mutable(i);
1376       std::string key_string_string =
1377           message_string_string->GetReflection()->GetString(
1378               *message_string_string, fd_map_string_string_key);
1379       message_string_string->GetReflection()->SetString(
1380           message_string_string, fd_map_string_string_value,
1381           StrFunc(Int(key_string_string), -5));
1382 
1383       Message* message_int32_message = mmf_int32_foreign_message->Mutable(i);
1384       int32 key_int32_message =
1385           message_int32_message->GetReflection()->GetInt32(
1386               *message_int32_message, fd_map_int32_foreign_message_key);
1387       ForeignMessage* value_int32_message = down_cast<ForeignMessage*>(
1388           message_int32_message->GetReflection()->MutableMessage(
1389               message_int32_message, fd_map_int32_foreign_message_value));
1390       value_int32_message->set_c(Func(key_int32_message, -6));
1391     }
1392   }
1393 
1394   // Check gets through mutable objects.
1395   for (int i = 0; i < 10; i++) {
1396     EXPECT_EQ(Func(i, -1), message.map_int32_int32().at(i));
1397     EXPECT_EQ(Func(i, -2), message.map_int32_double().at(i));
1398     EXPECT_EQ(StrFunc(i, -5), message.map_string_string().at(StrFunc(i, 1)));
1399     EXPECT_EQ(Func(i, -6), message.map_int32_foreign_message().at(i).c());
1400   }
1401 }
1402 
TEST_F(MapFieldReflectionTest,RepeatedFieldRefForRegularFields)1403 TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) {
1404   TestMap message;
1405   const Reflection* refl = message.GetReflection();
1406   const Descriptor* desc = message.GetDescriptor();
1407 
1408   Map<int32, int32>* map_int32_int32 = message.mutable_map_int32_int32();
1409   Map<int32, double>* map_int32_double = message.mutable_map_int32_double();
1410   Map<std::string, std::string>* map_string_string =
1411       message.mutable_map_string_string();
1412   Map<int32, ForeignMessage>* map_int32_foreign_message =
1413       message.mutable_map_int32_foreign_message();
1414 
1415   for (int i = 0; i < 10; ++i) {
1416     (*map_int32_int32)[i] = Func(i, 1);
1417     (*map_int32_double)[i] = Func(i, 2);
1418     (*map_string_string)[StrFunc(i, 1)] = StrFunc(i, 5);
1419     (*map_int32_foreign_message)[i].set_c(Func(i, 6));
1420   }
1421 
1422   // Get FieldDescriptors for all the fields of interest.
1423   const FieldDescriptor* fd_map_int32_int32 =
1424       desc->FindFieldByName("map_int32_int32");
1425   const FieldDescriptor* fd_map_int32_double =
1426       desc->FindFieldByName("map_int32_double");
1427   const FieldDescriptor* fd_map_string_string =
1428       desc->FindFieldByName("map_string_string");
1429   const FieldDescriptor* fd_map_int32_foreign_message =
1430       desc->FindFieldByName("map_int32_foreign_message");
1431 
1432   const FieldDescriptor* fd_map_int32_in32_key =
1433       fd_map_int32_int32->message_type()->FindFieldByName("key");
1434   const FieldDescriptor* fd_map_int32_in32_value =
1435       fd_map_int32_int32->message_type()->FindFieldByName("value");
1436   const FieldDescriptor* fd_map_int32_double_key =
1437       fd_map_int32_double->message_type()->FindFieldByName("key");
1438   const FieldDescriptor* fd_map_int32_double_value =
1439       fd_map_int32_double->message_type()->FindFieldByName("value");
1440   const FieldDescriptor* fd_map_string_string_key =
1441       fd_map_string_string->message_type()->FindFieldByName("key");
1442   const FieldDescriptor* fd_map_string_string_value =
1443       fd_map_string_string->message_type()->FindFieldByName("value");
1444   const FieldDescriptor* fd_map_int32_foreign_message_key =
1445       fd_map_int32_foreign_message->message_type()->FindFieldByName("key");
1446   const FieldDescriptor* fd_map_int32_foreign_message_value =
1447       fd_map_int32_foreign_message->message_type()->FindFieldByName("value");
1448 
1449   // Get RepeatedFieldRef objects for all fields of interest.
1450   const RepeatedFieldRef<Message> mf_int32_int32 =
1451       refl->GetRepeatedFieldRef<Message>(message, fd_map_int32_int32);
1452   const RepeatedFieldRef<Message> mf_int32_double =
1453       refl->GetRepeatedFieldRef<Message>(message, fd_map_int32_double);
1454   const RepeatedFieldRef<Message> mf_string_string =
1455       refl->GetRepeatedFieldRef<Message>(message, fd_map_string_string);
1456   const RepeatedFieldRef<Message> mf_int32_foreign_message =
1457       refl->GetRepeatedFieldRef<Message>(message, fd_map_int32_foreign_message);
1458 
1459   // Get mutable RepeatedFieldRef objects for all fields of interest.
1460   const MutableRepeatedFieldRef<Message> mmf_int32_int32 =
1461       refl->GetMutableRepeatedFieldRef<Message>(&message, fd_map_int32_int32);
1462   const MutableRepeatedFieldRef<Message> mmf_int32_double =
1463       refl->GetMutableRepeatedFieldRef<Message>(&message, fd_map_int32_double);
1464   const MutableRepeatedFieldRef<Message> mmf_string_string =
1465       refl->GetMutableRepeatedFieldRef<Message>(&message, fd_map_string_string);
1466   const MutableRepeatedFieldRef<Message> mmf_int32_foreign_message =
1467       refl->GetMutableRepeatedFieldRef<Message>(&message,
1468                                                 fd_map_int32_foreign_message);
1469 
1470   // Get entry default instances
1471   std::unique_ptr<Message> entry_int32_int32(
1472       MessageFactory::generated_factory()
1473           ->GetPrototype(fd_map_int32_int32->message_type())
1474           ->New());
1475   std::unique_ptr<Message> entry_int32_double(
1476       MessageFactory::generated_factory()
1477           ->GetPrototype(fd_map_int32_double->message_type())
1478           ->New());
1479   std::unique_ptr<Message> entry_string_string(
1480       MessageFactory::generated_factory()
1481           ->GetPrototype(fd_map_string_string->message_type())
1482           ->New());
1483   std::unique_ptr<Message> entry_int32_foreign_message(
1484       MessageFactory::generated_factory()
1485           ->GetPrototype(fd_map_int32_foreign_message->message_type())
1486           ->New());
1487 
1488   EXPECT_EQ(10, mf_int32_int32.size());
1489   EXPECT_EQ(10, mmf_int32_int32.size());
1490   EXPECT_EQ(10, mf_int32_double.size());
1491   EXPECT_EQ(10, mmf_int32_double.size());
1492   EXPECT_EQ(10, mf_string_string.size());
1493   EXPECT_EQ(10, mmf_string_string.size());
1494   EXPECT_EQ(10, mf_int32_foreign_message.size());
1495   EXPECT_EQ(10, mmf_int32_foreign_message.size());
1496 
1497   EXPECT_FALSE(mf_int32_int32.empty());
1498   EXPECT_FALSE(mmf_int32_int32.empty());
1499   EXPECT_FALSE(mf_int32_double.empty());
1500   EXPECT_FALSE(mmf_int32_double.empty());
1501   EXPECT_FALSE(mf_string_string.empty());
1502   EXPECT_FALSE(mmf_string_string.empty());
1503   EXPECT_FALSE(mf_int32_foreign_message.empty());
1504   EXPECT_FALSE(mmf_int32_foreign_message.empty());
1505 
1506   // Make sure we can do gets through the RepeatedFieldRef objects.
1507   for (int i = 0; i < 10; ++i) {
1508     {
1509       // Check gets through const objects.
1510       const Message& message_int32_int32 =
1511           mf_int32_int32.Get(i, entry_int32_int32.get());
1512       int32 key_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1513           message_int32_int32, fd_map_int32_in32_key);
1514       int32 value_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1515           message_int32_int32, fd_map_int32_in32_value);
1516       EXPECT_EQ(value_int32_int32, Func(key_int32_int32, 1));
1517 
1518       const Message& message_int32_double =
1519           mf_int32_double.Get(i, entry_int32_double.get());
1520       int32 key_int32_double = message_int32_double.GetReflection()->GetInt32(
1521           message_int32_double, fd_map_int32_double_key);
1522       double value_int32_double =
1523           message_int32_double.GetReflection()->GetDouble(
1524               message_int32_double, fd_map_int32_double_value);
1525       EXPECT_EQ(value_int32_double, Func(key_int32_double, 2));
1526 
1527       const Message& message_string_string =
1528           mf_string_string.Get(i, entry_string_string.get());
1529       std::string key_string_string =
1530           message_string_string.GetReflection()->GetString(
1531               message_string_string, fd_map_string_string_key);
1532       std::string value_string_string =
1533           message_string_string.GetReflection()->GetString(
1534               message_string_string, fd_map_string_string_value);
1535       EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5));
1536 
1537       const Message& message_int32_message =
1538           mf_int32_foreign_message.Get(i, entry_int32_foreign_message.get());
1539       int32 key_int32_message = message_int32_message.GetReflection()->GetInt32(
1540           message_int32_message, fd_map_int32_foreign_message_key);
1541       const ForeignMessage& value_int32_message =
1542           down_cast<const ForeignMessage&>(
1543               message_int32_message.GetReflection()->GetMessage(
1544                   message_int32_message, fd_map_int32_foreign_message_value));
1545       EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6));
1546     }
1547 
1548     {
1549       // Check gets through mutable objects.
1550       const Message& message_int32_int32 =
1551           mmf_int32_int32.Get(i, entry_int32_int32.get());
1552       int32 key_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1553           message_int32_int32, fd_map_int32_in32_key);
1554       int32 value_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1555           message_int32_int32, fd_map_int32_in32_value);
1556       EXPECT_EQ(value_int32_int32, Func(key_int32_int32, 1));
1557 
1558       const Message& message_int32_double =
1559           mmf_int32_double.Get(i, entry_int32_double.get());
1560       int32 key_int32_double = message_int32_double.GetReflection()->GetInt32(
1561           message_int32_double, fd_map_int32_double_key);
1562       double value_int32_double =
1563           message_int32_double.GetReflection()->GetDouble(
1564               message_int32_double, fd_map_int32_double_value);
1565       EXPECT_EQ(value_int32_double, Func(key_int32_double, 2));
1566 
1567       const Message& message_string_string =
1568           mmf_string_string.Get(i, entry_string_string.get());
1569       std::string key_string_string =
1570           message_string_string.GetReflection()->GetString(
1571               message_string_string, fd_map_string_string_key);
1572       std::string value_string_string =
1573           message_string_string.GetReflection()->GetString(
1574               message_string_string, fd_map_string_string_value);
1575       EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5));
1576 
1577       const Message& message_int32_message =
1578           mmf_int32_foreign_message.Get(i, entry_int32_foreign_message.get());
1579       int32 key_int32_message = message_int32_message.GetReflection()->GetInt32(
1580           message_int32_message, fd_map_int32_foreign_message_key);
1581       const ForeignMessage& value_int32_message =
1582           down_cast<const ForeignMessage&>(
1583               message_int32_message.GetReflection()->GetMessage(
1584                   message_int32_message, fd_map_int32_foreign_message_value));
1585       EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6));
1586     }
1587   }
1588 
1589   // Make sure we can do sets through the RepeatedFieldRef objects.
1590   for (int i = 0; i < 10; i++) {
1591     const Message& message_int32_int32 =
1592         mmf_int32_int32.Get(i, entry_int32_int32.get());
1593     int key = message_int32_int32.GetReflection()->GetInt32(
1594         message_int32_int32, fd_map_int32_in32_key);
1595 
1596     entry_int32_int32->GetReflection()->SetInt32(
1597         entry_int32_int32.get(), fd_map_int32_int32->message_type()->field(0),
1598         key);
1599     entry_int32_int32->GetReflection()->SetInt32(
1600         entry_int32_int32.get(), fd_map_int32_int32->message_type()->field(1),
1601         Func(key, -1));
1602     entry_int32_double->GetReflection()->SetInt32(
1603         entry_int32_double.get(), fd_map_int32_double->message_type()->field(0),
1604         key);
1605     entry_int32_double->GetReflection()->SetDouble(
1606         entry_int32_double.get(), fd_map_int32_double->message_type()->field(1),
1607         Func(key, -2));
1608     entry_string_string->GetReflection()->SetString(
1609         entry_string_string.get(),
1610         fd_map_string_string->message_type()->field(0), StrFunc(key, 1));
1611     entry_string_string->GetReflection()->SetString(
1612         entry_string_string.get(),
1613         fd_map_string_string->message_type()->field(1), StrFunc(key, -5));
1614     entry_int32_foreign_message->GetReflection()->SetInt32(
1615         entry_int32_foreign_message.get(),
1616         fd_map_int32_foreign_message->message_type()->field(0), key);
1617     Message* value_message =
1618         entry_int32_foreign_message->GetReflection()->MutableMessage(
1619             entry_int32_foreign_message.get(),
1620             fd_map_int32_foreign_message->message_type()->field(1));
1621     value_message->GetReflection()->SetInt32(
1622         value_message, value_message->GetDescriptor()->FindFieldByName("c"),
1623         Func(key, -6));
1624 
1625     mmf_int32_int32.Set(i, *entry_int32_int32);
1626     mmf_int32_double.Set(i, *entry_int32_double);
1627     mmf_string_string.Set(i, *entry_string_string);
1628     mmf_int32_foreign_message.Set(i, *entry_int32_foreign_message);
1629   }
1630 
1631   for (int i = 0; i < 10; i++) {
1632     EXPECT_EQ(Func(i, -1), message.map_int32_int32().at(i));
1633     EXPECT_EQ(Func(i, -2), message.map_int32_double().at(i));
1634     EXPECT_EQ(StrFunc(i, -5), message.map_string_string().at(StrFunc(i, 1)));
1635     EXPECT_EQ(Func(i, -6), message.map_int32_foreign_message().at(i).c());
1636   }
1637 
1638   // Test iterators.
1639   {
1640     int index = 0;
1641     std::unordered_map<int32, int32> result;
1642     for (RepeatedFieldRef<Message>::iterator it = mf_int32_int32.begin();
1643          it != mf_int32_int32.end(); ++it) {
1644       const Message& message = *it;
1645       int32 key =
1646           message.GetReflection()->GetInt32(message, fd_map_int32_in32_key);
1647       int32 value =
1648           message.GetReflection()->GetInt32(message, fd_map_int32_in32_value);
1649       result[key] = value;
1650       ++index;
1651     }
1652     EXPECT_EQ(10, index);
1653     for (std::unordered_map<int32, int32>::const_iterator it = result.begin();
1654          it != result.end(); ++it) {
1655       EXPECT_EQ(message.map_int32_int32().at(it->first), it->second);
1656     }
1657   }
1658 
1659   {
1660     int index = 0;
1661     std::unordered_map<int32, double> result;
1662     for (RepeatedFieldRef<Message>::iterator it = mf_int32_double.begin();
1663          it != mf_int32_double.end(); ++it) {
1664       const Message& message = *it;
1665       int32 key =
1666           message.GetReflection()->GetInt32(message, fd_map_int32_double_key);
1667       double value = message.GetReflection()->GetDouble(
1668           message, fd_map_int32_double_value);
1669       result[key] = value;
1670       ++index;
1671     }
1672     EXPECT_EQ(10, index);
1673     for (std::unordered_map<int32, double>::const_iterator it = result.begin();
1674          it != result.end(); ++it) {
1675       EXPECT_EQ(message.map_int32_double().at(it->first), it->second);
1676     }
1677   }
1678 
1679   {
1680     int index = 0;
1681     std::unordered_map<std::string, std::string> result;
1682     for (RepeatedFieldRef<Message>::iterator it = mf_string_string.begin();
1683          it != mf_string_string.end(); ++it) {
1684       const Message& message = *it;
1685       std::string key =
1686           message.GetReflection()->GetString(message, fd_map_string_string_key);
1687       std::string value = message.GetReflection()->GetString(
1688           message, fd_map_string_string_value);
1689       result[key] = value;
1690       ++index;
1691     }
1692     EXPECT_EQ(10, index);
1693     for (std::unordered_map<std::string, std::string>::const_iterator it =
1694              result.begin();
1695          it != result.end(); ++it) {
1696       EXPECT_EQ(message.map_string_string().at(it->first), it->second);
1697     }
1698   }
1699 
1700   {
1701     int index = 0;
1702     std::map<int32, ForeignMessage> result;
1703     for (RepeatedFieldRef<Message>::iterator it =
1704              mf_int32_foreign_message.begin();
1705          it != mf_int32_foreign_message.end(); ++it) {
1706       const Message& message = *it;
1707       int32 key = message.GetReflection()->GetInt32(
1708           message, fd_map_int32_foreign_message_key);
1709       const ForeignMessage& sub_message =
1710           down_cast<const ForeignMessage&>(message.GetReflection()->GetMessage(
1711               message, fd_map_int32_foreign_message_value));
1712       result[key].MergeFrom(sub_message);
1713       ++index;
1714     }
1715     EXPECT_EQ(10, index);
1716     for (std::map<int32, ForeignMessage>::const_iterator it = result.begin();
1717          it != result.end(); ++it) {
1718       EXPECT_EQ(message.map_int32_foreign_message().at(it->first).c(),
1719                 it->second.c());
1720     }
1721   }
1722 
1723   // Test MutableRepeatedFieldRef::Add()
1724   entry_int32_int32->GetReflection()->SetInt32(
1725       entry_int32_int32.get(), fd_map_int32_int32->message_type()->field(0),
1726       4321);
1727   entry_int32_int32->GetReflection()->SetInt32(
1728       entry_int32_int32.get(), fd_map_int32_int32->message_type()->field(1),
1729       1234);
1730   mmf_int32_int32.Add(*entry_int32_int32);
1731   EXPECT_EQ(1234, message.map_int32_int32().at(4321));
1732 
1733   entry_int32_double->GetReflection()->SetInt32(
1734       entry_int32_double.get(), fd_map_int32_double->message_type()->field(0),
1735       4321);
1736   entry_int32_double->GetReflection()->SetDouble(
1737       entry_int32_double.get(), fd_map_int32_double->message_type()->field(1),
1738       1234.0);
1739   mmf_int32_double.Add(*entry_int32_double);
1740   EXPECT_EQ(1234.0, message.map_int32_double().at(4321));
1741 
1742   entry_string_string->GetReflection()->SetString(
1743       entry_string_string.get(), fd_map_string_string->message_type()->field(0),
1744       "4321");
1745   entry_string_string->GetReflection()->SetString(
1746       entry_string_string.get(), fd_map_string_string->message_type()->field(1),
1747       "1234");
1748   mmf_string_string.Add(*entry_string_string);
1749   EXPECT_EQ("1234", message.map_string_string().at("4321"));
1750 
1751   entry_int32_foreign_message->GetReflection()->SetInt32(
1752       entry_int32_foreign_message.get(),
1753       fd_map_int32_foreign_message->message_type()->field(0), 4321);
1754   Message* value_message =
1755       entry_int32_foreign_message->GetReflection()->MutableMessage(
1756           entry_int32_foreign_message.get(),
1757           fd_map_int32_foreign_message->message_type()->field(1));
1758   ForeignMessage foreign_message;
1759   foreign_message.set_c(1234);
1760   value_message->CopyFrom(foreign_message);
1761 
1762   mmf_int32_foreign_message.Add(*entry_int32_foreign_message);
1763   EXPECT_EQ(1234, message.map_int32_foreign_message().at(4321).c());
1764 
1765   // Test Reflection::AddAllocatedMessage
1766   Message* free_entry_string_string =
1767       MessageFactory::generated_factory()
1768           ->GetPrototype(fd_map_string_string->message_type())
1769           ->New();
1770   entry_string_string->GetReflection()->SetString(
1771       free_entry_string_string, fd_map_string_string->message_type()->field(0),
1772       "4321");
1773   entry_string_string->GetReflection()->SetString(
1774       free_entry_string_string, fd_map_string_string->message_type()->field(1),
1775       "1234");
1776   refl->AddAllocatedMessage(&message, fd_map_string_string,
1777                             free_entry_string_string);
1778 
1779   // Test MutableRepeatedFieldRef::RemoveLast()
1780   mmf_int32_int32.RemoveLast();
1781   mmf_int32_double.RemoveLast();
1782   mmf_string_string.RemoveLast();
1783   mmf_int32_foreign_message.RemoveLast();
1784   EXPECT_EQ(10, message.map_int32_int32().size());
1785   EXPECT_EQ(10, message.map_int32_double().size());
1786   EXPECT_EQ(11, message.map_string_string().size());
1787   EXPECT_EQ(10, message.map_int32_foreign_message().size());
1788 
1789   // Test MutableRepeatedFieldRef::SwapElements()
1790   {
1791     const Message& message0a = mmf_int32_int32.Get(0, entry_int32_int32.get());
1792     int32 int32_value0a =
1793         message0a.GetReflection()->GetInt32(message0a, fd_map_int32_in32_value);
1794     const Message& message9a = mmf_int32_int32.Get(9, entry_int32_int32.get());
1795     int32 int32_value9a =
1796         message9a.GetReflection()->GetInt32(message9a, fd_map_int32_in32_value);
1797 
1798     mmf_int32_int32.SwapElements(0, 9);
1799 
1800     const Message& message0b = mmf_int32_int32.Get(0, entry_int32_int32.get());
1801     int32 int32_value0b =
1802         message0b.GetReflection()->GetInt32(message0b, fd_map_int32_in32_value);
1803     const Message& message9b = mmf_int32_int32.Get(9, entry_int32_int32.get());
1804     int32 int32_value9b =
1805         message9b.GetReflection()->GetInt32(message9b, fd_map_int32_in32_value);
1806 
1807     EXPECT_EQ(int32_value9a, int32_value0b);
1808     EXPECT_EQ(int32_value0a, int32_value9b);
1809   }
1810 
1811   {
1812     const Message& message0a =
1813         mmf_int32_double.Get(0, entry_int32_double.get());
1814     double double_value0a = message0a.GetReflection()->GetDouble(
1815         message0a, fd_map_int32_double_value);
1816     const Message& message9a =
1817         mmf_int32_double.Get(9, entry_int32_double.get());
1818     double double_value9a = message9a.GetReflection()->GetDouble(
1819         message9a, fd_map_int32_double_value);
1820 
1821     mmf_int32_double.SwapElements(0, 9);
1822 
1823     const Message& message0b =
1824         mmf_int32_double.Get(0, entry_int32_double.get());
1825     double double_value0b = message0b.GetReflection()->GetDouble(
1826         message0b, fd_map_int32_double_value);
1827     const Message& message9b =
1828         mmf_int32_double.Get(9, entry_int32_double.get());
1829     double double_value9b = message9b.GetReflection()->GetDouble(
1830         message9b, fd_map_int32_double_value);
1831 
1832     EXPECT_EQ(double_value9a, double_value0b);
1833     EXPECT_EQ(double_value0a, double_value9b);
1834   }
1835 
1836   {
1837     const Message& message0a =
1838         mmf_string_string.Get(0, entry_string_string.get());
1839     std::string string_value0a = message0a.GetReflection()->GetString(
1840         message0a, fd_map_string_string_value);
1841     const Message& message9a =
1842         mmf_string_string.Get(9, entry_string_string.get());
1843     std::string string_value9a = message9a.GetReflection()->GetString(
1844         message9a, fd_map_string_string_value);
1845 
1846     mmf_string_string.SwapElements(0, 9);
1847 
1848     const Message& message0b =
1849         mmf_string_string.Get(0, entry_string_string.get());
1850     std::string string_value0b = message0b.GetReflection()->GetString(
1851         message0b, fd_map_string_string_value);
1852     const Message& message9b =
1853         mmf_string_string.Get(9, entry_string_string.get());
1854     std::string string_value9b = message9b.GetReflection()->GetString(
1855         message9b, fd_map_string_string_value);
1856 
1857     EXPECT_EQ(string_value9a, string_value0b);
1858     EXPECT_EQ(string_value0a, string_value9b);
1859   }
1860 
1861   {
1862     const Message& message0a =
1863         mmf_int32_foreign_message.Get(0, entry_int32_foreign_message.get());
1864     const ForeignMessage& sub_message0a =
1865         down_cast<const ForeignMessage&>(message0a.GetReflection()->GetMessage(
1866             message0a, fd_map_int32_foreign_message_value));
1867     int32 int32_value0a = sub_message0a.c();
1868     const Message& message9a =
1869         mmf_int32_foreign_message.Get(9, entry_int32_foreign_message.get());
1870     const ForeignMessage& sub_message9a =
1871         down_cast<const ForeignMessage&>(message9a.GetReflection()->GetMessage(
1872             message9a, fd_map_int32_foreign_message_value));
1873     int32 int32_value9a = sub_message9a.c();
1874 
1875     mmf_int32_foreign_message.SwapElements(0, 9);
1876 
1877     const Message& message0b =
1878         mmf_int32_foreign_message.Get(0, entry_int32_foreign_message.get());
1879     const ForeignMessage& sub_message0b =
1880         down_cast<const ForeignMessage&>(message0b.GetReflection()->GetMessage(
1881             message0b, fd_map_int32_foreign_message_value));
1882     int32 int32_value0b = sub_message0b.c();
1883     const Message& message9b =
1884         mmf_int32_foreign_message.Get(9, entry_int32_foreign_message.get());
1885     const ForeignMessage& sub_message9b =
1886         down_cast<const ForeignMessage&>(message9b.GetReflection()->GetMessage(
1887             message9b, fd_map_int32_foreign_message_value));
1888     int32 int32_value9b = sub_message9b.c();
1889 
1890     EXPECT_EQ(int32_value9a, int32_value0b);
1891     EXPECT_EQ(int32_value0a, int32_value9b);
1892   }
1893 }
1894 
TEST_F(MapFieldReflectionTest,RepeatedFieldRefMergeFromAndSwap)1895 TEST_F(MapFieldReflectionTest, RepeatedFieldRefMergeFromAndSwap) {
1896   // Set-up message content.
1897   TestMap m0, m1, m2;
1898   for (int i = 0; i < 10; ++i) {
1899     (*m0.mutable_map_int32_int32())[i] = Func(i, 1);
1900     (*m0.mutable_map_int32_double())[i] = Func(i, 2);
1901     (*m0.mutable_map_string_string())[StrFunc(i, 1)] = StrFunc(i, 5);
1902     (*m0.mutable_map_int32_foreign_message())[i].set_c(Func(i, 6));
1903     (*m1.mutable_map_int32_int32())[i + 10] = Func(i, 11);
1904     (*m1.mutable_map_int32_double())[i + 10] = Func(i, 12);
1905     (*m1.mutable_map_string_string())[StrFunc(i + 10, 1)] = StrFunc(i, 15);
1906     (*m1.mutable_map_int32_foreign_message())[i + 10].set_c(Func(i, 16));
1907     (*m2.mutable_map_int32_int32())[i + 20] = Func(i, 21);
1908     (*m2.mutable_map_int32_double())[i + 20] = Func(i, 22);
1909     (*m2.mutable_map_string_string())[StrFunc(i + 20, 1)] = StrFunc(i, 25);
1910     (*m2.mutable_map_int32_foreign_message())[i + 20].set_c(Func(i, 26));
1911   }
1912 
1913   const Reflection* refl = m0.GetReflection();
1914   const Descriptor* desc = m0.GetDescriptor();
1915 
1916   // Get FieldDescriptors for all the fields of interest.
1917   const FieldDescriptor* fd_map_int32_int32 =
1918       desc->FindFieldByName("map_int32_int32");
1919   const FieldDescriptor* fd_map_int32_double =
1920       desc->FindFieldByName("map_int32_double");
1921   const FieldDescriptor* fd_map_string_string =
1922       desc->FindFieldByName("map_string_string");
1923   const FieldDescriptor* fd_map_int32_foreign_message =
1924       desc->FindFieldByName("map_int32_foreign_message");
1925 
1926   // Get MutableRepeatedFieldRef objects for all fields of interest.
1927   const MutableRepeatedFieldRef<Message> mmf_int32_int32 =
1928       refl->GetMutableRepeatedFieldRef<Message>(&m0, fd_map_int32_int32);
1929   const MutableRepeatedFieldRef<Message> mmf_int32_double =
1930       refl->GetMutableRepeatedFieldRef<Message>(&m0, fd_map_int32_double);
1931   const MutableRepeatedFieldRef<Message> mmf_string_string =
1932       refl->GetMutableRepeatedFieldRef<Message>(&m0, fd_map_string_string);
1933   const MutableRepeatedFieldRef<Message> mmf_int32_foreign_message =
1934       refl->GetMutableRepeatedFieldRef<Message>(&m0,
1935                                                 fd_map_int32_foreign_message);
1936 
1937   // Test MutableRepeatedRef::CopyFrom
1938   mmf_int32_int32.CopyFrom(
1939       refl->GetRepeatedFieldRef<Message>(m1, fd_map_int32_int32));
1940   mmf_int32_double.CopyFrom(
1941       refl->GetRepeatedFieldRef<Message>(m1, fd_map_int32_double));
1942   mmf_string_string.CopyFrom(
1943       refl->GetRepeatedFieldRef<Message>(m1, fd_map_string_string));
1944   mmf_int32_foreign_message.CopyFrom(
1945       refl->GetRepeatedFieldRef<Message>(m1, fd_map_int32_foreign_message));
1946 
1947   for (int i = 0; i < 10; ++i) {
1948     EXPECT_EQ(Func(i, 11), m0.map_int32_int32().at(i + 10));
1949     EXPECT_EQ(Func(i, 12), m0.map_int32_double().at(i + 10));
1950     EXPECT_EQ(StrFunc(i, 15), m0.map_string_string().at(StrFunc(i + 10, 1)));
1951     EXPECT_EQ(Func(i, 16), m0.map_int32_foreign_message().at(i + 10).c());
1952   }
1953 
1954   // Test MutableRepeatedRef::MergeFrom
1955   mmf_int32_int32.MergeFrom(
1956       refl->GetRepeatedFieldRef<Message>(m2, fd_map_int32_int32));
1957   mmf_int32_double.MergeFrom(
1958       refl->GetRepeatedFieldRef<Message>(m2, fd_map_int32_double));
1959   mmf_string_string.MergeFrom(
1960       refl->GetRepeatedFieldRef<Message>(m2, fd_map_string_string));
1961   mmf_int32_foreign_message.MergeFrom(
1962       refl->GetRepeatedFieldRef<Message>(m2, fd_map_int32_foreign_message));
1963   for (int i = 0; i < 10; ++i) {
1964     EXPECT_EQ(Func(i, 21), m0.map_int32_int32().at(i + 20));
1965     EXPECT_EQ(Func(i, 22), m0.map_int32_double().at(i + 20));
1966     EXPECT_EQ(StrFunc(i, 25), m0.map_string_string().at(StrFunc(i + 20, 1)));
1967     EXPECT_EQ(Func(i, 26), m0.map_int32_foreign_message().at(i + 20).c());
1968   }
1969 
1970   // Test MutableRepeatedRef::Swap
1971   // Swap between m0 and m2.
1972   mmf_int32_int32.Swap(
1973       refl->GetMutableRepeatedFieldRef<Message>(&m2, fd_map_int32_int32));
1974   mmf_int32_double.Swap(
1975       refl->GetMutableRepeatedFieldRef<Message>(&m2, fd_map_int32_double));
1976   mmf_string_string.Swap(
1977       refl->GetMutableRepeatedFieldRef<Message>(&m2, fd_map_string_string));
1978   mmf_int32_foreign_message.Swap(refl->GetMutableRepeatedFieldRef<Message>(
1979       &m2, fd_map_int32_foreign_message));
1980   for (int i = 0; i < 10; ++i) {
1981     // Check the content of m0.
1982     EXPECT_EQ(Func(i, 21), m0.map_int32_int32().at(i + 20));
1983     EXPECT_EQ(Func(i, 22), m0.map_int32_double().at(i + 20));
1984     EXPECT_EQ(StrFunc(i, 25), m0.map_string_string().at(StrFunc(i + 20, 1)));
1985     EXPECT_EQ(Func(i, 26), m0.map_int32_foreign_message().at(i + 20).c());
1986 
1987     // Check the content of m2.
1988     EXPECT_EQ(Func(i, 11), m2.map_int32_int32().at(i + 10));
1989     EXPECT_EQ(Func(i, 12), m2.map_int32_double().at(i + 10));
1990     EXPECT_EQ(StrFunc(i, 15), m2.map_string_string().at(StrFunc(i + 10, 1)));
1991     EXPECT_EQ(Func(i, 16), m2.map_int32_foreign_message().at(i + 10).c());
1992     EXPECT_EQ(Func(i, 21), m2.map_int32_int32().at(i + 20));
1993     EXPECT_EQ(Func(i, 22), m2.map_int32_double().at(i + 20));
1994     EXPECT_EQ(StrFunc(i, 25), m2.map_string_string().at(StrFunc(i + 20, 1)));
1995     EXPECT_EQ(Func(i, 26), m2.map_int32_foreign_message().at(i + 20).c());
1996   }
1997 
1998   // TODO(teboring): add test for duplicated key
1999 }
2000 
TEST_F(MapFieldReflectionTest,MapSizeWithDuplicatedKey)2001 TEST_F(MapFieldReflectionTest, MapSizeWithDuplicatedKey) {
2002   // Dynamic Message
2003   {
2004     DynamicMessageFactory factory;
2005     std::unique_ptr<Message> message(
2006         factory.GetPrototype(unittest::TestMap::descriptor())->New());
2007     const Reflection* reflection = message->GetReflection();
2008     const FieldDescriptor* field =
2009         unittest::TestMap::descriptor()->FindFieldByName("map_int32_int32");
2010 
2011     Message* entry1 = reflection->AddMessage(message.get(), field);
2012     Message* entry2 = reflection->AddMessage(message.get(), field);
2013 
2014     const Reflection* entry_reflection = entry1->GetReflection();
2015     const FieldDescriptor* key_field =
2016         entry1->GetDescriptor()->FindFieldByName("key");
2017     entry_reflection->SetInt32(entry1, key_field, 1);
2018     entry_reflection->SetInt32(entry2, key_field, 1);
2019 
2020     EXPECT_EQ(2, reflection->FieldSize(*message, field));
2021     EXPECT_EQ(1, MapSize(reflection, field, *message));
2022     EXPECT_EQ(2, reflection->FieldSize(*message, field));
2023   }
2024 
2025   // Generated Message
2026   {
2027     unittest::TestMap message;
2028     const Reflection* reflection = message.GetReflection();
2029     const FieldDescriptor* field =
2030         message.GetDescriptor()->FindFieldByName("map_int32_int32");
2031 
2032     Message* entry1 = reflection->AddMessage(&message, field);
2033     Message* entry2 = reflection->AddMessage(&message, field);
2034 
2035     const Reflection* entry_reflection = entry1->GetReflection();
2036     const FieldDescriptor* key_field =
2037         entry1->GetDescriptor()->FindFieldByName("key");
2038     entry_reflection->SetInt32(entry1, key_field, 1);
2039     entry_reflection->SetInt32(entry2, key_field, 1);
2040 
2041     EXPECT_EQ(2, reflection->FieldSize(message, field));
2042     EXPECT_EQ(1, MapSize(reflection, field, message));
2043   }
2044 }
2045 
TEST_F(MapFieldReflectionTest,UninitializedEntry)2046 TEST_F(MapFieldReflectionTest, UninitializedEntry) {
2047   unittest::TestRequiredMessageMap message;
2048   const Reflection* reflection = message.GetReflection();
2049   const FieldDescriptor* field =
2050       message.GetDescriptor()->FindFieldByName("map_field");
2051   auto entry = reflection->AddMessage(&message, field);
2052   EXPECT_FALSE(entry->IsInitialized());
2053   EXPECT_FALSE(message.IsInitialized());
2054 }
2055 
2056 class MyMapEntry
2057     : public internal::MapEntry<MyMapEntry, ::google::protobuf::int32, ::google::protobuf::int32,
2058                                 internal::WireFormatLite::TYPE_INT32,
2059                                 internal::WireFormatLite::TYPE_INT32> {
2060  public:
MyMapEntry()2061   constexpr MyMapEntry() {}
MyMapEntry(Arena *)2062   MyMapEntry(Arena*) { std::abort(); }
GetMetadata() const2063   Metadata GetMetadata() const override { std::abort(); }
ValidateKey(void *)2064   static bool ValidateKey(void*) { return true; }
ValidateValue(void *)2065   static bool ValidateValue(void*) { return true; }
2066 };
2067 
2068 class MyMapEntryLite
2069     : public internal::MapEntryLite<MyMapEntryLite, ::google::protobuf::int32, ::google::protobuf::int32,
2070                                     internal::WireFormatLite::TYPE_INT32,
2071                                     internal::WireFormatLite::TYPE_INT32> {
2072  public:
MyMapEntryLite()2073   constexpr MyMapEntryLite() {}
MyMapEntryLite(Arena *)2074   explicit MyMapEntryLite(Arena*) { std::abort(); }
ValidateKey(void *)2075   static bool ValidateKey(void*) { return true; }
ValidateValue(void *)2076   static bool ValidateValue(void*) { return true; }
2077 };
2078 
TEST(MapEntryTest,ConstInit)2079 TEST(MapEntryTest, ConstInit) {
2080   // This verifies that `MapEntry`, `MapEntryLite` and `MapEntryImpl` can be
2081   // constant initialized.
2082   PROTOBUF_CONSTINIT static MyMapEntry entry{};
2083   EXPECT_NE(entry.SpaceUsed(), 0);
2084 
2085   PROTOBUF_CONSTINIT static MyMapEntryLite entry_lite{};  // NOLINT
2086   EXPECT_TRUE(entry_lite.IsInitialized());
2087 }
2088 
2089 // Generated Message Test ===========================================
2090 
TEST(GeneratedMapFieldTest,Accessors)2091 TEST(GeneratedMapFieldTest, Accessors) {
2092   unittest::TestMap message;
2093 
2094   MapTestUtil::SetMapFields(&message);
2095   MapTestUtil::ExpectMapFieldsSet(message);
2096 
2097   MapTestUtil::ModifyMapFields(&message);
2098   MapTestUtil::ExpectMapFieldsModified(message);
2099 }
2100 
TEST(GeneratedMapFieldTest,SetMapFieldsInitialized)2101 TEST(GeneratedMapFieldTest, SetMapFieldsInitialized) {
2102   unittest::TestMap message;
2103 
2104   MapTestUtil::SetMapFieldsInitialized(&message);
2105   MapTestUtil::ExpectMapFieldsSetInitialized(message);
2106 }
2107 
TEST(GeneratedMapFieldTest,Proto2SetMapFieldsInitialized)2108 TEST(GeneratedMapFieldTest, Proto2SetMapFieldsInitialized) {
2109   unittest::TestEnumMap message;
2110   EXPECT_EQ(unittest::PROTO2_MAP_ENUM_FOO,
2111             (*message.mutable_known_map_field())[0]);
2112 }
2113 
TEST(GeneratedMapFieldTest,Clear)2114 TEST(GeneratedMapFieldTest, Clear) {
2115   unittest::TestMap message;
2116 
2117   MapTestUtil::SetMapFields(&message);
2118   message.Clear();
2119   MapTestUtil::ExpectClear(message);
2120 }
2121 
TEST(GeneratedMapFieldTest,ClearMessageMap)2122 TEST(GeneratedMapFieldTest, ClearMessageMap) {
2123   unittest::TestMessageMap message;
2124 
2125   // Creates a TestAllTypes with default value
2126   TestUtil::ExpectClear((*message.mutable_map_int32_message())[0]);
2127 }
2128 
TEST(GeneratedMapFieldTest,CopyFrom)2129 TEST(GeneratedMapFieldTest, CopyFrom) {
2130   unittest::TestMap message1, message2;
2131 
2132   MapTestUtil::SetMapFields(&message1);
2133   message2.CopyFrom(message1);
2134   MapTestUtil::ExpectMapFieldsSet(message2);
2135 
2136   // Copying from self should be a no-op.
2137   message2.CopyFrom(message2);
2138   MapTestUtil::ExpectMapFieldsSet(message2);
2139 }
2140 
TEST(GeneratedMapFieldTest,CopyFromMessageMap)2141 TEST(GeneratedMapFieldTest, CopyFromMessageMap) {
2142   unittest::TestMessageMap message1, message2;
2143 
2144   (*message1.mutable_map_int32_message())[0].add_repeated_int32(100);
2145   (*message2.mutable_map_int32_message())[0].add_repeated_int32(101);
2146 
2147   message1.CopyFrom(message2);
2148 
2149   // Checks repeated field is overwritten.
2150   EXPECT_EQ(1, message1.map_int32_message().at(0).repeated_int32_size());
2151   EXPECT_EQ(101, message1.map_int32_message().at(0).repeated_int32(0));
2152 }
2153 
TEST(GeneratedMapFieldTest,SwapWithEmpty)2154 TEST(GeneratedMapFieldTest, SwapWithEmpty) {
2155   unittest::TestMap message1, message2;
2156 
2157   MapTestUtil::SetMapFields(&message1);
2158   MapTestUtil::ExpectMapFieldsSet(message1);
2159   MapTestUtil::ExpectClear(message2);
2160 
2161   message1.Swap(&message2);
2162   MapTestUtil::ExpectMapFieldsSet(message2);
2163   MapTestUtil::ExpectClear(message1);
2164 }
2165 
TEST(GeneratedMapFieldTest,SwapWithSelf)2166 TEST(GeneratedMapFieldTest, SwapWithSelf) {
2167   unittest::TestMap message;
2168 
2169   MapTestUtil::SetMapFields(&message);
2170   MapTestUtil::ExpectMapFieldsSet(message);
2171 
2172   message.Swap(&message);
2173   MapTestUtil::ExpectMapFieldsSet(message);
2174 }
2175 
TEST(GeneratedMapFieldTest,SwapWithOther)2176 TEST(GeneratedMapFieldTest, SwapWithOther) {
2177   unittest::TestMap message1, message2;
2178 
2179   MapTestUtil::SetMapFields(&message1);
2180   MapTestUtil::SetMapFields(&message2);
2181   MapTestUtil::ModifyMapFields(&message2);
2182 
2183   message1.Swap(&message2);
2184   MapTestUtil::ExpectMapFieldsModified(message1);
2185   MapTestUtil::ExpectMapFieldsSet(message2);
2186 }
2187 
TEST(GeneratedMapFieldTest,CopyConstructor)2188 TEST(GeneratedMapFieldTest, CopyConstructor) {
2189   unittest::TestMap message1;
2190   MapTestUtil::SetMapFields(&message1);
2191 
2192   unittest::TestMap message2(message1);
2193   MapTestUtil::ExpectMapFieldsSet(message2);
2194 }
2195 
TEST(GeneratedMapFieldTest,CopyAssignmentOperator)2196 TEST(GeneratedMapFieldTest, CopyAssignmentOperator) {
2197   unittest::TestMap message1;
2198   MapTestUtil::SetMapFields(&message1);
2199 
2200   unittest::TestMap message2;
2201   message2 = message1;
2202   MapTestUtil::ExpectMapFieldsSet(message2);
2203 
2204   // Make sure that self-assignment does something sane.
2205   message2.operator=(message2);
2206   MapTestUtil::ExpectMapFieldsSet(message2);
2207 }
2208 
2209 #if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || PROTOBUF_RTTI
TEST(GeneratedMapFieldTest,UpcastCopyFrom)2210 TEST(GeneratedMapFieldTest, UpcastCopyFrom) {
2211   // Test the CopyFrom method that takes in the generic const Message&
2212   // parameter.
2213   unittest::TestMap message1, message2;
2214 
2215   MapTestUtil::SetMapFields(&message1);
2216 
2217   const Message* source = implicit_cast<const Message*>(&message1);
2218   message2.CopyFrom(*source);
2219 
2220   MapTestUtil::ExpectMapFieldsSet(message2);
2221 }
2222 #endif
2223 
2224 #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
2225 
TEST(GeneratedMapFieldTest,CopyFromDynamicMessage)2226 TEST(GeneratedMapFieldTest, CopyFromDynamicMessage) {
2227   // Test copying from a DynamicMessage, which must fall back to using
2228   // reflection.
2229   unittest::TestMap message2;
2230 
2231   // Construct a new version of the dynamic message via the factory.
2232   DynamicMessageFactory factory;
2233   std::unique_ptr<Message> message1;
2234   message1.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New());
2235   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2236   reflection_tester.SetMapFieldsViaReflection(message1.get());
2237   reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
2238   reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get());
2239   message2.CopyFrom(*message1);
2240   MapTestUtil::ExpectMapFieldsSet(message2);
2241 }
2242 
TEST(GeneratedMapFieldTest,CopyFromDynamicMessageMapReflection)2243 TEST(GeneratedMapFieldTest, CopyFromDynamicMessageMapReflection) {
2244   unittest::TestMap message2;
2245 
2246   // Construct a new version of the dynamic message via the factory.
2247   DynamicMessageFactory factory;
2248   std::unique_ptr<Message> message1;
2249   message1.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New());
2250   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2251   reflection_tester.SetMapFieldsViaMapReflection(message1.get());
2252   reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
2253   reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get());
2254   message2.CopyFrom(*message1);
2255   MapTestUtil::ExpectMapFieldsSet(message2);
2256 }
2257 
TEST(GeneratedMapFieldTest,DynamicMessageMergeFromDynamicMessage)2258 TEST(GeneratedMapFieldTest, DynamicMessageMergeFromDynamicMessage) {
2259   // Construct two dynamic message and sets via map reflection.
2260   DynamicMessageFactory factory;
2261   std::unique_ptr<Message> message1;
2262   message1.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New());
2263   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2264   reflection_tester.SetMapFieldsViaMapReflection(message1.get());
2265 
2266   // message2 is created by same factory.
2267   std::unique_ptr<Message> message2;
2268   message2.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New());
2269   reflection_tester.SetMapFieldsViaMapReflection(message2.get());
2270 
2271   // message3 is created by different factory.
2272   DynamicMessageFactory factory3;
2273   std::unique_ptr<Message> message3;
2274   message3.reset(factory3.GetPrototype(unittest::TestMap::descriptor())->New());
2275   reflection_tester.SetMapFieldsViaMapReflection(message3.get());
2276 
2277   message2->MergeFrom(*message1);
2278   message3->MergeFrom(*message1);
2279 
2280   // Test MergeFrom does not sync to repeated fields and
2281   // there is no duplicate keys in text format.
2282   std::string output1, output2, output3;
2283   TextFormat::PrintToString(*message1, &output1);
2284   TextFormat::PrintToString(*message2, &output2);
2285   TextFormat::PrintToString(*message3, &output3);
2286   EXPECT_EQ(output1, output2);
2287   EXPECT_EQ(output1, output3);
2288 }
2289 
TEST(GeneratedMapFieldTest,DynamicMessageCopyFrom)2290 TEST(GeneratedMapFieldTest, DynamicMessageCopyFrom) {
2291   // Test copying to a DynamicMessage, which must fall back to using reflection.
2292   unittest::TestMap message2;
2293   MapTestUtil::SetMapFields(&message2);
2294 
2295   // Construct a new version of the dynamic message via the factory.
2296   DynamicMessageFactory factory;
2297   std::unique_ptr<Message> message1;
2298   message1.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New());
2299 
2300   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2301   message1->MergeFrom(message2);
2302   reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
2303   reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get());
2304 }
2305 
TEST(GeneratedMapFieldTest,DynamicMessageCopyFromMapReflection)2306 TEST(GeneratedMapFieldTest, DynamicMessageCopyFromMapReflection) {
2307   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2308   unittest::TestMap message2;
2309   reflection_tester.SetMapFieldsViaMapReflection(&message2);
2310 
2311   // Construct a dynamic message via the factory.
2312   DynamicMessageFactory factory;
2313   std::unique_ptr<Message> message1;
2314   message1.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New());
2315 
2316   message1->MergeFrom(message2);
2317   reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get());
2318   reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
2319 }
2320 
TEST(GeneratedMapFieldTest,SyncDynamicMapWithRepeatedField)2321 TEST(GeneratedMapFieldTest, SyncDynamicMapWithRepeatedField) {
2322   // Construct a dynamic message via the factory.
2323   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2324   DynamicMessageFactory factory;
2325   std::unique_ptr<Message> message;
2326   message.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New());
2327   reflection_tester.SetMapFieldsViaReflection(message.get());
2328   reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message.get());
2329   reflection_tester.ExpectMapFieldsSetViaReflection(*message);
2330 }
2331 
2332 #endif  // !PROTOBUF_TEST_NO_DESCRIPTORS
2333 
TEST(GeneratedMapFieldTest,NonEmptyMergeFrom)2334 TEST(GeneratedMapFieldTest, NonEmptyMergeFrom) {
2335   unittest::TestMap message1, message2;
2336 
2337   MapTestUtil::SetMapFields(&message1);
2338 
2339   // This field will test merging into an empty spot.
2340   (*message2.mutable_map_int32_int32())[1] = 1;
2341   message1.mutable_map_int32_int32()->erase(1);
2342 
2343   // This tests overwriting.
2344   (*message2.mutable_map_int32_double())[1] = 1;
2345   (*message1.mutable_map_int32_double())[1] = 2;
2346 
2347   message1.MergeFrom(message2);
2348   MapTestUtil::ExpectMapFieldsSet(message1);
2349 
2350   // Test reflection MergeFrom does not sync to repeated field
2351   // and there is no duplicated keys.
2352   MapTestUtil::SetMapFields(&message1);
2353   MapTestUtil::SetMapFields(&message2);
2354 
2355   message2.MergeFrom(message1);
2356 
2357   std::string output1, output2;
2358   TextFormat::PrintToString(message1, &output1);
2359   TextFormat::PrintToString(message2, &output2);
2360   EXPECT_EQ(output1, output2);
2361 }
2362 
TEST(GeneratedMapFieldTest,MergeFromMessageMap)2363 TEST(GeneratedMapFieldTest, MergeFromMessageMap) {
2364   unittest::TestMessageMap message1, message2;
2365 
2366   (*message1.mutable_map_int32_message())[0].add_repeated_int32(100);
2367   (*message2.mutable_map_int32_message())[0].add_repeated_int32(101);
2368 
2369   message1.MergeFrom(message2);
2370 
2371   // Checks repeated field is overwritten.
2372   EXPECT_EQ(1, message1.map_int32_message().at(0).repeated_int32_size());
2373   EXPECT_EQ(101, message1.map_int32_message().at(0).repeated_int32(0));
2374 }
2375 
2376 // Test the generated SerializeWithCachedSizesToArray()
TEST(GeneratedMapFieldTest,SerializationToArray)2377 TEST(GeneratedMapFieldTest, SerializationToArray) {
2378   unittest::TestMap message1, message2;
2379   std::string data;
2380   MapTestUtil::SetMapFields(&message1);
2381   size_t size = message1.ByteSizeLong();
2382   data.resize(size);
2383   uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
2384   uint8* end = message1.SerializeWithCachedSizesToArray(start);
2385   EXPECT_EQ(size, end - start);
2386   EXPECT_TRUE(message2.ParseFromString(data));
2387   MapTestUtil::ExpectMapFieldsSet(message2);
2388 }
2389 
2390 // Test the generated SerializeWithCachedSizes()
TEST(GeneratedMapFieldTest,SerializationToStream)2391 TEST(GeneratedMapFieldTest, SerializationToStream) {
2392   unittest::TestMap message1, message2;
2393   MapTestUtil::SetMapFields(&message1);
2394   size_t size = message1.ByteSizeLong();
2395   std::string data;
2396   data.resize(size);
2397   {
2398     // Allow the output stream to buffer only one byte at a time.
2399     io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
2400     io::CodedOutputStream output_stream(&array_stream);
2401     message1.SerializeWithCachedSizes(&output_stream);
2402     EXPECT_FALSE(output_stream.HadError());
2403     EXPECT_EQ(size, output_stream.ByteCount());
2404   }
2405   EXPECT_TRUE(message2.ParseFromString(data));
2406   MapTestUtil::ExpectMapFieldsSet(message2);
2407 }
2408 
2409 
TEST(GeneratedMapFieldTest,SameTypeMaps)2410 TEST(GeneratedMapFieldTest, SameTypeMaps) {
2411   const Descriptor* map1 = unittest::TestSameTypeMap::descriptor()
2412                                ->FindFieldByName("map1")
2413                                ->message_type();
2414   const Descriptor* map2 = unittest::TestSameTypeMap::descriptor()
2415                                ->FindFieldByName("map2")
2416                                ->message_type();
2417 
2418   const Message* map1_entry =
2419       MessageFactory::generated_factory()->GetPrototype(map1);
2420   const Message* map2_entry =
2421       MessageFactory::generated_factory()->GetPrototype(map2);
2422 
2423   EXPECT_EQ(map1, map1_entry->GetDescriptor());
2424   EXPECT_EQ(map2, map2_entry->GetDescriptor());
2425 }
2426 
TEST(GeneratedMapFieldTest,Proto2UnknownEnum)2427 TEST(GeneratedMapFieldTest, Proto2UnknownEnum) {
2428   unittest::TestEnumMapPlusExtra from;
2429   (*from.mutable_known_map_field())[0] = unittest::E_PROTO2_MAP_ENUM_FOO;
2430   (*from.mutable_unknown_map_field())[0] = unittest::E_PROTO2_MAP_ENUM_EXTRA;
2431   std::string data;
2432   from.SerializeToString(&data);
2433 
2434   unittest::TestEnumMap to;
2435   EXPECT_TRUE(to.ParseFromString(data));
2436   EXPECT_EQ(0, to.unknown_map_field().size());
2437   const UnknownFieldSet& unknown_field_set =
2438       to.GetReflection()->GetUnknownFields(to);
2439   EXPECT_EQ(1, unknown_field_set.field_count());
2440   EXPECT_EQ(1, to.known_map_field().size());
2441   EXPECT_EQ(unittest::PROTO2_MAP_ENUM_FOO, to.known_map_field().at(0));
2442 
2443   data.clear();
2444   from.Clear();
2445   to.SerializeToString(&data);
2446   EXPECT_TRUE(from.ParseFromString(data));
2447   EXPECT_EQ(0, from.GetReflection()->GetUnknownFields(from).field_count());
2448   EXPECT_EQ(1, from.known_map_field().size());
2449   EXPECT_EQ(unittest::E_PROTO2_MAP_ENUM_FOO, from.known_map_field().at(0));
2450   EXPECT_EQ(1, from.unknown_map_field().size());
2451   EXPECT_EQ(unittest::E_PROTO2_MAP_ENUM_EXTRA, from.unknown_map_field().at(0));
2452 }
2453 
TEST(GeneratedMapFieldTest,StandardWireFormat)2454 TEST(GeneratedMapFieldTest, StandardWireFormat) {
2455   unittest::TestMap message;
2456   std::string data = "\x0A\x04\x08\x01\x10\x01";
2457 
2458   EXPECT_TRUE(message.ParseFromString(data));
2459   EXPECT_EQ(1, message.map_int32_int32().size());
2460   EXPECT_EQ(1, message.map_int32_int32().at(1));
2461 }
2462 
TEST(GeneratedMapFieldTest,UnorderedWireFormat)2463 TEST(GeneratedMapFieldTest, UnorderedWireFormat) {
2464   unittest::TestMap message;
2465 
2466   // put value before key in wire format
2467   std::string data = "\x0A\x04\x10\x01\x08\x02";
2468 
2469   EXPECT_TRUE(message.ParseFromString(data));
2470   EXPECT_EQ(1, message.map_int32_int32().size());
2471   ASSERT_NE(message.map_int32_int32().find(2), message.map_int32_int32().end());
2472   EXPECT_EQ(1, message.map_int32_int32().at(2));
2473 }
2474 
TEST(GeneratedMapFieldTest,DuplicatedKeyWireFormat)2475 TEST(GeneratedMapFieldTest, DuplicatedKeyWireFormat) {
2476   unittest::TestMap message;
2477 
2478   // Two key fields in wire format
2479   std::string data = "\x0A\x06\x08\x01\x08\x02\x10\x01";
2480 
2481   EXPECT_TRUE(message.ParseFromString(data));
2482   EXPECT_EQ(1, message.map_int32_int32().size());
2483   EXPECT_EQ(1, message.map_int32_int32().at(2));
2484 
2485   // A similar test, but with a map from int to a message type.
2486   // Again, we want to be sure that the "second one wins" when
2487   // there are two separate entries with the same key.
2488   const int key = 99;
2489   unittest::TestRequiredMessageMap map_message;
2490   unittest::TestRequired with_dummy4;
2491   with_dummy4.set_a(0);
2492   with_dummy4.set_b(0);
2493   with_dummy4.set_c(0);
2494   with_dummy4.set_dummy4(11);
2495   (*map_message.mutable_map_field())[key] = with_dummy4;
2496   std::string s = map_message.SerializeAsString();
2497   unittest::TestRequired with_dummy5;
2498   with_dummy5.set_a(0);
2499   with_dummy5.set_b(0);
2500   with_dummy5.set_c(0);
2501   with_dummy5.set_dummy5(12);
2502   (*map_message.mutable_map_field())[key] = with_dummy5;
2503   std::string both = s + map_message.SerializeAsString();
2504   // We don't expect a merge now.  The "second one wins."
2505   ASSERT_TRUE(map_message.ParseFromString(both));
2506   ASSERT_EQ(1, map_message.map_field().size());
2507   ASSERT_EQ(1, map_message.map_field().count(key));
2508   EXPECT_EQ(0, map_message.map_field().find(key)->second.a());
2509   EXPECT_EQ(0, map_message.map_field().find(key)->second.b());
2510   EXPECT_EQ(0, map_message.map_field().find(key)->second.c());
2511   EXPECT_FALSE(map_message.map_field().find(key)->second.has_dummy4());
2512   ASSERT_TRUE(map_message.map_field().find(key)->second.has_dummy5());
2513   EXPECT_EQ(12, map_message.map_field().find(key)->second.dummy5());
2514 }
2515 
2516 // Exhaustive combinations of keys, values, and junk in any order.
2517 // This re-tests some of the things tested above, but if it fails
2518 // it's more work to determine what went wrong, so it isn't necessarily
2519 // bad that we have the simpler tests too.
TEST(GeneratedMapFieldTest,KeysValuesUnknownsWireFormat)2520 TEST(GeneratedMapFieldTest, KeysValuesUnknownsWireFormat) {
2521   unittest::TestMap message;
2522   const int kMaxNumKeysAndValuesAndJunk = 4;
2523   const char kKeyTag = 0x08;
2524   const char kValueTag = 0x10;
2525   const char kJunkTag = 0x20;
2526   for (int items = 0; items <= kMaxNumKeysAndValuesAndJunk; items++) {
2527     std::string data = "\x0A";
2528     // Encode length of what will follow.
2529     data.push_back(items * 2);
2530     static const int kBitsOfIPerItem = 4;
2531     static const int mask = (1 << kBitsOfIPerItem) - 1;
2532     // Each iteration of the following is a test.  It uses i as bit vector
2533     // encoding the keys and values to put in the wire format.
2534     for (int i = 0; i < (1 << (items * kBitsOfIPerItem)); i++) {
2535       std::string wire_format = data;
2536       int expected_key = 0;
2537       int expected_value = 0;
2538       for (int k = i, j = 0; j < items; j++, k >>= kBitsOfIPerItem) {
2539         bool is_key = k & 0x1;
2540         bool is_value = !is_key && (k & 0x2);
2541         wire_format.push_back(is_key ? kKeyTag
2542                                      : is_value ? kValueTag : kJunkTag);
2543         char c = static_cast<char>(k & mask) >> 2;  // One char after the tag.
2544         wire_format.push_back(c);
2545         if (is_key) expected_key = static_cast<int>(c);
2546         if (is_value) expected_value = static_cast<int>(c);
2547         bool res = message.ParseFromString(wire_format);
2548         bool expect_success = true;
2549         // Unfortunately the old map parser accepts malformed input, the new
2550         // parser accepts only correct input.
2551         if (j != items - 1) expect_success = false;
2552         if (expect_success) {
2553           ASSERT_TRUE(res);
2554           ASSERT_EQ(1, message.map_int32_int32().size());
2555           ASSERT_EQ(expected_key, message.map_int32_int32().begin()->first);
2556           ASSERT_EQ(expected_value, message.map_int32_int32().begin()->second);
2557         } else {
2558           ASSERT_FALSE(res);
2559         }
2560       }
2561     }
2562   }
2563 }
2564 
TEST(GeneratedMapFieldTest,DuplicatedValueWireFormat)2565 TEST(GeneratedMapFieldTest, DuplicatedValueWireFormat) {
2566   unittest::TestMap message;
2567 
2568   // Two value fields in wire format
2569   std::string data = "\x0A\x06\x08\x01\x10\x01\x10\x02";
2570 
2571   EXPECT_TRUE(message.ParseFromString(data));
2572   EXPECT_EQ(1, message.map_int32_int32().size());
2573   EXPECT_EQ(2, message.map_int32_int32().at(1));
2574 }
2575 
TEST(GeneratedMapFieldTest,MissedKeyWireFormat)2576 TEST(GeneratedMapFieldTest, MissedKeyWireFormat) {
2577   unittest::TestMap message;
2578 
2579   // No key field in wire format
2580   std::string data = "\x0A\x02\x10\x01";
2581 
2582   EXPECT_TRUE(message.ParseFromString(data));
2583   EXPECT_EQ(1, message.map_int32_int32().size());
2584   ASSERT_NE(message.map_int32_int32().find(0), message.map_int32_int32().end());
2585   EXPECT_EQ(1, message.map_int32_int32().at(0));
2586 }
2587 
TEST(GeneratedMapFieldTest,MissedValueWireFormat)2588 TEST(GeneratedMapFieldTest, MissedValueWireFormat) {
2589   unittest::TestMap message;
2590 
2591   // No value field in wire format
2592   std::string data = "\x0A\x02\x08\x01";
2593 
2594   EXPECT_TRUE(message.ParseFromString(data));
2595   EXPECT_EQ(1, message.map_int32_int32().size());
2596   ASSERT_NE(message.map_int32_int32().find(1), message.map_int32_int32().end());
2597   EXPECT_EQ(0, message.map_int32_int32().at(1));
2598 }
2599 
TEST(GeneratedMapFieldTest,MissedValueTextFormat)2600 TEST(GeneratedMapFieldTest, MissedValueTextFormat) {
2601   unittest::TestMap message;
2602 
2603   // No value field in text format
2604   std::string text =
2605       "map_int32_foreign_message {\n"
2606       "  key: 1234567890\n"
2607       "}";
2608 
2609   EXPECT_TRUE(TextFormat::ParseFromString(text, &message));
2610   EXPECT_EQ(1, message.map_int32_foreign_message().size());
2611   EXPECT_EQ(11, message.ByteSizeLong());
2612 }
2613 
TEST(GeneratedMapFieldTest,UnknownFieldWireFormat)2614 TEST(GeneratedMapFieldTest, UnknownFieldWireFormat) {
2615   unittest::TestMap message;
2616 
2617   // Unknown field in wire format
2618   std::string data = "\x0A\x06\x08\x02\x10\x03\x18\x01";
2619 
2620   EXPECT_TRUE(message.ParseFromString(data));
2621   EXPECT_EQ(1, message.map_int32_int32().size());
2622   EXPECT_EQ(3, message.map_int32_int32().at(2));
2623 }
2624 
TEST(GeneratedMapFieldTest,CorruptedWireFormat)2625 TEST(GeneratedMapFieldTest, CorruptedWireFormat) {
2626   unittest::TestMap message;
2627 
2628   // corrupted data in wire format
2629   std::string data = "\x0A\x06\x08\x02\x11\x03";
2630 
2631   EXPECT_FALSE(message.ParseFromString(data));
2632 }
2633 
TEST(GeneratedMapFieldTest,IsInitialized)2634 TEST(GeneratedMapFieldTest, IsInitialized) {
2635   unittest::TestRequiredMessageMap map_message;
2636 
2637   // Add an uninitialized message.
2638   (*map_message.mutable_map_field())[0];
2639   EXPECT_FALSE(map_message.IsInitialized());
2640 
2641   // Initialize uninitialized message
2642   (*map_message.mutable_map_field())[0].set_a(0);
2643   (*map_message.mutable_map_field())[0].set_b(0);
2644   (*map_message.mutable_map_field())[0].set_c(0);
2645   EXPECT_TRUE(map_message.IsInitialized());
2646 }
2647 
TEST(GeneratedMapFieldTest,SpaceUsed)2648 TEST(GeneratedMapFieldTest, SpaceUsed) {
2649   unittest::TestRequiredMessageMap map_message;
2650   const size_t initial = map_message.SpaceUsed();
2651   const size_t space_used_message = unittest::TestRequired().SpaceUsed();
2652 
2653   auto& m = *map_message.mutable_map_field();
2654   constexpr int kNumValues = 100;
2655   for (int i = 0; i < kNumValues; ++i) {
2656     m[i];
2657   }
2658 
2659   // The exact value will depend on internal state, like collisions,
2660   // so we can't predict it. But we can predict a lower bound.
2661   size_t lower_bound =
2662       initial + kNumValues * (space_used_message + sizeof(int32) +
2663                               /* Node::next */ sizeof(void*) +
2664                               /* table entry */ sizeof(void*));
2665 
2666   EXPECT_LE(lower_bound, map_message.SpaceUsed());
2667 }
2668 
TEST(GeneratedMapFieldTest,MessagesMustMerge)2669 TEST(GeneratedMapFieldTest, MessagesMustMerge) {
2670   unittest::TestRequiredMessageMap map_message;
2671 
2672   unittest::TestRequired with_dummy4;
2673   with_dummy4.set_a(97);
2674   with_dummy4.set_b(91);
2675   with_dummy4.set_dummy4(98);
2676   EXPECT_FALSE(with_dummy4.IsInitialized());
2677   (*map_message.mutable_map_field())[0] = with_dummy4;
2678   EXPECT_FALSE(map_message.IsInitialized());
2679 
2680   unittest::TestRequired with_dummy5;
2681   with_dummy5.set_b(0);
2682   with_dummy5.set_c(33);
2683   with_dummy5.set_dummy5(99);
2684   EXPECT_FALSE(with_dummy5.IsInitialized());
2685   (*map_message.mutable_map_field())[0] = with_dummy5;
2686   EXPECT_FALSE(map_message.IsInitialized());
2687 
2688   // The wire format of MapEntry is straightforward (*) and can be manually
2689   // constructed to force merging of two uninitialized messages that would
2690   // result in an initialized message.
2691   //
2692   // (*) http://google3/net/proto2/internal/map_test.cc?l=2433&rcl=310012028
2693   std::string dummy4_s = with_dummy4.SerializePartialAsString();
2694   std::string dummy5_s = with_dummy5.SerializePartialAsString();
2695   int payload_size = dummy4_s.size() + dummy5_s.size();
2696   // Makes sure the payload size fits into one byte.
2697   ASSERT_LT(payload_size, 128);
2698 
2699   std::string s(6, 0);
2700   char* p = &s[0];
2701   *p++ = WireFormatLite::MakeTag(1, WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
2702   // Length: 2B for key tag & val and 2B for val tag and length of the following
2703   // payload.
2704   *p++ = 4 + payload_size;
2705   *p++ = WireFormatLite::MakeTag(1, WireFormatLite::WIRETYPE_VARINT);
2706   *p++ = 0;
2707   *p++ = WireFormatLite::MakeTag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
2708   *p++ = payload_size;
2709   StrAppend(&s, dummy4_s, dummy5_s);
2710 
2711   // Test key then value then value.
2712   int key = 0;
2713   ASSERT_TRUE(map_message.ParseFromString(s));
2714   ASSERT_EQ(1, map_message.map_field().size());
2715   ASSERT_EQ(1, map_message.map_field().count(key));
2716   EXPECT_EQ(97, map_message.map_field().find(key)->second.a());
2717   EXPECT_EQ(0, map_message.map_field().find(key)->second.b());
2718   EXPECT_EQ(33, map_message.map_field().find(key)->second.c());
2719   EXPECT_EQ(98, map_message.map_field().find(key)->second.dummy4());
2720   EXPECT_EQ(99, map_message.map_field().find(key)->second.dummy5());
2721 
2722   // Test key then value then value then key.
2723   s.push_back(s[2]);  // Copy the key's tag.
2724   key = 19;
2725   s.push_back(key);  // Second key is 19 instead of 0.
2726   s[1] += 2;         // Adjust encoded size.
2727   ASSERT_TRUE(map_message.ParseFromString(s));
2728   ASSERT_EQ(1, map_message.map_field().size());
2729   ASSERT_EQ(1, map_message.map_field().count(key));
2730   EXPECT_EQ(97, map_message.map_field().find(key)->second.a());
2731   EXPECT_EQ(0, map_message.map_field().find(key)->second.b());
2732   EXPECT_EQ(33, map_message.map_field().find(key)->second.c());
2733   EXPECT_EQ(98, map_message.map_field().find(key)->second.dummy4());
2734   EXPECT_EQ(99, map_message.map_field().find(key)->second.dummy5());
2735 }
2736 
2737 // Generated Message Reflection Test ================================
2738 
TEST(GeneratedMapFieldReflectionTest,SpaceUsed)2739 TEST(GeneratedMapFieldReflectionTest, SpaceUsed) {
2740   unittest::TestMap message;
2741   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2742   reflection_tester.SetMapFieldsViaReflection(&message);
2743 
2744   EXPECT_LT(0, message.GetReflection()->SpaceUsedLong(message));
2745 }
2746 
TEST(GeneratedMapFieldReflectionTest,Accessors)2747 TEST(GeneratedMapFieldReflectionTest, Accessors) {
2748   // Set every field to a unique value then go back and check all those
2749   // values.
2750   unittest::TestMap message;
2751   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2752   reflection_tester.SetMapFieldsViaReflection(&message);
2753   MapTestUtil::ExpectMapFieldsSet(message);
2754   reflection_tester.ExpectMapFieldsSetViaReflection(message);
2755   reflection_tester.ExpectMapFieldsSetViaReflectionIterator(&message);
2756 
2757   reflection_tester.ModifyMapFieldsViaReflection(&message);
2758   MapTestUtil::ExpectMapFieldsModified(message);
2759 }
2760 
TEST(GeneratedMapFieldReflectionTest,Swap)2761 TEST(GeneratedMapFieldReflectionTest, Swap) {
2762   unittest::TestMap message1;
2763   unittest::TestMap message2;
2764 
2765   MapTestUtil::SetMapFields(&message1);
2766 
2767   const Reflection* reflection = message1.GetReflection();
2768   reflection->Swap(&message1, &message2);
2769 
2770   MapTestUtil::ExpectClear(message1);
2771   MapTestUtil::ExpectMapFieldsSet(message2);
2772 }
2773 
TEST(GeneratedMapFieldReflectionTest,SwapWithBothSet)2774 TEST(GeneratedMapFieldReflectionTest, SwapWithBothSet) {
2775   unittest::TestMap message1;
2776   unittest::TestMap message2;
2777 
2778   MapTestUtil::SetMapFields(&message1);
2779   MapTestUtil::SetMapFields(&message2);
2780   MapTestUtil::ModifyMapFields(&message2);
2781 
2782   const Reflection* reflection = message1.GetReflection();
2783   reflection->Swap(&message1, &message2);
2784 
2785   MapTestUtil::ExpectMapFieldsModified(message1);
2786   MapTestUtil::ExpectMapFieldsSet(message2);
2787 }
2788 
TEST(GeneratedMapFieldReflectionTest,SwapFields)2789 TEST(GeneratedMapFieldReflectionTest, SwapFields) {
2790   unittest::TestMap message1;
2791   unittest::TestMap message2;
2792 
2793   MapTestUtil::SetMapFields(&message2);
2794 
2795   std::vector<const FieldDescriptor*> fields;
2796   const Reflection* reflection = message1.GetReflection();
2797   reflection->ListFields(message2, &fields);
2798   reflection->SwapFields(&message1, &message2, fields);
2799 
2800   MapTestUtil::ExpectMapFieldsSet(message1);
2801   MapTestUtil::ExpectClear(message2);
2802 }
2803 
TEST(GeneratedMapFieldReflectionTest,ClearField)2804 TEST(GeneratedMapFieldReflectionTest, ClearField) {
2805   unittest::TestMap message;
2806   MapTestUtil::SetMapFields(&message);
2807   MapTestUtil::ExpectMapFieldsSet(message);
2808 
2809   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2810   reflection_tester.ClearMapFieldsViaReflection(&message);
2811   reflection_tester.ExpectClearViaReflection(message);
2812   reflection_tester.ExpectClearViaReflectionIterator(&message);
2813 }
2814 
TEST(GeneratedMapFieldReflectionTest,RemoveLast)2815 TEST(GeneratedMapFieldReflectionTest, RemoveLast) {
2816   unittest::TestMap message;
2817   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2818 
2819   MapTestUtil::SetMapFields(&message);
2820   MapTestUtil::ExpectMapsSize(message, 2);
2821   std::vector<const Message*> expected_entries =
2822       MapTestUtil::GetMapEntries(message, 0);
2823 
2824   reflection_tester.RemoveLastMapsViaReflection(&message);
2825 
2826   MapTestUtil::ExpectMapsSize(message, 1);
2827   std::vector<const Message*> remained_entries =
2828       MapTestUtil::GetMapEntries(message, 0);
2829   EXPECT_TRUE(expected_entries == remained_entries);
2830 }
2831 
TEST(GeneratedMapFieldReflectionTest,ReleaseLast)2832 TEST(GeneratedMapFieldReflectionTest, ReleaseLast) {
2833   unittest::TestMap message;
2834   const Descriptor* descriptor = message.GetDescriptor();
2835   MapReflectionTester reflection_tester(descriptor);
2836 
2837   MapTestUtil::SetMapFields(&message);
2838 
2839   MapTestUtil::ExpectMapsSize(message, 2);
2840 
2841   reflection_tester.ReleaseLastMapsViaReflection(&message);
2842 
2843   MapTestUtil::ExpectMapsSize(message, 1);
2844 
2845   // Now test that we actually release the right message.
2846   message.Clear();
2847   MapTestUtil::SetMapFields(&message);
2848 
2849   MapTestUtil::ExpectMapsSize(message, 2);
2850   std::vector<const Message*> expect_last =
2851       MapTestUtil::GetMapEntries(message, 1);
2852   std::vector<const Message*> release_last =
2853       MapTestUtil::GetMapEntriesFromRelease(&message);
2854   MapTestUtil::ExpectMapsSize(message, 1);
2855   EXPECT_TRUE(expect_last == release_last);
2856   for (std::vector<const Message*>::iterator it = release_last.begin();
2857        it != release_last.end(); ++it) {
2858     delete *it;
2859   }
2860 }
2861 
TEST(GeneratedMapFieldReflectionTest,SwapElements)2862 TEST(GeneratedMapFieldReflectionTest, SwapElements) {
2863   unittest::TestMap message;
2864   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2865 
2866   MapTestUtil::SetMapFields(&message);
2867 
2868   // Get pointers of map entries at their original position
2869   std::vector<const Message*> entries0 = MapTestUtil::GetMapEntries(message, 0);
2870   std::vector<const Message*> entries1 = MapTestUtil::GetMapEntries(message, 1);
2871 
2872   // Swap the first time.
2873   reflection_tester.SwapMapsViaReflection(&message);
2874 
2875   // Get pointer of map entry after swap once.
2876   std::vector<const Message*> entries0_once =
2877       MapTestUtil::GetMapEntries(message, 0);
2878   std::vector<const Message*> entries1_once =
2879       MapTestUtil::GetMapEntries(message, 1);
2880 
2881   // Test map entries are swapped.
2882   MapTestUtil::ExpectMapsSize(message, 2);
2883   EXPECT_TRUE(entries0 == entries1_once);
2884   EXPECT_TRUE(entries1 == entries0_once);
2885 
2886   // Swap the second time.
2887   reflection_tester.SwapMapsViaReflection(&message);
2888 
2889   // Get pointer of map entry after swap once.
2890   std::vector<const Message*> entries0_twice =
2891       MapTestUtil::GetMapEntries(message, 0);
2892   std::vector<const Message*> entries1_twice =
2893       MapTestUtil::GetMapEntries(message, 1);
2894 
2895   // Test map entries are swapped back.
2896   MapTestUtil::ExpectMapsSize(message, 2);
2897   EXPECT_TRUE(entries0 == entries0_twice);
2898   EXPECT_TRUE(entries1 == entries1_twice);
2899 }
2900 
TEST(GeneratedMapFieldReflectionTest,MutableUnknownFields)2901 TEST(GeneratedMapFieldReflectionTest, MutableUnknownFields) {
2902   unittest::TestMap message;
2903   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2904   reflection_tester.MutableUnknownFieldsOfMapFieldsViaReflection(&message);
2905 }
2906 
TEST(GeneratedMapFieldReflectionTest,EmbedProto2Message)2907 TEST(GeneratedMapFieldReflectionTest, EmbedProto2Message) {
2908   unittest::TestMessageMap message;
2909 
2910   const FieldDescriptor* map_field =
2911       unittest::TestMessageMap::descriptor()->FindFieldByName(
2912           "map_int32_message");
2913   const FieldDescriptor* value =
2914       map_field->message_type()->FindFieldByName("value");
2915 
2916   Message* entry_message =
2917       message.GetReflection()->AddMessage(&message, map_field);
2918   EXPECT_EQ(
2919       &entry_message->GetReflection()->GetMessage(*entry_message, value),
2920       reinterpret_cast<const Message*>(&TestAllTypes::default_instance()));
2921 
2922   Message* proto2_message =
2923       entry_message->GetReflection()->MutableMessage(entry_message, value);
2924   EXPECT_EQ(unittest::TestAllTypes::descriptor(),
2925             proto2_message->GetDescriptor());
2926   ASSERT_EQ(1, message.map_int32_message().size());
2927 }
2928 
TEST(GeneratedMapFieldReflectionTest,MergeFromClearMapEntry)2929 TEST(GeneratedMapFieldReflectionTest, MergeFromClearMapEntry) {
2930   unittest::TestMap message;
2931   const FieldDescriptor* map_field =
2932       unittest::TestMap::descriptor()->FindFieldByName("map_int32_int32");
2933   const FieldDescriptor* key =
2934       map_field->message_type()->FindFieldByName("key");
2935   const FieldDescriptor* value =
2936       map_field->message_type()->FindFieldByName("value");
2937 
2938   Message* entry_message1 =
2939       message.GetReflection()->AddMessage(&message, map_field);
2940   EXPECT_FALSE(entry_message1->GetReflection()->HasField(*entry_message1, key));
2941   EXPECT_FALSE(
2942       entry_message1->GetReflection()->HasField(*entry_message1, value));
2943 
2944   Message* entry_message2 =
2945       message.GetReflection()->AddMessage(&message, map_field);
2946   EXPECT_FALSE(entry_message2->GetReflection()->HasField(*entry_message2, key));
2947   EXPECT_FALSE(
2948       entry_message2->GetReflection()->HasField(*entry_message2, value));
2949 
2950   entry_message1->MergeFrom(*entry_message2);
2951   EXPECT_FALSE(entry_message1->GetReflection()->HasField(*entry_message1, key));
2952   EXPECT_FALSE(
2953       entry_message1->GetReflection()->HasField(*entry_message1, value));
2954 }
2955 
TEST(GeneratedMapFieldReflectionTest,MapEntryClear)2956 TEST(GeneratedMapFieldReflectionTest, MapEntryClear) {
2957   unittest::TestMap message;
2958   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2959   reflection_tester.MutableUnknownFieldsOfMapFieldsViaReflection(&message);
2960 }
2961 
TEST(GeneratedMapFieldReflectionTest,Proto2MapEntryClear)2962 TEST(GeneratedMapFieldReflectionTest, Proto2MapEntryClear) {
2963   unittest::TestEnumMap message;
2964   const Descriptor* descriptor = message.GetDescriptor();
2965   const FieldDescriptor* field_descriptor =
2966       descriptor->FindFieldByName("known_map_field");
2967   const FieldDescriptor* value_descriptor =
2968       field_descriptor->message_type()->FindFieldByName("value");
2969   Message* sub_message =
2970       message.GetReflection()->AddMessage(&message, field_descriptor);
2971   EXPECT_EQ(0, sub_message->GetReflection()->GetEnumValue(*sub_message,
2972                                                           value_descriptor));
2973 }
2974 
2975 // Map Reflection API Test =========================================
2976 
TEST(GeneratedMapFieldReflectionTest,SetViaMapReflection)2977 TEST(GeneratedMapFieldReflectionTest, SetViaMapReflection) {
2978   unittest::TestMap message;
2979   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
2980   reflection_tester.SetMapFieldsViaMapReflection(&message);
2981   reflection_tester.ExpectMapFieldsSetViaReflection(message);
2982   reflection_tester.ExpectMapFieldsSetViaReflectionIterator(&message);
2983 }
2984 
2985 // Dynamic Message Test =============================================
2986 
2987 class MapFieldInDynamicMessageTest : public testing::Test {
2988  protected:
2989   const DescriptorPool* pool_;
2990   DynamicMessageFactory factory_;
2991   const Descriptor* map_descriptor_;
2992   const Descriptor* recursive_map_descriptor_;
2993   const Message* map_prototype_;
2994 
MapFieldInDynamicMessageTest()2995   MapFieldInDynamicMessageTest()
2996       : pool_(DescriptorPool::generated_pool()), factory_(pool_) {}
2997 
SetUp()2998   virtual void SetUp() {
2999     map_descriptor_ = pool_->FindMessageTypeByName("protobuf_unittest.TestMap");
3000     recursive_map_descriptor_ =
3001         pool_->FindMessageTypeByName("protobuf_unittest.TestRecursiveMapMessage");
3002     ASSERT_TRUE(map_descriptor_ != NULL);
3003     ASSERT_TRUE(recursive_map_descriptor_ != NULL);
3004     map_prototype_ = factory_.GetPrototype(map_descriptor_);
3005   }
3006 };
3007 
TEST_F(MapFieldInDynamicMessageTest,MapIndependentOffsets)3008 TEST_F(MapFieldInDynamicMessageTest, MapIndependentOffsets) {
3009   // Check that all fields have independent offsets by setting each
3010   // one to a unique value then checking that they all still have those
3011   // unique values (i.e. they don't stomp each other).
3012   std::unique_ptr<Message> message(map_prototype_->New());
3013   MapReflectionTester reflection_tester(map_descriptor_);
3014 
3015   reflection_tester.SetMapFieldsViaReflection(message.get());
3016   reflection_tester.ExpectMapFieldsSetViaReflection(*message);
3017 }
3018 
TEST_F(MapFieldInDynamicMessageTest,DynamicMapReflection)3019 TEST_F(MapFieldInDynamicMessageTest, DynamicMapReflection) {
3020   // Check that map fields work properly.
3021   std::unique_ptr<Message> message(map_prototype_->New());
3022 
3023   // Check set functions.
3024   MapReflectionTester reflection_tester(map_descriptor_);
3025   reflection_tester.SetMapFieldsViaMapReflection(message.get());
3026   reflection_tester.ExpectMapFieldsSetViaReflection(*message);
3027 }
3028 
TEST_F(MapFieldInDynamicMessageTest,MapSpaceUsed)3029 TEST_F(MapFieldInDynamicMessageTest, MapSpaceUsed) {
3030   // Test that SpaceUsedLong() works properly
3031 
3032   // Since we share the implementation with generated messages, we don't need
3033   // to test very much here.  Just make sure it appears to be working.
3034 
3035   std::unique_ptr<Message> message(map_prototype_->New());
3036   MapReflectionTester reflection_tester(map_descriptor_);
3037 
3038   int initial_space_used = message->SpaceUsedLong();
3039 
3040   reflection_tester.SetMapFieldsViaReflection(message.get());
3041   EXPECT_LT(initial_space_used, message->SpaceUsedLong());
3042 }
3043 
TEST_F(MapFieldInDynamicMessageTest,RecursiveMap)3044 TEST_F(MapFieldInDynamicMessageTest, RecursiveMap) {
3045   TestRecursiveMapMessage from;
3046   (*from.mutable_a())[""];
3047   std::string data = from.SerializeAsString();
3048   std::unique_ptr<Message> to(
3049       factory_.GetPrototype(recursive_map_descriptor_)->New());
3050   ASSERT_TRUE(to->ParseFromString(data));
3051 }
3052 
TEST_F(MapFieldInDynamicMessageTest,MapValueReferernceValidAfterSerialize)3053 TEST_F(MapFieldInDynamicMessageTest, MapValueReferernceValidAfterSerialize) {
3054   std::unique_ptr<Message> message(map_prototype_->New());
3055   MapReflectionTester reflection_tester(map_descriptor_);
3056   reflection_tester.SetMapFieldsViaMapReflection(message.get());
3057 
3058   // Get value reference before serialization, so that we know the value is from
3059   // map.
3060   MapKey map_key;
3061   MapValueRef map_val;
3062   map_key.SetInt32Value(0);
3063   reflection_tester.GetMapValueViaMapReflection(
3064       message.get(), "map_int32_foreign_message", map_key, &map_val);
3065   Message* submsg = map_val.MutableMessageValue();
3066 
3067   // In previous implementation, calling SerializeToString will cause syncing
3068   // from map to repeated field, which will invalidate the submsg we previously
3069   // got.
3070   std::string data;
3071   message->SerializeToString(&data);
3072 
3073   const Reflection* submsg_reflection = submsg->GetReflection();
3074   const Descriptor* submsg_desc = submsg->GetDescriptor();
3075   const FieldDescriptor* submsg_field = submsg_desc->FindFieldByName("c");
3076   submsg_reflection->SetInt32(submsg, submsg_field, 128);
3077 
3078   message->SerializeToString(&data);
3079   TestMap to;
3080   to.ParseFromString(data);
3081   EXPECT_EQ(128, to.map_int32_foreign_message().at(0).c());
3082 }
3083 
TEST_F(MapFieldInDynamicMessageTest,MapEntryReferernceValidAfterSerialize)3084 TEST_F(MapFieldInDynamicMessageTest, MapEntryReferernceValidAfterSerialize) {
3085   std::unique_ptr<Message> message(map_prototype_->New());
3086   MapReflectionTester reflection_tester(map_descriptor_);
3087   reflection_tester.SetMapFieldsViaReflection(message.get());
3088 
3089   // Get map entry before serialization, so that we know the it is from
3090   // repeated field.
3091   Message* map_entry = reflection_tester.GetMapEntryViaReflection(
3092       message.get(), "map_int32_foreign_message", 0);
3093   const Reflection* map_entry_reflection = map_entry->GetReflection();
3094   const Descriptor* map_entry_desc = map_entry->GetDescriptor();
3095   const FieldDescriptor* value_field = map_entry_desc->FindFieldByName("value");
3096   Message* submsg =
3097       map_entry_reflection->MutableMessage(map_entry, value_field);
3098 
3099   // In previous implementation, calling SerializeToString will cause syncing
3100   // from repeated field to map, which will invalidate the map_entry we
3101   // previously got.
3102   std::string data;
3103   message->SerializeToString(&data);
3104 
3105   const Reflection* submsg_reflection = submsg->GetReflection();
3106   const Descriptor* submsg_desc = submsg->GetDescriptor();
3107   const FieldDescriptor* submsg_field = submsg_desc->FindFieldByName("c");
3108   submsg_reflection->SetInt32(submsg, submsg_field, 128);
3109 
3110   message->SerializeToString(&data);
3111   TestMap to;
3112   to.ParseFromString(data);
3113   EXPECT_EQ(128, to.map_int32_foreign_message().at(0).c());
3114 }
3115 
3116 // ReflectionOps Test ===============================================
3117 
TEST(ReflectionOpsForMapFieldTest,MapSanityCheck)3118 TEST(ReflectionOpsForMapFieldTest, MapSanityCheck) {
3119   unittest::TestMap message;
3120 
3121   MapTestUtil::SetMapFields(&message);
3122   MapTestUtil::ExpectMapFieldsSet(message);
3123 }
3124 
TEST(ReflectionOpsForMapFieldTest,MapCopy)3125 TEST(ReflectionOpsForMapFieldTest, MapCopy) {
3126   unittest::TestMap message, message2;
3127 
3128   MapTestUtil::SetMapFields(&message);
3129 
3130   ReflectionOps::Copy(message, &message2);
3131 
3132   MapTestUtil::ExpectMapFieldsSet(message2);
3133 
3134   // Copying from self should be a no-op.
3135   ReflectionOps::Copy(message2, &message2);
3136   MapTestUtil::ExpectMapFieldsSet(message2);
3137 }
3138 
TEST(ReflectionOpsForMapFieldTest,MergeMap)3139 TEST(ReflectionOpsForMapFieldTest, MergeMap) {
3140   // Note:  Copy is implemented in terms of Merge() so technically the Copy
3141   //   test already tested most of this.
3142 
3143   unittest::TestMap message, message2;
3144 
3145   MapTestUtil::SetMapFields(&message);
3146 
3147   ReflectionOps::Merge(message2, &message);
3148 
3149   MapTestUtil::ExpectMapFieldsSet(message);
3150 }
3151 
TEST(ReflectionOpsForMapFieldTest,ClearMap)3152 TEST(ReflectionOpsForMapFieldTest, ClearMap) {
3153   unittest::TestMap message;
3154 
3155   MapTestUtil::SetMapFields(&message);
3156 
3157   ReflectionOps::Clear(&message);
3158 
3159   MapTestUtil::ExpectClear(message);
3160 }
3161 
TEST(ReflectionOpsForMapFieldTest,MapDiscardUnknownFields)3162 TEST(ReflectionOpsForMapFieldTest, MapDiscardUnknownFields) {
3163   unittest::TestMap message;
3164   MapTestUtil::SetMapFields(&message);
3165 
3166   // Set some unknown fields in message.
3167   message.GetReflection()->MutableUnknownFields(&message)->AddVarint(123456,
3168                                                                      654321);
3169 
3170   // Discard them.
3171   ReflectionOps::DiscardUnknownFields(&message);
3172   MapTestUtil::ExpectMapFieldsSet(message);
3173 
3174   EXPECT_EQ(0,
3175             message.GetReflection()->GetUnknownFields(message).field_count());
3176 }
3177 
TEST(ReflectionOpsForMapFieldTest,IsInitialized)3178 TEST(ReflectionOpsForMapFieldTest, IsInitialized) {
3179   unittest::TestRequiredMessageMap map_message;
3180 
3181   // Add an uninitialized message.
3182   (*map_message.mutable_map_field())[0];
3183   EXPECT_FALSE(ReflectionOps::IsInitialized(map_message));
3184 
3185   // Initialize uninitialized message
3186   (*map_message.mutable_map_field())[0].set_a(0);
3187   (*map_message.mutable_map_field())[0].set_b(0);
3188   (*map_message.mutable_map_field())[0].set_c(0);
3189   EXPECT_TRUE(ReflectionOps::IsInitialized(map_message));
3190 }
3191 
3192 // Wire Format Test =================================================
3193 
TEST(WireFormatForMapFieldTest,ParseMap)3194 TEST(WireFormatForMapFieldTest, ParseMap) {
3195   unittest::TestMap source, dest;
3196   std::string data;
3197 
3198   // Serialize using the generated code.
3199   MapTestUtil::SetMapFields(&source);
3200   source.SerializeToString(&data);
3201 
3202   // Parse using WireFormat.
3203   io::ArrayInputStream raw_input(data.data(), data.size());
3204   io::CodedInputStream input(&raw_input);
3205   WireFormat::ParseAndMergePartial(&input, &dest);
3206 
3207   // Check.
3208   MapTestUtil::ExpectMapFieldsSet(dest);
3209 }
3210 
TEST(WireFormatForMapFieldTest,MapByteSize)3211 TEST(WireFormatForMapFieldTest, MapByteSize) {
3212   unittest::TestMap message;
3213   MapTestUtil::SetMapFields(&message);
3214 
3215   EXPECT_EQ(message.ByteSizeLong(), WireFormat::ByteSize(message));
3216   message.Clear();
3217   EXPECT_EQ(0, message.ByteSizeLong());
3218   EXPECT_EQ(0, WireFormat::ByteSize(message));
3219 }
3220 
TEST(WireFormatForMapFieldTest,SerializeMap)3221 TEST(WireFormatForMapFieldTest, SerializeMap) {
3222   unittest::TestMap message;
3223   std::string generated_data;
3224   std::string dynamic_data;
3225 
3226   MapTestUtil::SetMapFields(&message);
3227 
3228   // Serialize using the generated code.
3229   {
3230     message.ByteSizeLong();
3231     io::StringOutputStream raw_output(&generated_data);
3232     io::CodedOutputStream output(&raw_output);
3233     message.SerializeWithCachedSizes(&output);
3234     ASSERT_FALSE(output.HadError());
3235   }
3236 
3237   // Serialize using WireFormat.
3238   {
3239     io::StringOutputStream raw_output(&dynamic_data);
3240     io::CodedOutputStream output(&raw_output);
3241     size_t size = WireFormat::ByteSize(message);
3242     WireFormat::SerializeWithCachedSizes(message, size, &output);
3243     ASSERT_FALSE(output.HadError());
3244   }
3245 
3246   // Should parse to the same message.
3247   EXPECT_TRUE(TestUtil::EqualsToSerialized(message, generated_data));
3248   EXPECT_TRUE(TestUtil::EqualsToSerialized(message, dynamic_data));
3249 }
3250 
TEST(WireFormatForMapFieldTest,SerializeMapDynamicMessage)3251 TEST(WireFormatForMapFieldTest, SerializeMapDynamicMessage) {
3252   DynamicMessageFactory factory;
3253   std::unique_ptr<Message> dynamic_message;
3254   dynamic_message.reset(
3255       factory.GetPrototype(unittest::TestMap::descriptor())->New());
3256   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
3257   reflection_tester.SetMapFieldsViaReflection(dynamic_message.get());
3258   reflection_tester.ExpectMapFieldsSetViaReflection(*dynamic_message);
3259 
3260   unittest::TestMap generated_message;
3261   MapTestUtil::SetMapFields(&generated_message);
3262   MapTestUtil::ExpectMapFieldsSet(generated_message);
3263 
3264   std::string generated_data;
3265   std::string dynamic_data;
3266 
3267   // Serialize.
3268   generated_message.SerializeToString(&generated_data);
3269   dynamic_message->SerializeToString(&dynamic_data);
3270 
3271   // Because map serialization doesn't guarantee order, we just compare
3272   // serialized size here. This is enough to tell dynamic message doesn't miss
3273   // anything in serialization.
3274   EXPECT_TRUE(dynamic_data.size() == generated_data.size());
3275 }
3276 
TEST(WireFormatForMapFieldTest,MapByteSizeDynamicMessage)3277 TEST(WireFormatForMapFieldTest, MapByteSizeDynamicMessage) {
3278   DynamicMessageFactory factory;
3279   std::unique_ptr<Message> dynamic_message;
3280   dynamic_message.reset(
3281       factory.GetPrototype(unittest::TestMap::descriptor())->New());
3282   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
3283   reflection_tester.SetMapFieldsViaReflection(dynamic_message.get());
3284   reflection_tester.ExpectMapFieldsSetViaReflection(*dynamic_message);
3285   std::string expected_serialized_data;
3286   dynamic_message->SerializeToString(&expected_serialized_data);
3287   int expected_size = expected_serialized_data.size();
3288   EXPECT_EQ(dynamic_message->ByteSizeLong(), expected_size);
3289 
3290   std::unique_ptr<Message> message2;
3291   message2.reset(factory.GetPrototype(unittest::TestMap::descriptor())->New());
3292   reflection_tester.SetMapFieldsViaMapReflection(message2.get());
3293 
3294   const FieldDescriptor* field =
3295       unittest::TestMap::descriptor()->FindFieldByName("map_int32_int32");
3296   const Reflection* reflection = dynamic_message->GetReflection();
3297 
3298   // Force the map field to mark with STATE_MODIFIED_REPEATED
3299   reflection->RemoveLast(dynamic_message.get(), field);
3300   dynamic_message->MergeFrom(*message2);
3301   dynamic_message->MergeFrom(*message2);
3302   // The map field is marked as STATE_MODIFIED_REPEATED, ByteSizeLong() will use
3303   // repeated field which have duplicate keys to calculate.
3304   size_t duplicate_size = dynamic_message->ByteSizeLong();
3305   EXPECT_TRUE(duplicate_size > expected_size);
3306   std::string duplicate_serialized_data;
3307   dynamic_message->SerializeToString(&duplicate_serialized_data);
3308   EXPECT_EQ(dynamic_message->ByteSizeLong(), duplicate_serialized_data.size());
3309 
3310   // Force the map field to mark with map CLEAN
3311   EXPECT_EQ(reflection_tester.MapSize(*dynamic_message, "map_int32_int32"), 2);
3312   // The map field is marked as CLEAN, ByteSizeLong() will use map which do not
3313   // have duplicate keys to calculate.
3314   int size = dynamic_message->ByteSizeLong();
3315   EXPECT_EQ(expected_size, size);
3316 
3317   // Protobuf used to have a bug for serialize when map it marked CLEAN. It used
3318   // repeated field to calculate ByteSizeLong but use map to serialize the real
3319   // data, thus the ByteSizeLong may bigger than real serialized size. A crash
3320   // might be happen at SerializeToString(). Or an "unexpected end group"
3321   // warning was raised at parse back if user use SerializeWithCachedSizes()
3322   // which avoids size check at serialize.
3323   std::string serialized_data;
3324   dynamic_message->SerializeToString(&serialized_data);
3325   EXPECT_EQ(serialized_data, expected_serialized_data);
3326   dynamic_message->ParseFromString(serialized_data);
3327 }
3328 
TEST(WireFormatForMapFieldTest,MapParseHelpers)3329 TEST(WireFormatForMapFieldTest, MapParseHelpers) {
3330   std::string data;
3331 
3332   {
3333     // Set up.
3334     protobuf_unittest::TestMap message;
3335     MapTestUtil::SetMapFields(&message);
3336     message.SerializeToString(&data);
3337   }
3338 
3339   {
3340     // Test ParseFromString.
3341     protobuf_unittest::TestMap message;
3342     EXPECT_TRUE(message.ParseFromString(data));
3343     MapTestUtil::ExpectMapFieldsSet(message);
3344   }
3345 
3346   {
3347     // Test ParseFromIstream.
3348     protobuf_unittest::TestMap message;
3349     std::stringstream stream(data);
3350     EXPECT_TRUE(message.ParseFromIstream(&stream));
3351     EXPECT_TRUE(stream.eof());
3352     MapTestUtil::ExpectMapFieldsSet(message);
3353   }
3354 
3355   {
3356     // Test ParseFromBoundedZeroCopyStream.
3357     std::string data_with_junk(data);
3358     data_with_junk.append("some junk on the end");
3359     io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size());
3360     protobuf_unittest::TestMap message;
3361     EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size()));
3362     MapTestUtil::ExpectMapFieldsSet(message);
3363   }
3364 
3365   {
3366     // Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if
3367     // EOF is reached before the expected number of bytes.
3368     io::ArrayInputStream stream(data.data(), data.size());
3369     protobuf_unittest::TestAllTypes message;
3370     EXPECT_FALSE(
3371         message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1));
3372   }
3373 }
3374 
3375 // Deterministic Serialization Test ==========================================
3376 
3377 template <typename T>
DeterministicSerializationWithSerializePartialToCodedStream(const T & t)3378 static std::string DeterministicSerializationWithSerializePartialToCodedStream(
3379     const T& t) {
3380   const size_t size = t.ByteSizeLong();
3381   std::string result(size, '\0');
3382   io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size);
3383   io::CodedOutputStream output_stream(&array_stream);
3384   output_stream.SetSerializationDeterministic(true);
3385   t.SerializePartialToCodedStream(&output_stream);
3386   EXPECT_FALSE(output_stream.HadError());
3387   EXPECT_EQ(size, output_stream.ByteCount());
3388   return result;
3389 }
3390 
3391 template <typename T>
DeterministicSerializationWithSerializeToCodedStream(const T & t)3392 static std::string DeterministicSerializationWithSerializeToCodedStream(
3393     const T& t) {
3394   const size_t size = t.ByteSizeLong();
3395   std::string result(size, '\0');
3396   io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size);
3397   io::CodedOutputStream output_stream(&array_stream);
3398   output_stream.SetSerializationDeterministic(true);
3399   t.SerializeToCodedStream(&output_stream);
3400   EXPECT_FALSE(output_stream.HadError());
3401   EXPECT_EQ(size, output_stream.ByteCount());
3402   return result;
3403 }
3404 
3405 template <typename T>
DeterministicSerialization(const T & t)3406 static std::string DeterministicSerialization(const T& t) {
3407   const size_t size = t.ByteSizeLong();
3408   std::string result(size, '\0');
3409   io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size);
3410   {
3411     io::CodedOutputStream output_stream(&array_stream);
3412     output_stream.SetSerializationDeterministic(true);
3413     t.SerializeWithCachedSizes(&output_stream);
3414     EXPECT_FALSE(output_stream.HadError());
3415     EXPECT_EQ(size, output_stream.ByteCount());
3416   }
3417   EXPECT_EQ(result, DeterministicSerializationWithSerializeToCodedStream(t));
3418   EXPECT_EQ(result,
3419             DeterministicSerializationWithSerializePartialToCodedStream(t));
3420   return result;
3421 }
3422 
3423 // Helper for MapSerializationTest.  Return a 7-bit ASCII string.
ConstructKey(uint64 n)3424 static std::string ConstructKey(uint64 n) {
3425   std::string s(n % static_cast<uint64>(9), '\0');
3426   if (s.empty()) {
3427     return StrCat(n);
3428   } else {
3429     while (n != 0) {
3430       s[n % s.size()] = (n >> 10) & 0x7f;
3431       n /= 888;
3432     }
3433     return s;
3434   }
3435 }
3436 
TEST(MapSerializationTest,Deterministic)3437 TEST(MapSerializationTest, Deterministic) {
3438   const int kIters = 25;
3439   protobuf_unittest::TestMaps t;
3440   protobuf_unittest::TestIntIntMap inner;
3441   (*inner.mutable_m())[0] = (*inner.mutable_m())[10] =
3442       (*inner.mutable_m())[-200] = 0;
3443   uint64 frog = 9;
3444   const uint64 multiplier = 0xa29cd16f;
3445   for (int i = 0; i < kIters; i++) {
3446     const int32 i32 = static_cast<int32>(frog & 0xffffffff);
3447     const uint32 u32 = static_cast<uint32>(i32) * 91919;
3448     const int64 i64 = static_cast<int64>(frog);
3449     const uint64 u64 = frog * static_cast<uint64>(187321);
3450     const bool b = i32 > 0;
3451     const std::string s = ConstructKey(frog);
3452     (*inner.mutable_m())[i] = i32;
3453     (*t.mutable_m_int32())[i32] = (*t.mutable_m_sint32())[i32] =
3454         (*t.mutable_m_sfixed32())[i32] = inner;
3455     (*t.mutable_m_uint32())[u32] = (*t.mutable_m_fixed32())[u32] = inner;
3456     (*t.mutable_m_int64())[i64] = (*t.mutable_m_sint64())[i64] =
3457         (*t.mutable_m_sfixed64())[i64] = inner;
3458     (*t.mutable_m_uint64())[u64] = (*t.mutable_m_fixed64())[u64] = inner;
3459     (*t.mutable_m_bool())[b] = inner;
3460     (*t.mutable_m_string())[s] = inner;
3461     (*t.mutable_m_string())[s + std::string(1 << (u32 % static_cast<uint32>(9)),
3462                                             b)] = inner;
3463     inner.mutable_m()->erase(i);
3464     frog = frog * multiplier + i;
3465     frog ^= (frog >> 41);
3466   }
3467 
3468   // Verifies if two consecutive calls to deterministic serialization produce
3469   // the same bytes. Deterministic serialization means the same serialization
3470   // bytes in the same binary.
3471   const std::string s1 = DeterministicSerialization(t);
3472   const std::string s2 = DeterministicSerialization(t);
3473   EXPECT_EQ(s1, s2);
3474 
3475   protobuf_unittest::TestMaps u;
3476   EXPECT_TRUE(u.ParseFromString(s1));
3477   EXPECT_TRUE(util::MessageDifferencer::Equals(u, t));
3478 }
3479 
TEST(MapSerializationTest,DeterministicSubmessage)3480 TEST(MapSerializationTest, DeterministicSubmessage) {
3481   protobuf_unittest::TestSubmessageMaps p;
3482   protobuf_unittest::TestMaps t;
3483   const std::string filename = "golden_message_maps";
3484   std::string golden;
3485   GOOGLE_CHECK_OK(File::GetContents(
3486       TestUtil::GetTestDataPath("net/proto2/internal/testdata/" + filename),
3487       &golden, true));
3488   t.ParseFromString(golden);
3489   *(p.mutable_m()) = t;
3490   std::vector<std::string> v;
3491   // Use multiple attempts to increase the chance of a failure if something is
3492   // buggy.  For example, each separate copy of a map might use a different
3493   // randomly-chosen hash function.
3494   const int kAttempts = 10;
3495   for (int i = 0; i < kAttempts; i++) {
3496     protobuf_unittest::TestSubmessageMaps q(p);
3497     ASSERT_EQ(DeterministicSerialization(q), DeterministicSerialization(p));
3498   }
3499 }
3500 
3501 // Text Format Test =================================================
3502 
TEST(TextFormatMapTest,SerializeAndParse)3503 TEST(TextFormatMapTest, SerializeAndParse) {
3504   unittest::TestMap source;
3505   unittest::TestMap dest;
3506   MapTestUtil::SetMapFields(&source);
3507   std::string output;
3508 
3509   // Test compact ASCII
3510   TextFormat::Printer printer;
3511   printer.PrintToString(source, &output);
3512   TextFormat::Parser parser;
3513   EXPECT_TRUE(parser.ParseFromString(output, &dest));
3514   MapTestUtil::ExpectMapFieldsSet(dest);
3515 }
3516 
TEST(TextFormatMapTest,DynamicMessage)3517 TEST(TextFormatMapTest, DynamicMessage) {
3518   TestMap prototype;
3519   DynamicMessageFactory factory;
3520   std::unique_ptr<Message> message(
3521       factory.GetPrototype(prototype.GetDescriptor())->New());
3522   MapReflectionTester tester(message->GetDescriptor());
3523   tester.SetMapFieldsViaReflection(message.get());
3524 
3525   std::string expected_text;
3526   GOOGLE_CHECK_OK(
3527       File::GetContents(TestUtil::GetTestDataPath("net/proto2/internal/"
3528                                                   "testdata/map_test_data.txt"),
3529                         &expected_text, true));
3530 
3531   EXPECT_EQ(message->DebugString(), expected_text);
3532 }
3533 
TEST(TextFormatMapTest,Sorted)3534 TEST(TextFormatMapTest, Sorted) {
3535   unittest::TestMap message;
3536   MapReflectionTester tester(message.GetDescriptor());
3537   tester.SetMapFieldsViaReflection(&message);
3538 
3539   std::string expected_text;
3540   GOOGLE_CHECK_OK(
3541       File::GetContents(TestUtil::GetTestDataPath("net/proto2/internal/"
3542                                                   "testdata/map_test_data.txt"),
3543                         &expected_text, true));
3544 
3545   CleanStringLineEndings(&expected_text, false);
3546   EXPECT_EQ(message.DebugString(), expected_text);
3547 
3548   // Test again on the reverse order.
3549   unittest::TestMap message2;
3550   tester.SetMapFieldsViaReflection(&message2);
3551   tester.SwapMapsViaReflection(&message2);
3552   EXPECT_EQ(message2.DebugString(), expected_text);
3553 }
3554 
TEST(TextFormatMapTest,ParseCorruptedString)3555 TEST(TextFormatMapTest, ParseCorruptedString) {
3556   std::string serialized_message;
3557   GOOGLE_CHECK_OK(
3558       File::GetContents(TestUtil::GetTestDataPath(
3559                             "net/proto2/internal/testdata/golden_message_maps"),
3560                         &serialized_message, true));
3561   protobuf_unittest::TestMaps message;
3562   GOOGLE_CHECK(message.ParseFromString(serialized_message));
3563   TestParseCorruptedString<protobuf_unittest::TestMaps, true>(message);
3564   TestParseCorruptedString<protobuf_unittest::TestMaps, false>(message);
3565 }
3566 
3567 // Previously, serializing to text format will disable iterator from generated
3568 // API. Now, the iterator can be still used even after serializing to text
3569 // format.
TEST(TextFormatMapTest,NoDisableIterator)3570 TEST(TextFormatMapTest, NoDisableIterator) {
3571   unittest::TestMap source;
3572   (*source.mutable_map_int32_int32())[1] = 1;
3573 
3574   // Get iterator.
3575   Map<int32, int32>::iterator iter = source.mutable_map_int32_int32()->find(1);
3576 
3577   // Serialize message to text format, which will invalidate the previous
3578   // iterator previously.
3579   std::string output;
3580   TextFormat::Printer printer;
3581   printer.PrintToString(source, &output);
3582 
3583   // Modify map via the iterator (invalidated in previous implementation.).
3584   iter->second = 2;
3585 
3586   // In previous implementation, the new change won't be reflected in text
3587   // format, because the previous iterator has been invalidated.
3588   output.clear();
3589   printer.PrintToString(source, &output);
3590   std::string expected =
3591       "map_int32_int32 {\n"
3592       "  key: 1\n"
3593       "  value: 2\n"
3594       "}\n";
3595   EXPECT_EQ(output, expected);
3596 }
3597 
3598 // Previously, serializing to text format will disable iterator from reflection
3599 // API.
TEST(TextFormatMapTest,NoDisableReflectionIterator)3600 TEST(TextFormatMapTest, NoDisableReflectionIterator) {
3601   unittest::TestMap source;
3602   (*source.mutable_map_int32_int32())[1] = 1;
3603 
3604   // Get iterator. This will also sync internal repeated field with map inside
3605   // of MapField.
3606   const Reflection* reflection = source.GetReflection();
3607   const FieldDescriptor* field_desc =
3608       source.GetDescriptor()->FindFieldByName("map_int32_int32");
3609   RepeatedPtrField<Message>* map_field =
3610       reflection->MutableRepeatedPtrField<Message>(&source, field_desc);
3611   RepeatedPtrField<Message>::iterator iter = map_field->begin();
3612 
3613   // Serialize message to text format, which will invalidate the previous
3614   // iterator previously.
3615   std::string output;
3616   TextFormat::Printer printer;
3617   printer.PrintToString(source, &output);
3618 
3619   // Modify map via the iterator (invalidated in previous implementation.).
3620   const Reflection* map_entry_reflection = iter->GetReflection();
3621   const FieldDescriptor* value_field_desc =
3622       iter->GetDescriptor()->FindFieldByName("value");
3623   map_entry_reflection->SetInt32(&(*iter), value_field_desc, 2);
3624   GOOGLE_LOG(INFO) << iter->DebugString();
3625 
3626   // In previous implementation, the new change won't be reflected in text
3627   // format, because the previous iterator has been invalidated.
3628   output.clear();
3629   printer.PrintToString(source, &output);
3630   std::string expected =
3631       "map_int32_int32 {\n"
3632       "  key: 1\n"
3633       "  value: 2\n"
3634       "}\n";
3635   EXPECT_EQ(output, expected);
3636 }
3637 
3638 
3639 // arena support =================================================
TEST(ArenaTest,ParsingAndSerializingNoHeapAllocation)3640 TEST(ArenaTest, ParsingAndSerializingNoHeapAllocation) {
3641   // Allocate a large initial block to avoid mallocs during hooked test.
3642   std::vector<char> arena_block(128 * 1024);
3643   ArenaOptions options;
3644   options.initial_block = &arena_block[0];
3645   options.initial_block_size = arena_block.size();
3646   Arena arena(options);
3647   std::string data;
3648   data.reserve(128 * 1024);
3649 
3650   {
3651     // TODO(teboring): Enable no heap check when ArenaStringPtr is used in map.
3652     // NoHeapChecker no_heap;
3653 
3654     unittest::TestArenaMap* from =
3655         Arena::CreateMessage<unittest::TestArenaMap>(&arena);
3656     MapTestUtil::SetArenaMapFields(from);
3657     from->SerializeToString(&data);
3658 
3659     unittest::TestArenaMap* to =
3660         Arena::CreateMessage<unittest::TestArenaMap>(&arena);
3661     to->ParseFromString(data);
3662     MapTestUtil::ExpectArenaMapFieldsSet(*to);
3663   }
3664 }
3665 
3666 // Use text format parsing and serializing to test reflection api.
TEST(ArenaTest,ReflectionInTextFormat)3667 TEST(ArenaTest, ReflectionInTextFormat) {
3668   Arena arena;
3669   std::string data;
3670 
3671   TextFormat::Printer printer;
3672   TextFormat::Parser parser;
3673 
3674   unittest::TestArenaMap* from =
3675       Arena::CreateMessage<unittest::TestArenaMap>(&arena);
3676   unittest::TestArenaMap* to =
3677       Arena::CreateMessage<unittest::TestArenaMap>(&arena);
3678 
3679   MapTestUtil::SetArenaMapFields(from);
3680   printer.PrintToString(*from, &data);
3681 
3682   EXPECT_TRUE(parser.ParseFromString(data, to));
3683   MapTestUtil::ExpectArenaMapFieldsSet(*to);
3684 }
3685 
3686 // Make sure the memory allocated for string in map is deallocated.
TEST(ArenaTest,StringMapNoLeak)3687 TEST(ArenaTest, StringMapNoLeak) {
3688   Arena arena;
3689   unittest::TestArenaMap* message =
3690       Arena::CreateMessage<unittest::TestArenaMap>(&arena);
3691   std::string data;
3692   // String with length less than 16 will not be allocated from heap.
3693   int original_capacity = data.capacity();
3694   while (data.capacity() <= original_capacity) {
3695     data.append("a");
3696   }
3697   (*message->mutable_map_string_string())[data] = data;
3698   // We rely on heap checkers to detect memory leak for us.
3699   ASSERT_FALSE(message == NULL);
3700 }
3701 
TEST(ArenaTest,IsInitialized)3702 TEST(ArenaTest, IsInitialized) {
3703   // Allocate a large initial polluted block.
3704   std::vector<char> arena_block(128 * 1024);
3705   std::fill(arena_block.begin(), arena_block.end(), '\xff');
3706 
3707   ArenaOptions options;
3708   options.initial_block = &arena_block[0];
3709   options.initial_block_size = arena_block.size();
3710   Arena arena(options);
3711 
3712   unittest::TestArenaMap* message =
3713       Arena::CreateMessage<unittest::TestArenaMap>(&arena);
3714   EXPECT_EQ(0, (*message->mutable_map_int32_int32())[0]);
3715 }
3716 
TEST(ArenaTest,DynamicMapFieldOnArena)3717 TEST(ArenaTest, DynamicMapFieldOnArena) {
3718   Arena arena;
3719   unittest::TestMap message2;
3720 
3721   DynamicMessageFactory factory;
3722   Message* message1 =
3723       factory.GetPrototype(unittest::TestMap::descriptor())->New(&arena);
3724   MapReflectionTester reflection_tester(unittest::TestMap::descriptor());
3725   reflection_tester.SetMapFieldsViaReflection(message1);
3726   reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
3727   reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1);
3728   message2.CopyFrom(*message1);
3729   MapTestUtil::ExpectMapFieldsSet(message2);
3730 }
3731 
TEST(MoveTest,MoveConstructorWorks)3732 TEST(MoveTest, MoveConstructorWorks) {
3733   Map<int32, TestAllTypes> original_map;
3734   original_map[42].mutable_optional_nested_message()->set_bb(42);
3735   original_map[43].mutable_optional_nested_message()->set_bb(43);
3736   const auto* nested_msg42_ptr = &original_map[42].optional_nested_message();
3737   const auto* nested_msg43_ptr = &original_map[43].optional_nested_message();
3738 
3739   Map<int32, TestAllTypes> moved_to_map(std::move(original_map));
3740   EXPECT_TRUE(original_map.empty());
3741   EXPECT_EQ(2, moved_to_map.size());
3742   EXPECT_EQ(42, moved_to_map[42].optional_nested_message().bb());
3743   EXPECT_EQ(43, moved_to_map[43].optional_nested_message().bb());
3744   // This test takes advantage of the fact that pointers are swapped, so there
3745   // should be pointer stability.
3746   EXPECT_EQ(nested_msg42_ptr, &moved_to_map[42].optional_nested_message());
3747   EXPECT_EQ(nested_msg43_ptr, &moved_to_map[43].optional_nested_message());
3748 }
3749 
TEST(MoveTest,MoveAssignmentWorks)3750 TEST(MoveTest, MoveAssignmentWorks) {
3751   Map<int32, TestAllTypes> original_map;
3752   original_map[42].mutable_optional_nested_message()->set_bb(42);
3753   original_map[43].mutable_optional_nested_message()->set_bb(43);
3754   const auto* nested_msg42_ptr = &original_map[42].optional_nested_message();
3755   const auto* nested_msg43_ptr = &original_map[43].optional_nested_message();
3756 
3757   Map<int32, TestAllTypes> moved_to_map = std::move(original_map);
3758   EXPECT_TRUE(original_map.empty());
3759   EXPECT_EQ(2, moved_to_map.size());
3760   EXPECT_EQ(42, moved_to_map[42].optional_nested_message().bb());
3761   EXPECT_EQ(43, moved_to_map[43].optional_nested_message().bb());
3762   // This test takes advantage of the fact that pointers are swapped, so there
3763   // should be pointer stability.
3764   EXPECT_EQ(nested_msg42_ptr, &moved_to_map[42].optional_nested_message());
3765   EXPECT_EQ(nested_msg43_ptr, &moved_to_map[43].optional_nested_message());
3766 }
3767 
3768 
3769 }  // namespace
3770 }  // namespace internal
3771 }  // namespace protobuf
3772 }  // namespace google
3773