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