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