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 <google/protobuf/stubs/hash.h>
41 #include <map>
42 #include <memory>
43 #ifndef _SHARED_PTR_H
44 #include <google/protobuf/stubs/shared_ptr.h>
45 #endif
46 #include <set>
47 #include <sstream>
48 #include <vector>
49
50 #include <google/protobuf/stubs/casts.h>
51 #include <google/protobuf/stubs/logging.h>
52 #include <google/protobuf/stubs/common.h>
53 #include <google/protobuf/stubs/scoped_ptr.h>
54 #include <google/protobuf/stubs/stringprintf.h>
55 #include <google/protobuf/testing/file.h>
56 #include <google/protobuf/arena_test_util.h>
57 #include <google/protobuf/map_proto2_unittest.pb.h>
58 #include <google/protobuf/map_unittest.pb.h>
59 #include <google/protobuf/map_test_util.h>
60 #include <google/protobuf/test_util.h>
61 #include <google/protobuf/unittest.pb.h>
62 #include <google/protobuf/descriptor.pb.h>
63 #include <google/protobuf/descriptor.h>
64 #include <google/protobuf/descriptor_database.h>
65 #include <google/protobuf/dynamic_message.h>
66 #include <google/protobuf/map.h>
67 #include <google/protobuf/map_field_inl.h>
68 #include <google/protobuf/message.h>
69 #include <google/protobuf/reflection.h>
70 #include <google/protobuf/reflection_ops.h>
71 #include <google/protobuf/text_format.h>
72 #include <google/protobuf/wire_format.h>
73 #include <google/protobuf/wire_format_lite_inl.h>
74 #include <google/protobuf/io/coded_stream.h>
75 #include <google/protobuf/io/tokenizer.h>
76 #include <google/protobuf/io/zero_copy_stream_impl.h>
77 #include <google/protobuf/util/time_util.h>
78 #include <google/protobuf/stubs/strutil.h>
79 #include <google/protobuf/stubs/substitute.h>
80 #include <google/protobuf/testing/googletest.h>
81 #include <gtest/gtest.h>
82
83 namespace google {
84
85 using google::protobuf::unittest::ForeignMessage;
86 using google::protobuf::unittest::TestAllTypes;
87 using google::protobuf::unittest::TestMap;
88 using google::protobuf::unittest::TestRecursiveMapMessage;
89
90 namespace protobuf {
91 namespace internal {
92
93 // Map API Test =====================================================
94
95 // Parameterized tests on whether to use old style maps.
96 class MapImplTest : public testing::TestWithParam<bool> {
97 protected:
MapImplTest()98 MapImplTest()
99 : map_ptr_(new Map<int32, int32>(GetParam())),
100 map_(*map_ptr_),
101 const_map_(*map_ptr_) {
102 EXPECT_TRUE(map_.empty());
103 EXPECT_EQ(0, map_.size());
104 }
~MapImplTest()105 ~MapImplTest() {}
106
ExpectSingleElement(int32 key,int32 value)107 void ExpectSingleElement(int32 key, int32 value) {
108 EXPECT_FALSE(map_.empty());
109 EXPECT_EQ(1, map_.size());
110 ExpectElement(key, value);
111 }
112
ExpectElements(const std::map<int32,int32> & map)113 void ExpectElements(const std::map<int32, int32>& map) {
114 EXPECT_FALSE(map_.empty());
115 EXPECT_EQ(map.size(), map_.size());
116 for (std::map<int32, int32>::const_iterator it = map.begin();
117 it != map.end(); ++it) {
118 ExpectElement(it->first, it->second);
119 }
120 }
121
ExpectElement(int32 key,int32 value)122 void ExpectElement(int32 key, int32 value) {
123 // Test map size is correct.
124 EXPECT_EQ(value, map_[key]);
125 EXPECT_EQ(1, map_.count(key));
126
127 // Check mutable at and find work correctly.
128 EXPECT_EQ(value, map_.at(key));
129 Map<int32, int32>::iterator it = map_.find(key);
130
131 // interator dereferenceable
132 EXPECT_EQ(key, (*it).first);
133 EXPECT_EQ(value, (*it).second);
134 EXPECT_EQ(key, it->first);
135 EXPECT_EQ(value, it->second);
136
137 // iterator mutable
138 ((*it).second) = value + 1;
139 EXPECT_EQ(value + 1, map_[key]);
140 ((*it).second) = value;
141 EXPECT_EQ(value, map_[key]);
142
143 it->second = value + 1;
144 EXPECT_EQ(value + 1, map_[key]);
145 it->second = value;
146 EXPECT_EQ(value, map_[key]);
147
148 // copy constructor
149 Map<int32, int32>::iterator it_copy = it;
150 EXPECT_EQ(key, it_copy->first);
151 EXPECT_EQ(value, it_copy->second);
152
153 // Immutable API ================================================
154
155 // Check immutable at and find work correctly.
156 EXPECT_EQ(value, const_map_.at(key));
157 Map<int32, int32>::const_iterator const_it = const_map_.find(key);
158
159 // interator dereferenceable
160 EXPECT_EQ(key, (*const_it).first);
161 EXPECT_EQ(value, (*const_it).second);
162 EXPECT_EQ(key, const_it->first);
163 EXPECT_EQ(value, const_it->second);
164
165 // copy constructor
166 Map<int32, int32>::const_iterator const_it_copy = const_it;
167 EXPECT_EQ(key, const_it_copy->first);
168 EXPECT_EQ(value, const_it_copy->second);
169 }
170
171 google::protobuf::scoped_ptr<Map<int32, int32> > map_ptr_;
172 Map<int32, int32>& map_;
173 const Map<int32, int32>& const_map_;
174 };
175
TEST_P(MapImplTest,OperatorBracket)176 TEST_P(MapImplTest, OperatorBracket) {
177 int32 key = 0;
178 int32 value1 = 100;
179 int32 value2 = 101;
180
181 EXPECT_EQ(0, map_[key]);
182
183 map_[key] = value1;
184 ExpectSingleElement(key, value1);
185
186 map_[key] = value2;
187 ExpectSingleElement(key, value2);
188 }
189
TEST_P(MapImplTest,OperatorBracketNonExist)190 TEST_P(MapImplTest, OperatorBracketNonExist) {
191 int32 key = 0;
192 int32 default_value = 0;
193
194 EXPECT_EQ(default_value, map_[key]);
195 ExpectSingleElement(key, default_value);
196 }
197
TEST_P(MapImplTest,MutableAt)198 TEST_P(MapImplTest, MutableAt) {
199 int32 key = 0;
200 int32 value1 = 100;
201 int32 value2 = 101;
202
203 map_[key] = value1;
204 ExpectSingleElement(key, value1);
205
206 map_.at(key) = value2;
207 ExpectSingleElement(key, value2);
208 }
209
210 #ifdef PROTOBUF_HAS_DEATH_TEST
211
TEST_P(MapImplTest,MutableAtNonExistDeathTest)212 TEST_P(MapImplTest, MutableAtNonExistDeathTest) {
213 EXPECT_DEATH(map_.at(0), "");
214 }
215
TEST_P(MapImplTest,ImmutableAtNonExistDeathTest)216 TEST_P(MapImplTest, ImmutableAtNonExistDeathTest) {
217 EXPECT_DEATH(const_map_.at(0), "");
218 }
219
TEST_P(MapImplTest,UsageErrors)220 TEST_P(MapImplTest, UsageErrors) {
221 MapKey key;
222 key.SetInt64Value(1);
223 EXPECT_DEATH(key.GetUInt64Value(),
224 "Protocol Buffer map usage error:\n"
225 "MapKey::GetUInt64Value type does not match\n"
226 " Expected : uint64\n"
227 " Actual : int64");
228
229 MapValueRef value;
230 EXPECT_DEATH(value.SetFloatValue(0.1),
231 "Protocol Buffer map usage error:\n"
232 "MapValueRef::type MapValueRef is not initialized.");
233 }
234
235 #endif // PROTOBUF_HAS_DEATH_TEST
236
TEST_P(MapImplTest,CountNonExist)237 TEST_P(MapImplTest, CountNonExist) {
238 EXPECT_EQ(0, map_.count(0));
239 }
240
TEST_P(MapImplTest,MutableFindNonExist)241 TEST_P(MapImplTest, MutableFindNonExist) {
242 EXPECT_TRUE(map_.end() == map_.find(0));
243 }
244
TEST_P(MapImplTest,ImmutableFindNonExist)245 TEST_P(MapImplTest, ImmutableFindNonExist) {
246 EXPECT_TRUE(const_map_.end() == const_map_.find(0));
247 }
248
TEST_P(MapImplTest,ConstEnd)249 TEST_P(MapImplTest, ConstEnd) {
250 EXPECT_TRUE(const_map_.end() == const_map_.cend());
251 }
252
TEST_P(MapImplTest,GetReferenceFromIterator)253 TEST_P(MapImplTest, GetReferenceFromIterator) {
254 for (int i = 0; i < 10; i++) {
255 map_[i] = i;
256 }
257
258 for (Map<int32, int32>::const_iterator it = map_.cbegin();
259 it != map_.cend();) {
260 Map<int32, int32>::const_reference entry = *it++;
261 EXPECT_EQ(entry.first, entry.second);
262 }
263
264 for (Map<int32, int32>::const_iterator it = const_map_.begin();
265 it != const_map_.end();) {
266 Map<int32, int32>::const_reference entry = *it++;
267 EXPECT_EQ(entry.first, entry.second);
268 }
269
270 for (Map<int32, int32>::iterator it = map_.begin(); it != map_.end();) {
271 Map<int32, int32>::reference entry = *it++;
272 EXPECT_EQ(entry.first + 1, ++entry.second);
273 }
274 }
275
TEST_P(MapImplTest,IteratorBasic)276 TEST_P(MapImplTest, IteratorBasic) {
277 map_[0] = 0;
278
279 // Default constructible (per forward iterator requirements).
280 Map<int, int>::const_iterator cit;
281 Map<int, int>::iterator it;
282
283 it = map_.begin();
284 cit = it; // Converts to const_iterator
285
286 // Can compare between them.
287 EXPECT_TRUE(it == cit);
288 EXPECT_FALSE(cit != it);
289
290 // Pre increment.
291 EXPECT_FALSE(it == ++cit);
292
293 // Post increment.
294 EXPECT_FALSE(it++ == cit);
295 EXPECT_TRUE(it == cit);
296 }
297
298 template <typename Iterator>
median(Iterator i0,Iterator i1)299 static int64 median(Iterator i0, Iterator i1) {
300 vector<int64> v(i0, i1);
301 std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end());
302 return v[v.size() / 2];
303 }
304
Now()305 static int64 Now() {
306 return google::protobuf::util::TimeUtil::TimestampToNanoseconds(
307 google::protobuf::util::TimeUtil::GetCurrentTime());
308 }
309
310 // Arbitrary odd integers for creating test data.
311 static int k0 = 812398771;
312 static int k1 = 1312938717;
313 static int k2 = 1321555333;
314
315 // A naive begin() implementation will cause begin() to get slower and slower
316 // if one erases elements at the "front" of the hash map, and we'd like to
317 // avoid that, as std::unordered_map does.
TEST_P(MapImplTest,BeginIsFast)318 TEST_P(MapImplTest, BeginIsFast) {
319 // Disable this test for both new and old implementations.
320 if (/*GetParam()*/true) return;
321 Map<int32, int32> map(false); // This test uses new-style maps only.
322 const int kTestSize = 250000;
323 // Create a random-looking map of size n. Use non-negative integer keys.
324 uint32 frog = 123983;
325 int last_key = 0;
326 int counter = 0;
327 while (map.size() < kTestSize) {
328 frog *= static_cast<uint32>(k0);
329 frog ^= frog >> 17;
330 frog += counter++;
331 last_key =
332 static_cast<int>(frog) >= 0 ? static_cast<int>(frog) : last_key ^ 1;
333 GOOGLE_DCHECK_GE(last_key, 0);
334 map[last_key] = last_key ^ 1;
335 }
336 vector<int64> times;
337 // We're going to do map.erase(map.begin()) over and over again. But,
338 // just in case one iteration is fast compared to the granularity of
339 // our time keeping, we measure kChunkSize iterations per outer-loop iter.
340 const int kChunkSize = 1000;
341 GOOGLE_CHECK_EQ(kTestSize % kChunkSize, 0);
342 do {
343 const int64 start = Now();
344 for (int i = 0; i < kChunkSize; i++) {
345 map.erase(map.begin());
346 }
347 const int64 end = Now();
348 if (end > start) {
349 times.push_back(end - start);
350 }
351 } while (!map.empty());
352 if (times.size() < .99 * kTestSize / kChunkSize) {
353 GOOGLE_LOG(WARNING) << "Now() isn't helping us measure time";
354 return;
355 }
356 int64 x0 = median(times.begin(), times.begin() + 9);
357 int64 x1 = median(times.begin() + times.size() - 9, times.end());
358 GOOGLE_LOG(INFO) << "x0=" << x0 << ", x1=" << x1;
359 // x1 will greatly exceed x0 if the code we just executed took O(n^2) time.
360 // And we'll probably time out and never get here. So, this test is
361 // intentionally loose: we check that x0 and x1 are within a factor of 8.
362 EXPECT_GE(x1, x0 / 8);
363 EXPECT_GE(x0, x1 / 8);
364 }
365
366 // Try to create kTestSize keys that will land in just a few buckets, and
367 // time the insertions, to get a rough estimate of whether an O(n^2) worst case
368 // was triggered. This test is a hacky, but probably better than nothing.
TEST_P(MapImplTest,HashFlood)369 TEST_P(MapImplTest, HashFlood) {
370 const int kTestSize = 1024; // must be a power of 2
371 std::set<int> s;
372 for (int i = 0; s.size() < kTestSize; i++) {
373 if ((map_.hash_function()(i) & (kTestSize - 1)) < 3) {
374 s.insert(i);
375 }
376 }
377 // Create hash table with kTestSize entries that hash flood a table with
378 // 1024 (or 512 or 2048 or ...) entries. This assumes that map_ uses powers
379 // of 2 for table sizes, and that it's sufficient to "flood" with respect to
380 // the low bits of the output of map_.hash_function().
381 vector<int64> times;
382 std::set<int>::iterator it = s.begin();
383 int count = 0;
384 do {
385 const int64 start = Now();
386 map_[*it] = 0;
387 const int64 end = Now();
388 if (end > start) {
389 times.push_back(end - start);
390 }
391 ++count;
392 ++it;
393 } while (it != s.end());
394 if (times.size() < .99 * count) return;
395 int64 x0 = median(times.begin(), times.begin() + 9);
396 int64 x1 = median(times.begin() + times.size() - 9, times.end());
397 // x1 will greatly exceed x0 if the code we just executed took O(n^2) time.
398 // But we want to allow O(n log n). A factor of 20 should be generous enough.
399 EXPECT_LE(x1, x0 * 20);
400 }
401
402 template <typename T, typename U>
TestValidityForAllKeysExcept(int key_to_avoid,const T & check_map,const U & map)403 static void TestValidityForAllKeysExcept(int key_to_avoid,
404 const T& check_map,
405 const U& map) {
406 typedef typename U::value_type value_type; // a key-value pair
407 for (typename U::const_iterator it = map.begin(); it != map.end(); ++it) {
408 const int key = it->first;
409 if (key == key_to_avoid) continue;
410 // All iterators relevant to this key, whether old (from check_map) or new,
411 // must point to the same memory. So, test pointer equality here.
412 const value_type* check_val = &*check_map.find(key)->second;
413 EXPECT_EQ(check_val, &*it);
414 EXPECT_EQ(check_val, &*map.find(key));
415 }
416 }
417
418 // EXPECT i0 and i1 to be the same. Advancing them should have the same effect,
419 // too.
420 template <typename Iter>
TestEqualIterators(Iter i0,Iter i1,Iter end)421 static void TestEqualIterators(Iter i0, Iter i1, Iter end) {
422 const int kMaxAdvance = 10;
423 for (int i = 0; i < kMaxAdvance; i++) {
424 EXPECT_EQ(i0 == end, i1 == end);
425 if (i0 == end) return;
426 EXPECT_EQ(&*i0, &*i1) << "iter " << i;
427 ++i0;
428 ++i1;
429 }
430 }
431
432 template <typename IteratorType>
TestOldVersusNewIterator(int skip,Map<int,int> * m)433 static void TestOldVersusNewIterator(int skip, Map<int, int>* m) {
434 const int initial_size = m->size();
435 IteratorType it = m->begin();
436 for (int i = 0; i < skip && it != m->end(); it++, i++) {}
437 if (it == m->end()) return;
438 const IteratorType old = it;
439 GOOGLE_LOG(INFO) << "skip=" << skip << ", old->first=" << old->first;
440 const int target_size =
441 initial_size < 100 ? initial_size * 5 : initial_size * 5 / 4;
442 for (int i = 0; m->size() <= target_size; i++) {
443 (*m)[i] = 0;
444 }
445 // Iterator 'old' should still work just fine despite the growth of *m.
446 const IteratorType after_growth = m->find(old->first);
447 TestEqualIterators<IteratorType>(old, after_growth, m->end());
448
449 // Now shrink the number of elements. Do this with a mix of erases and
450 // inserts to increase the chance that the hashtable will resize to a lower
451 // number of buckets. (But, in any case, the test is still useful.)
452 for (int i = 0; i < 2 * (target_size - initial_size); i++) {
453 if (i != old->first) {
454 m->erase(i);
455 }
456 if (((i ^ m->begin()->first) & 15) == 0) {
457 (*m)[i * 342] = i;
458 }
459 }
460 // Now, the table has grown and shrunk; test again.
461 TestEqualIterators<IteratorType>(old, m->find(old->first), m->end());
462 TestEqualIterators<IteratorType>(old, after_growth, m->end());
463 }
464
465 // Create and test an n-element Map, with emphasis on iterator correctness.
StressTestIterators(int n,bool test_old_style_proto2_maps)466 static void StressTestIterators(int n, bool test_old_style_proto2_maps) {
467 GOOGLE_LOG(INFO) << "StressTestIterators " << n;
468 GOOGLE_CHECK_GT(n, 0);
469 // Create a random-looking map of size n. Use non-negative integer keys.
470 Map<int, int> m(test_old_style_proto2_maps);
471 uint32 frog = 123987 + n;
472 int last_key = 0;
473 int counter = 0;
474 while (m.size() < n) {
475 frog *= static_cast<uint32>(k0);
476 frog ^= frog >> 17;
477 frog += counter++;
478 last_key =
479 static_cast<int>(frog) >= 0 ? static_cast<int>(frog) : last_key ^ 1;
480 GOOGLE_DCHECK_GE(last_key, 0);
481 m[last_key] = last_key ^ 1;
482 }
483 // Test it.
484 ASSERT_EQ(n, m.size());
485 // Create maps of pointers and iterators.
486 // These should remain valid even if we modify m.
487 hash_map<int, Map<int, int>::value_type*> mp(n);
488 hash_map<int, Map<int, int>::iterator> mi(n);
489 for (Map<int, int>::iterator it = m.begin(); it != m.end(); ++it) {
490 mp[it->first] = &*it;
491 mi[it->first] = it;
492 }
493 ASSERT_EQ(m.size(), mi.size());
494 ASSERT_EQ(m.size(), mp.size());
495 m.erase(last_key);
496 ASSERT_EQ(n - 1, m.size());
497 TestValidityForAllKeysExcept(last_key, mp, m);
498 TestValidityForAllKeysExcept(last_key, mi, m);
499
500 m[last_key] = 0;
501 ASSERT_EQ(n, m.size());
502 // Test old iterator vs new iterator, with table modification in between.
503 TestOldVersusNewIterator<Map<int, int>::const_iterator>(n % 3, &m);
504 TestOldVersusNewIterator<Map<int, int>::iterator>(n % (1 + (n / 40)), &m);
505 // Finally, ensure erase(iterator) doesn't reorder anything, becuase that is
506 // what its documentation says.
507 m[last_key] = m[last_key ^ 999] = 0;
508 vector<Map<int, int>::iterator> v;
509 v.reserve(m.size());
510 int position_of_last_key = 0;
511 for (Map<int, int>::iterator it = m.begin(); it != m.end(); ++it) {
512 if (it->first == last_key) {
513 position_of_last_key = v.size();
514 }
515 v.push_back(it);
516 }
517 ASSERT_EQ(m.size(), v.size());
518 const Map<int, int>::iterator erase_result = m.erase(m.find(last_key));
519 int index = 0;
520 for (Map<int, int>::iterator it = m.begin(); it != m.end(); ++it, ++index) {
521 if (index == position_of_last_key) {
522 EXPECT_EQ(&*erase_result, &*v[++index]);
523 }
524 ASSERT_EQ(&*it, &*v[index]);
525 }
526 }
527
TEST_P(MapImplTest,IteratorInvalidation)528 TEST_P(MapImplTest, IteratorInvalidation) {
529 // As multiple underlying hash_map implementations do not follow the
530 // validation requirement, the test is disabled for old-style maps.
531 if (GetParam()) return;
532 // Create a set of pseudo-random sizes to test.
533 #ifndef NDEBUG
534 const int kMaxSizeToTest = 100 * 1000;
535 #else
536 const int kMaxSizeToTest = 1000 * 1000;
537 #endif
538 std::set<int> s;
539 int n = kMaxSizeToTest;
540 int frog = k1 + n;
541 while (n > 1 && s.size() < 25) {
542 s.insert(n);
543 n = static_cast<int>(n * 100 / (101.0 + (frog & 63)));
544 frog *= k2;
545 frog ^= frog >> 17;
546 }
547 // Ensure we test a few small sizes.
548 s.insert(1);
549 s.insert(2);
550 s.insert(3);
551 // Now, the real work.
552 for (std::set<int>::iterator i = s.begin(); i != s.end(); ++i) {
553 StressTestIterators(*i, GetParam());
554 }
555 }
556
557 // Test that erase() revalidates iterators.
TEST_P(MapImplTest,EraseRevalidates)558 TEST_P(MapImplTest, EraseRevalidates) {
559 // As multiple underlying hash_map implementations do not follow the
560 // validation requirement, the test is disabled for old-style maps.
561 if (GetParam()) return;
562 map_[3] = map_[13] = map_[20] = 0;
563 const int initial_size = map_.size();
564 EXPECT_EQ(3, initial_size);
565 vector<Map<int, int>::iterator> v;
566 for (Map<int, int>::iterator it = map_.begin(); it != map_.end(); ++it) {
567 v.push_back(it);
568 }
569 EXPECT_EQ(initial_size, v.size());
570 for (int i = 0; map_.size() <= initial_size * 20; i++) {
571 map_[i] = 0;
572 }
573 const int larger_size = map_.size();
574 // We've greatly increased the size of the map, so it is highly likely that
575 // the following will corrupt m if erase() doesn't properly revalidate
576 // iterators passed to it. Finishing this routine without crashing indicates
577 // success.
578 for (int i = 0; i < v.size(); i++) {
579 map_.erase(v[i]);
580 }
581 EXPECT_EQ(larger_size - v.size(), map_.size());
582 }
583
584 template <typename T>
IsConstHelper(T &)585 bool IsConstHelper(T& /*t*/) { // NOLINT. We want to catch non-const refs here.
586 return false;
587 }
588 template <typename T>
IsConstHelper(const T &)589 bool IsConstHelper(const T& /*t*/) {
590 return true;
591 }
592
TEST_P(MapImplTest,IteratorConstness)593 TEST_P(MapImplTest, IteratorConstness) {
594 map_[0] = 0;
595 EXPECT_TRUE(IsConstHelper(*map_.cbegin()));
596 EXPECT_TRUE(IsConstHelper(*const_map_.begin()));
597 EXPECT_FALSE(IsConstHelper(*map_.begin()));
598 }
599
IsForwardIteratorHelper(std::forward_iterator_tag)600 bool IsForwardIteratorHelper(std::forward_iterator_tag /*tag*/) { return true; }
601 template <typename T>
IsForwardIteratorHelper(T)602 bool IsForwardIteratorHelper(T /*t*/) {
603 return false;
604 }
605
TEST_P(MapImplTest,IteratorCategory)606 TEST_P(MapImplTest, IteratorCategory) {
607 EXPECT_TRUE(IsForwardIteratorHelper(
608 std::iterator_traits<Map<int, int>::iterator>::iterator_category()));
609 EXPECT_TRUE(IsForwardIteratorHelper(std::iterator_traits<
610 Map<int, int>::const_iterator>::iterator_category()));
611 }
612
TEST_P(MapImplTest,InsertSingle)613 TEST_P(MapImplTest, InsertSingle) {
614 int32 key = 0;
615 int32 value1 = 100;
616 int32 value2 = 101;
617
618 // Insert a non-existed key.
619 std::pair<Map<int32, int32>::iterator, bool> result1 =
620 map_.insert(Map<int32, int32>::value_type(key, value1));
621 ExpectSingleElement(key, value1);
622
623 Map<int32, int32>::iterator it1 = result1.first;
624 EXPECT_EQ(key, it1->first);
625 EXPECT_EQ(value1, it1->second);
626 EXPECT_TRUE(result1.second);
627
628 // Insert an existed key.
629 std::pair<Map<int32, int32>::iterator, bool> result2 =
630 map_.insert(Map<int32, int32>::value_type(key, value2));
631 ExpectSingleElement(key, value1);
632
633 Map<int32, int32>::iterator it2 = result2.first;
634 EXPECT_TRUE(it1 == it2);
635 EXPECT_FALSE(result2.second);
636 }
637
TEST_P(MapImplTest,InsertByIterator)638 TEST_P(MapImplTest, InsertByIterator) {
639 int32 key1 = 0;
640 int32 key2 = 1;
641 int32 value1a = 100;
642 int32 value1b = 101;
643 int32 value2a = 200;
644 int32 value2b = 201;
645
646 std::map<int32, int32> map1;
647 map1[key1] = value1a;
648 map1[key2] = value2a;
649
650 map_.insert(map1.begin(), map1.end());
651 ExpectElements(map1);
652
653 std::map<int32, int32> map2;
654 map2[key1] = value1b;
655 map2[key2] = value2b;
656
657 map_.insert(map2.begin(), map2.end());
658 ExpectElements(map1);
659 }
660
TEST_P(MapImplTest,EraseSingleByKey)661 TEST_P(MapImplTest, EraseSingleByKey) {
662 int32 key = 0;
663 int32 value = 100;
664
665 map_[key] = value;
666 ExpectSingleElement(key, value);
667
668 // Erase an existing key.
669 EXPECT_EQ(1, map_.erase(key));
670 EXPECT_TRUE(map_.empty());
671 EXPECT_EQ(0, map_.size());
672 EXPECT_TRUE(map_.end() == map_.find(key));
673 EXPECT_TRUE(map_.begin() == map_.end());
674
675 // Erase a non-existing key.
676 EXPECT_EQ(0, map_.erase(key));
677 }
678
TEST_P(MapImplTest,EraseMutipleByKey)679 TEST_P(MapImplTest, EraseMutipleByKey) {
680 // erase in one specific order to trigger corner cases
681 for (int i = 0; i < 5; i++) {
682 map_[i] = i;
683 }
684
685 map_.erase(0);
686 EXPECT_EQ(4, map_.size());
687 EXPECT_TRUE(map_.end() == map_.find(0));
688
689 map_.erase(1);
690 EXPECT_EQ(3, map_.size());
691 EXPECT_TRUE(map_.end() == map_.find(1));
692
693 map_.erase(3);
694 EXPECT_EQ(2, map_.size());
695 EXPECT_TRUE(map_.end() == map_.find(3));
696
697 map_.erase(4);
698 EXPECT_EQ(1, map_.size());
699 EXPECT_TRUE(map_.end() == map_.find(4));
700
701 map_.erase(2);
702 EXPECT_EQ(0, map_.size());
703 EXPECT_TRUE(map_.end() == map_.find(2));
704 }
705
TEST_P(MapImplTest,EraseSingleByIterator)706 TEST_P(MapImplTest, EraseSingleByIterator) {
707 int32 key = 0;
708 int32 value = 100;
709
710 map_[key] = value;
711 ExpectSingleElement(key, value);
712
713 Map<int32, int32>::iterator it = map_.find(key);
714 map_.erase(it);
715 EXPECT_TRUE(map_.empty());
716 EXPECT_EQ(0, map_.size());
717 EXPECT_TRUE(map_.end() == map_.find(key));
718 EXPECT_TRUE(map_.begin() == map_.end());
719 }
720
TEST_P(MapImplTest,ValidIteratorAfterErase)721 TEST_P(MapImplTest, ValidIteratorAfterErase) {
722 for (int i = 0; i < 10; i++) {
723 map_[i] = i;
724 }
725
726 int count = 0;
727
728 for (Map<int32, int32>::iterator it = map_.begin(); it != map_.end();) {
729 count++;
730 if (it->first % 2 == 1) {
731 map_.erase(it++);
732 } else {
733 ++it;
734 }
735 }
736
737 EXPECT_EQ(10, count);
738 EXPECT_EQ(5, map_.size());
739 }
740
TEST_P(MapImplTest,EraseByIterator)741 TEST_P(MapImplTest, EraseByIterator) {
742 int32 key1 = 0;
743 int32 key2 = 1;
744 int32 value1 = 100;
745 int32 value2 = 101;
746
747 std::map<int32, int32> map;
748 map[key1] = value1;
749 map[key2] = value2;
750
751 map_.insert(map.begin(), map.end());
752 ExpectElements(map);
753
754 map_.erase(map_.begin(), map_.end());
755 EXPECT_TRUE(map_.empty());
756 EXPECT_EQ(0, map_.size());
757 EXPECT_TRUE(map_.end() == map_.find(key1));
758 EXPECT_TRUE(map_.end() == map_.find(key2));
759 EXPECT_TRUE(map_.begin() == map_.end());
760 }
761
TEST_P(MapImplTest,Clear)762 TEST_P(MapImplTest, Clear) {
763 int32 key = 0;
764 int32 value = 100;
765
766 map_[key] = value;
767 ExpectSingleElement(key, value);
768
769 map_.clear();
770
771 EXPECT_TRUE(map_.empty());
772 EXPECT_EQ(0, map_.size());
773 EXPECT_TRUE(map_.end() == map_.find(key));
774 EXPECT_TRUE(map_.begin() == map_.end());
775 }
776
CopyConstructorHelper(Arena * arena,Map<int32,int32> * m)777 static void CopyConstructorHelper(Arena* arena, Map<int32, int32>* m) {
778 int32 key1 = 0;
779 int32 key2 = 1;
780 int32 value1 = 100;
781 int32 value2 = 101;
782
783 std::map<int32, int32> map;
784 map[key1] = value1;
785 map[key2] = value2;
786
787 m->insert(map.begin(), map.end());
788
789 Map<int32, int32> other(*m);
790
791 EXPECT_EQ(2, other.size());
792 EXPECT_EQ(value1, other.at(key1));
793 EXPECT_EQ(value2, other.at(key2));
794 }
795
TEST_P(MapImplTest,CopyConstructorWithArena)796 TEST_P(MapImplTest, CopyConstructorWithArena) {
797 Arena a;
798 CopyConstructorHelper(&a, &map_);
799 }
800
TEST_P(MapImplTest,CopyConstructorWithoutArena)801 TEST_P(MapImplTest, CopyConstructorWithoutArena) {
802 CopyConstructorHelper(NULL, &map_);
803 }
804
TEST_P(MapImplTest,IterConstructor)805 TEST_P(MapImplTest, IterConstructor) {
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 Map<int32, int32> new_map(map.begin(), map.end(),
816 GetParam());
817
818 EXPECT_EQ(2, new_map.size());
819 EXPECT_EQ(value1, new_map.at(key1));
820 EXPECT_EQ(value2, new_map.at(key2));
821 }
822
TEST_P(MapImplTest,Assigner)823 TEST_P(MapImplTest, Assigner) {
824 int32 key1 = 0;
825 int32 key2 = 1;
826 int32 value1 = 100;
827 int32 value2 = 101;
828
829 std::map<int32, int32> map;
830 map[key1] = value1;
831 map[key2] = value2;
832
833 map_.insert(map.begin(), map.end());
834
835 Map<int32, int32> other(GetParam());
836 int32 key_other = 123;
837 int32 value_other = 321;
838 other[key_other] = value_other;
839 EXPECT_EQ(1, other.size());
840
841 other = map_;
842
843 EXPECT_EQ(2, other.size());
844 EXPECT_EQ(value1, other.at(key1));
845 EXPECT_EQ(value2, other.at(key2));
846 EXPECT_TRUE(other.find(key_other) == other.end());
847
848 // Self assign
849 other = other;
850 EXPECT_EQ(2, other.size());
851 EXPECT_EQ(value1, other.at(key1));
852 EXPECT_EQ(value2, other.at(key2));
853
854 // Try assignment to a map with a different choice of "style."
855 Map<int32, int32> m(!GetParam());
856 m = other;
857 EXPECT_EQ(2, m.size());
858 EXPECT_EQ(value1, m.at(key1));
859 EXPECT_EQ(value2, m.at(key2));
860 }
861
TEST_P(MapImplTest,Rehash)862 TEST_P(MapImplTest, Rehash) {
863 const int test_size = 50;
864 std::map<int32, int32> reference_map;
865 for (int i = 0; i < test_size; i++) {
866 reference_map[i] = i;
867 }
868 for (int i = 0; i < test_size; i++) {
869 map_[i] = reference_map[i];
870 EXPECT_EQ(reference_map[i], map_[i]);
871 }
872 for (int i = 0; i < test_size; i++) {
873 map_.erase(i);
874 EXPECT_TRUE(map_.end() == map_.find(i));
875 }
876 EXPECT_TRUE(map_.empty());
877 }
878
TEST_P(MapImplTest,EqualRange)879 TEST_P(MapImplTest, EqualRange) {
880 int key = 100, key_missing = 101;
881 map_[key] = 100;
882
883 std::pair<google::protobuf::Map<int32, int32>::iterator,
884 google::protobuf::Map<int32, int32>::iterator> range = map_.equal_range(key);
885 EXPECT_TRUE(map_.find(key) == range.first);
886 EXPECT_TRUE(++map_.find(key) == range.second);
887
888 range = map_.equal_range(key_missing);
889 EXPECT_TRUE(map_.end() == range.first);
890 EXPECT_TRUE(map_.end() == range.second);
891
892 std::pair<google::protobuf::Map<int32, int32>::const_iterator,
893 google::protobuf::Map<int32, int32>::const_iterator> const_range =
894 const_map_.equal_range(key);
895 EXPECT_TRUE(const_map_.find(key) == const_range.first);
896 EXPECT_TRUE(++const_map_.find(key) == const_range.second);
897
898 const_range = const_map_.equal_range(key_missing);
899 EXPECT_TRUE(const_map_.end() == const_range.first);
900 EXPECT_TRUE(const_map_.end() == const_range.second);
901 }
902
TEST_P(MapImplTest,ConvertToStdMap)903 TEST_P(MapImplTest, ConvertToStdMap) {
904 map_[100] = 101;
905 std::map<int32, int32> std_map(map_.begin(), map_.end());
906 EXPECT_EQ(1, std_map.size());
907 EXPECT_EQ(101, std_map[100]);
908 }
909
TEST_P(MapImplTest,ConvertToStdVectorOfPairs)910 TEST_P(MapImplTest, ConvertToStdVectorOfPairs) {
911 map_[100] = 101;
912 std::vector<std::pair<int32, int32> > std_vec(map_.begin(), map_.end());
913 EXPECT_EQ(1, std_vec.size());
914 EXPECT_EQ(100, std_vec[0].first);
915 EXPECT_EQ(101, std_vec[0].second);
916 }
917
918 INSTANTIATE_TEST_CASE_P(BoolSequence, MapImplTest, testing::Bool());
919
920 // Map Field Reflection Test ========================================
921
Func(int i,int j)922 static int Func(int i, int j) {
923 return i * j;
924 }
925
StrFunc(int i,int j)926 static string StrFunc(int i, int j) {
927 string str;
928 SStringPrintf(&str, "%d", Func(i, j));
929 return str;
930 }
931
Int(const string & value)932 static int Int(const string& value) {
933 int result = 0;
934 std::istringstream(value) >> result;
935 return result;
936 }
937
938 class MapFieldReflectionTest : public testing::Test {
939 protected:
940 typedef FieldDescriptor FD;
941 };
942
TEST_F(MapFieldReflectionTest,RegularFields)943 TEST_F(MapFieldReflectionTest, RegularFields) {
944 TestMap message;
945 const Reflection* refl = message.GetReflection();
946 const Descriptor* desc = message.GetDescriptor();
947
948 Map<int32, int32>* map_int32_int32 = message.mutable_map_int32_int32();
949 Map<int32, double>* map_int32_double = message.mutable_map_int32_double();
950 Map<string, string>* map_string_string = message.mutable_map_string_string();
951 Map<int32, ForeignMessage>* map_int32_foreign_message =
952 message.mutable_map_int32_foreign_message();
953
954 for (int i = 0; i < 10; ++i) {
955 (*map_int32_int32)[i] = Func(i, 1);
956 (*map_int32_double)[i] = Func(i, 2);
957 (*map_string_string)[StrFunc(i, 1)] = StrFunc(i, 5);
958 (*map_int32_foreign_message)[i].set_c(Func(i, 6));
959 }
960
961 // Get FieldDescriptors for all the fields of interest.
962 const FieldDescriptor* fd_map_int32_int32 =
963 desc->FindFieldByName("map_int32_int32");
964 const FieldDescriptor* fd_map_int32_double =
965 desc->FindFieldByName("map_int32_double");
966 const FieldDescriptor* fd_map_string_string =
967 desc->FindFieldByName("map_string_string");
968 const FieldDescriptor* fd_map_int32_foreign_message =
969 desc->FindFieldByName("map_int32_foreign_message");
970
971 const FieldDescriptor* fd_map_int32_in32_key =
972 fd_map_int32_int32->message_type()->FindFieldByName("key");
973 const FieldDescriptor* fd_map_int32_in32_value =
974 fd_map_int32_int32->message_type()->FindFieldByName("value");
975 const FieldDescriptor* fd_map_int32_double_key =
976 fd_map_int32_double->message_type()->FindFieldByName("key");
977 const FieldDescriptor* fd_map_int32_double_value =
978 fd_map_int32_double->message_type()->FindFieldByName("value");
979 const FieldDescriptor* fd_map_string_string_key =
980 fd_map_string_string->message_type()->FindFieldByName("key");
981 const FieldDescriptor* fd_map_string_string_value =
982 fd_map_string_string->message_type()->FindFieldByName("value");
983 const FieldDescriptor* fd_map_int32_foreign_message_key =
984 fd_map_int32_foreign_message->message_type()->FindFieldByName("key");
985 const FieldDescriptor* fd_map_int32_foreign_message_value =
986 fd_map_int32_foreign_message->message_type()->FindFieldByName("value");
987
988 // Get RepeatedPtrField objects for all fields of interest.
989 const RepeatedPtrField<Message>& mf_int32_int32 =
990 refl->GetRepeatedPtrField<Message>(message, fd_map_int32_int32);
991 const RepeatedPtrField<Message>& mf_int32_double =
992 refl->GetRepeatedPtrField<Message>(message, fd_map_int32_double);
993 const RepeatedPtrField<Message>& mf_string_string =
994 refl->GetRepeatedPtrField<Message>(message, fd_map_string_string);
995 const RepeatedPtrField<Message>&
996 mf_int32_foreign_message =
997 refl->GetRepeatedPtrField<Message>(
998 message, fd_map_int32_foreign_message);
999
1000 // Get mutable RepeatedPtrField objects for all fields of interest.
1001 RepeatedPtrField<Message>* mmf_int32_int32 =
1002 refl->MutableRepeatedPtrField<Message>(&message, fd_map_int32_int32);
1003 RepeatedPtrField<Message>* mmf_int32_double =
1004 refl->MutableRepeatedPtrField<Message>(&message, fd_map_int32_double);
1005 RepeatedPtrField<Message>* mmf_string_string =
1006 refl->MutableRepeatedPtrField<Message>(&message, fd_map_string_string);
1007 RepeatedPtrField<Message>* mmf_int32_foreign_message =
1008 refl->MutableRepeatedPtrField<Message>(
1009 &message, fd_map_int32_foreign_message);
1010
1011 // Make sure we can do gets through the RepeatedPtrField objects.
1012 for (int i = 0; i < 10; ++i) {
1013 {
1014 // Check gets through const objects.
1015 const Message& message_int32_int32 = mf_int32_int32.Get(i);
1016 int32 key_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1017 message_int32_int32, fd_map_int32_in32_key);
1018 int32 value_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1019 message_int32_int32, fd_map_int32_in32_value);
1020 EXPECT_EQ(value_int32_int32, Func(key_int32_int32, 1));
1021
1022 const Message& message_int32_double = mf_int32_double.Get(i);
1023 int32 key_int32_double = message_int32_double.GetReflection()->GetInt32(
1024 message_int32_double, fd_map_int32_double_key);
1025 double value_int32_double =
1026 message_int32_double.GetReflection()->GetDouble(
1027 message_int32_double, fd_map_int32_double_value);
1028 EXPECT_EQ(value_int32_double, Func(key_int32_double, 2));
1029
1030 const Message& message_string_string = mf_string_string.Get(i);
1031 string key_string_string =
1032 message_string_string.GetReflection()->GetString(
1033 message_string_string, fd_map_string_string_key);
1034 string value_string_string =
1035 message_string_string.GetReflection()->GetString(
1036 message_string_string, fd_map_string_string_value);
1037 EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5));
1038
1039 const Message& message_int32_message = mf_int32_foreign_message.Get(i);
1040 int32 key_int32_message = message_int32_message.GetReflection()->GetInt32(
1041 message_int32_message, fd_map_int32_foreign_message_key);
1042 const ForeignMessage& value_int32_message =
1043 down_cast<const ForeignMessage&>(
1044 message_int32_message.GetReflection()
1045 ->GetMessage(message_int32_message,
1046 fd_map_int32_foreign_message_value));
1047 EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6));
1048 }
1049
1050 {
1051 // Check gets through mutable objects.
1052 const Message& message_int32_int32 = mmf_int32_int32->Get(i);
1053 int32 key_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1054 message_int32_int32, fd_map_int32_in32_key);
1055 int32 value_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1056 message_int32_int32, fd_map_int32_in32_value);
1057 EXPECT_EQ(value_int32_int32, Func(key_int32_int32, 1));
1058
1059 const Message& message_int32_double = mmf_int32_double->Get(i);
1060 int32 key_int32_double = message_int32_double.GetReflection()->GetInt32(
1061 message_int32_double, fd_map_int32_double_key);
1062 double value_int32_double =
1063 message_int32_double.GetReflection()->GetDouble(
1064 message_int32_double, fd_map_int32_double_value);
1065 EXPECT_EQ(value_int32_double, Func(key_int32_double, 2));
1066
1067 const Message& message_string_string = mmf_string_string->Get(i);
1068 string key_string_string =
1069 message_string_string.GetReflection()->GetString(
1070 message_string_string, fd_map_string_string_key);
1071 string value_string_string =
1072 message_string_string.GetReflection()->GetString(
1073 message_string_string, fd_map_string_string_value);
1074 EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5));
1075
1076 const Message& message_int32_message = mmf_int32_foreign_message->Get(i);
1077 int32 key_int32_message = message_int32_message.GetReflection()->GetInt32(
1078 message_int32_message, fd_map_int32_foreign_message_key);
1079 const ForeignMessage& value_int32_message =
1080 down_cast<const ForeignMessage&>(
1081 message_int32_message.GetReflection()
1082 ->GetMessage(message_int32_message,
1083 fd_map_int32_foreign_message_value));
1084 EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6));
1085 }
1086 }
1087
1088 // Do sets through the RepeatedPtrField objects.
1089 for (int i = 0; i < 10; i++) {
1090 {
1091 Message* message_int32_int32 = mmf_int32_int32->Mutable(i);
1092 int32 key_int32_int32 = message_int32_int32->GetReflection()->GetInt32(
1093 *message_int32_int32, fd_map_int32_in32_key);
1094 message_int32_int32->GetReflection()->SetInt32(message_int32_int32,
1095 fd_map_int32_in32_value,
1096 Func(key_int32_int32, -1));
1097
1098 Message* message_int32_double = mmf_int32_double->Mutable(i);
1099 int32 key_int32_double = message_int32_double->GetReflection()->GetInt32(
1100 *message_int32_double, fd_map_int32_double_key);
1101 message_int32_double->GetReflection()->SetDouble(
1102 message_int32_double, fd_map_int32_double_value,
1103 Func(key_int32_double, -2));
1104
1105 Message* message_string_string = mmf_string_string->Mutable(i);
1106 string key_string_string =
1107 message_string_string->GetReflection()->GetString(
1108 *message_string_string, fd_map_string_string_key);
1109 message_string_string->GetReflection()->SetString(
1110 message_string_string, fd_map_string_string_value,
1111 StrFunc(Int(key_string_string), -5));
1112
1113 Message* message_int32_message = mmf_int32_foreign_message->Mutable(i);
1114 int32 key_int32_message =
1115 message_int32_message->GetReflection()->GetInt32(
1116 *message_int32_message, fd_map_int32_foreign_message_key);
1117 ForeignMessage* value_int32_message = down_cast<ForeignMessage*>(
1118 message_int32_message->GetReflection()
1119 ->MutableMessage(message_int32_message,
1120 fd_map_int32_foreign_message_value));
1121 value_int32_message->set_c(Func(key_int32_message, -6));
1122 }
1123 }
1124
1125 // Check gets through mutable objects.
1126 for (int i = 0; i < 10; i++) {
1127 EXPECT_EQ(Func(i, -1), message.map_int32_int32().at(i));
1128 EXPECT_EQ(Func(i, -2), message.map_int32_double().at(i));
1129 EXPECT_EQ(StrFunc(i, -5), message.map_string_string().at(StrFunc(i, 1)));
1130 EXPECT_EQ(Func(i, -6), message.map_int32_foreign_message().at(i).c());
1131 }
1132 }
1133
TEST_F(MapFieldReflectionTest,RepeatedFieldRefForRegularFields)1134 TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) {
1135 TestMap message;
1136 const Reflection* refl = message.GetReflection();
1137 const Descriptor* desc = message.GetDescriptor();
1138
1139 Map<int32, int32>* map_int32_int32 = message.mutable_map_int32_int32();
1140 Map<int32, double>* map_int32_double = message.mutable_map_int32_double();
1141 Map<string, string>* map_string_string = message.mutable_map_string_string();
1142 Map<int32, ForeignMessage>* map_int32_foreign_message =
1143 message.mutable_map_int32_foreign_message();
1144
1145 for (int i = 0; i < 10; ++i) {
1146 (*map_int32_int32)[i] = Func(i, 1);
1147 (*map_int32_double)[i] = Func(i, 2);
1148 (*map_string_string)[StrFunc(i, 1)] = StrFunc(i, 5);
1149 (*map_int32_foreign_message)[i].set_c(Func(i, 6));
1150 }
1151
1152 // Get FieldDescriptors for all the fields of interest.
1153 const FieldDescriptor* fd_map_int32_int32 =
1154 desc->FindFieldByName("map_int32_int32");
1155 const FieldDescriptor* fd_map_int32_double =
1156 desc->FindFieldByName("map_int32_double");
1157 const FieldDescriptor* fd_map_string_string =
1158 desc->FindFieldByName("map_string_string");
1159 const FieldDescriptor* fd_map_int32_foreign_message =
1160 desc->FindFieldByName("map_int32_foreign_message");
1161
1162 const FieldDescriptor* fd_map_int32_in32_key =
1163 fd_map_int32_int32->message_type()->FindFieldByName("key");
1164 const FieldDescriptor* fd_map_int32_in32_value =
1165 fd_map_int32_int32->message_type()->FindFieldByName("value");
1166 const FieldDescriptor* fd_map_int32_double_key =
1167 fd_map_int32_double->message_type()->FindFieldByName("key");
1168 const FieldDescriptor* fd_map_int32_double_value =
1169 fd_map_int32_double->message_type()->FindFieldByName("value");
1170 const FieldDescriptor* fd_map_string_string_key =
1171 fd_map_string_string->message_type()->FindFieldByName("key");
1172 const FieldDescriptor* fd_map_string_string_value =
1173 fd_map_string_string->message_type()->FindFieldByName("value");
1174 const FieldDescriptor* fd_map_int32_foreign_message_key =
1175 fd_map_int32_foreign_message->message_type()->FindFieldByName("key");
1176 const FieldDescriptor* fd_map_int32_foreign_message_value =
1177 fd_map_int32_foreign_message->message_type()->FindFieldByName("value");
1178
1179 // Get RepeatedFieldRef objects for all fields of interest.
1180 const RepeatedFieldRef<Message> mf_int32_int32 =
1181 refl->GetRepeatedFieldRef<Message>(message, fd_map_int32_int32);
1182 const RepeatedFieldRef<Message> mf_int32_double =
1183 refl->GetRepeatedFieldRef<Message>(message, fd_map_int32_double);
1184 const RepeatedFieldRef<Message> mf_string_string =
1185 refl->GetRepeatedFieldRef<Message>(message, fd_map_string_string);
1186 const RepeatedFieldRef<Message> mf_int32_foreign_message =
1187 refl->GetRepeatedFieldRef<Message>(message, fd_map_int32_foreign_message);
1188
1189 // Get mutable RepeatedFieldRef objects for all fields of interest.
1190 const MutableRepeatedFieldRef<Message> mmf_int32_int32 =
1191 refl->GetMutableRepeatedFieldRef<Message>(&message, fd_map_int32_int32);
1192 const MutableRepeatedFieldRef<Message> mmf_int32_double =
1193 refl->GetMutableRepeatedFieldRef<Message>(&message, fd_map_int32_double);
1194 const MutableRepeatedFieldRef<Message> mmf_string_string =
1195 refl->GetMutableRepeatedFieldRef<Message>(&message, fd_map_string_string);
1196 const MutableRepeatedFieldRef<Message>
1197 mmf_int32_foreign_message =
1198 refl->GetMutableRepeatedFieldRef<Message>(
1199 &message, fd_map_int32_foreign_message);
1200
1201 // Get entry default instances
1202 google::protobuf::scoped_ptr<Message> entry_int32_int32(
1203 MessageFactory::generated_factory()
1204 ->GetPrototype(fd_map_int32_int32->message_type())
1205 ->New());
1206 google::protobuf::scoped_ptr<Message> entry_int32_double(
1207 MessageFactory::generated_factory()
1208 ->GetPrototype(fd_map_int32_double->message_type())
1209 ->New());
1210 google::protobuf::scoped_ptr<Message> entry_string_string(
1211 MessageFactory::generated_factory()
1212 ->GetPrototype(fd_map_string_string->message_type())
1213 ->New());
1214 google::protobuf::scoped_ptr<Message> entry_int32_foreign_message(
1215 MessageFactory::generated_factory()
1216 ->GetPrototype(fd_map_int32_foreign_message->message_type())
1217 ->New());
1218
1219 EXPECT_EQ(10, mf_int32_int32.size());
1220 EXPECT_EQ(10, mmf_int32_int32.size());
1221 EXPECT_EQ(10, mf_int32_double.size());
1222 EXPECT_EQ(10, mmf_int32_double.size());
1223 EXPECT_EQ(10, mf_string_string.size());
1224 EXPECT_EQ(10, mmf_string_string.size());
1225 EXPECT_EQ(10, mf_int32_foreign_message.size());
1226 EXPECT_EQ(10, mmf_int32_foreign_message.size());
1227
1228 EXPECT_FALSE(mf_int32_int32.empty());
1229 EXPECT_FALSE(mmf_int32_int32.empty());
1230 EXPECT_FALSE(mf_int32_double.empty());
1231 EXPECT_FALSE(mmf_int32_double.empty());
1232 EXPECT_FALSE(mf_string_string.empty());
1233 EXPECT_FALSE(mmf_string_string.empty());
1234 EXPECT_FALSE(mf_int32_foreign_message.empty());
1235 EXPECT_FALSE(mmf_int32_foreign_message.empty());
1236
1237 // Make sure we can do gets through the RepeatedFieldRef objects.
1238 for (int i = 0; i < 10; ++i) {
1239 {
1240 // Check gets through const objects.
1241 const Message& message_int32_int32 =
1242 mf_int32_int32.Get(i, entry_int32_int32.get());
1243 int32 key_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1244 message_int32_int32, fd_map_int32_in32_key);
1245 int32 value_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1246 message_int32_int32, fd_map_int32_in32_value);
1247 EXPECT_EQ(value_int32_int32, Func(key_int32_int32, 1));
1248
1249 const Message& message_int32_double =
1250 mf_int32_double.Get(i, entry_int32_double.get());
1251 int32 key_int32_double = message_int32_double.GetReflection()->GetInt32(
1252 message_int32_double, fd_map_int32_double_key);
1253 double value_int32_double =
1254 message_int32_double.GetReflection()->GetDouble(
1255 message_int32_double, fd_map_int32_double_value);
1256 EXPECT_EQ(value_int32_double, Func(key_int32_double, 2));
1257
1258 const Message& message_string_string =
1259 mf_string_string.Get(i, entry_string_string.get());
1260 string key_string_string =
1261 message_string_string.GetReflection()->GetString(
1262 message_string_string, fd_map_string_string_key);
1263 string value_string_string =
1264 message_string_string.GetReflection()->GetString(
1265 message_string_string, fd_map_string_string_value);
1266 EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5));
1267
1268 const Message& message_int32_message =
1269 mf_int32_foreign_message.Get(i, entry_int32_foreign_message.get());
1270 int32 key_int32_message = message_int32_message.GetReflection()->GetInt32(
1271 message_int32_message, fd_map_int32_foreign_message_key);
1272 const ForeignMessage& value_int32_message =
1273 down_cast<const ForeignMessage&>(
1274 message_int32_message.GetReflection()
1275 ->GetMessage(message_int32_message,
1276 fd_map_int32_foreign_message_value));
1277 EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6));
1278 }
1279
1280 {
1281 // Check gets through mutable objects.
1282 const Message& message_int32_int32 =
1283 mmf_int32_int32.Get(i, entry_int32_int32.get());
1284 int32 key_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1285 message_int32_int32, fd_map_int32_in32_key);
1286 int32 value_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
1287 message_int32_int32, fd_map_int32_in32_value);
1288 EXPECT_EQ(value_int32_int32, Func(key_int32_int32, 1));
1289
1290 const Message& message_int32_double =
1291 mmf_int32_double.Get(i, entry_int32_double.get());
1292 int32 key_int32_double = message_int32_double.GetReflection()->GetInt32(
1293 message_int32_double, fd_map_int32_double_key);
1294 double value_int32_double =
1295 message_int32_double.GetReflection()->GetDouble(
1296 message_int32_double, fd_map_int32_double_value);
1297 EXPECT_EQ(value_int32_double, Func(key_int32_double, 2));
1298
1299 const Message& message_string_string =
1300 mmf_string_string.Get(i, entry_string_string.get());
1301 string key_string_string =
1302 message_string_string.GetReflection()->GetString(
1303 message_string_string, fd_map_string_string_key);
1304 string value_string_string =
1305 message_string_string.GetReflection()->GetString(
1306 message_string_string, fd_map_string_string_value);
1307 EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5));
1308
1309 const Message& message_int32_message =
1310 mmf_int32_foreign_message.Get(i, entry_int32_foreign_message.get());
1311 int32 key_int32_message = message_int32_message.GetReflection()->GetInt32(
1312 message_int32_message, fd_map_int32_foreign_message_key);
1313 const ForeignMessage& value_int32_message =
1314 down_cast<const ForeignMessage&>(
1315 message_int32_message.GetReflection()
1316 ->GetMessage(message_int32_message,
1317 fd_map_int32_foreign_message_value));
1318 EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6));
1319 }
1320 }
1321
1322 // Make sure we can do sets through the RepeatedFieldRef objects.
1323 for (int i = 0; i < 10; i++) {
1324 const Message& message_int32_int32 =
1325 mmf_int32_int32.Get(i, entry_int32_int32.get());
1326 int key = message_int32_int32.GetReflection()->GetInt32(
1327 message_int32_int32, fd_map_int32_in32_key);
1328
1329 entry_int32_int32->GetReflection()->SetInt32(
1330 entry_int32_int32.get(), fd_map_int32_int32->message_type()->field(0),
1331 key);
1332 entry_int32_int32->GetReflection()->SetInt32(
1333 entry_int32_int32.get(), fd_map_int32_int32->message_type()->field(1),
1334 Func(key, -1));
1335 entry_int32_double->GetReflection()->SetInt32(
1336 entry_int32_double.get(), fd_map_int32_double->message_type()->field(0),
1337 key);
1338 entry_int32_double->GetReflection()->SetDouble(
1339 entry_int32_double.get(), fd_map_int32_double->message_type()->field(1),
1340 Func(key, -2));
1341 entry_string_string->GetReflection()->SetString(
1342 entry_string_string.get(),
1343 fd_map_string_string->message_type()->field(0), StrFunc(key, 1));
1344 entry_string_string->GetReflection()->SetString(
1345 entry_string_string.get(),
1346 fd_map_string_string->message_type()->field(1), StrFunc(key, -5));
1347 entry_int32_foreign_message->GetReflection()->SetInt32(
1348 entry_int32_foreign_message.get(),
1349 fd_map_int32_foreign_message->message_type()->field(0), key);
1350 Message* value_message =
1351 entry_int32_foreign_message->GetReflection()->MutableMessage(
1352 entry_int32_foreign_message.get(),
1353 fd_map_int32_foreign_message->message_type()->field(1));
1354 value_message->GetReflection()->SetInt32(
1355 value_message, value_message->GetDescriptor()->FindFieldByName("c"),
1356 Func(key, -6));
1357
1358 mmf_int32_int32.Set(i, *entry_int32_int32);
1359 mmf_int32_double.Set(i, *entry_int32_double);
1360 mmf_string_string.Set(i, *entry_string_string);
1361 mmf_int32_foreign_message.Set(i, *entry_int32_foreign_message);
1362 }
1363
1364 for (int i = 0; i < 10; i++) {
1365 EXPECT_EQ(Func(i, -1), message.map_int32_int32().at(i));
1366 EXPECT_EQ(Func(i, -2), message.map_int32_double().at(i));
1367 EXPECT_EQ(StrFunc(i, -5), message.map_string_string().at(StrFunc(i, 1)));
1368 EXPECT_EQ(Func(i, -6), message.map_int32_foreign_message().at(i).c());
1369 }
1370
1371 // Test iterators.
1372 {
1373 int index = 0;
1374 hash_map<int32, int32> result;
1375 for (RepeatedFieldRef<Message>::iterator it = mf_int32_int32.begin();
1376 it != mf_int32_int32.end(); ++it) {
1377 const Message& message = *it;
1378 int32 key =
1379 message.GetReflection()->GetInt32(message, fd_map_int32_in32_key);
1380 int32 value =
1381 message.GetReflection()->GetInt32(message, fd_map_int32_in32_value);
1382 result[key] = value;
1383 ++index;
1384 }
1385 EXPECT_EQ(10, index);
1386 for (hash_map<int32, int32>::const_iterator it = result.begin();
1387 it != result.end(); ++it) {
1388 EXPECT_EQ(message.map_int32_int32().at(it->first), it->second);
1389 }
1390 }
1391
1392 {
1393 int index = 0;
1394 hash_map<int32, double> result;
1395 for (RepeatedFieldRef<Message>::iterator it = mf_int32_double.begin();
1396 it != mf_int32_double.end(); ++it) {
1397 const Message& message = *it;
1398 int32 key =
1399 message.GetReflection()->GetInt32(message, fd_map_int32_double_key);
1400 double value = message.GetReflection()->GetDouble(
1401 message, fd_map_int32_double_value);
1402 result[key] = value;
1403 ++index;
1404 }
1405 EXPECT_EQ(10, index);
1406 for (hash_map<int32, double>::const_iterator it = result.begin();
1407 it != result.end(); ++it) {
1408 EXPECT_EQ(message.map_int32_double().at(it->first), it->second);
1409 }
1410 }
1411
1412 {
1413 int index = 0;
1414 hash_map<string, string> result;
1415 for (RepeatedFieldRef<Message>::iterator it = mf_string_string.begin();
1416 it != mf_string_string.end(); ++it) {
1417 const Message& message = *it;
1418 string key =
1419 message.GetReflection()->GetString(message, fd_map_string_string_key);
1420 string value = message.GetReflection()->GetString(
1421 message, fd_map_string_string_value);
1422 result[key] = value;
1423 ++index;
1424 }
1425 EXPECT_EQ(10, index);
1426 for (hash_map<string, string>::const_iterator it = result.begin();
1427 it != result.end(); ++it) {
1428 EXPECT_EQ(message.map_string_string().at(it->first), it->second);
1429 }
1430 }
1431
1432 {
1433 int index = 0;
1434 std::map<int32, ForeignMessage> result;
1435 for (RepeatedFieldRef<Message>::iterator it =
1436 mf_int32_foreign_message.begin();
1437 it != mf_int32_foreign_message.end(); ++it) {
1438 const Message& message = *it;
1439 int32 key = message.GetReflection()->GetInt32(
1440 message, fd_map_int32_foreign_message_key);
1441 const ForeignMessage& sub_message = down_cast<const ForeignMessage&>(
1442 message.GetReflection()
1443 ->GetMessage(message, fd_map_int32_foreign_message_value));
1444 result[key].MergeFrom(sub_message);
1445 ++index;
1446 }
1447 EXPECT_EQ(10, index);
1448 for (std::map<int32, ForeignMessage>::const_iterator it = result.begin();
1449 it != result.end(); ++it) {
1450 EXPECT_EQ(message.map_int32_foreign_message().at(it->first).c(),
1451 it->second.c());
1452 }
1453 }
1454
1455 // Test MutableRepeatedFieldRef::Add()
1456 entry_int32_int32->GetReflection()->SetInt32(
1457 entry_int32_int32.get(), fd_map_int32_int32->message_type()->field(0),
1458 4321);
1459 entry_int32_int32->GetReflection()->SetInt32(
1460 entry_int32_int32.get(), fd_map_int32_int32->message_type()->field(1),
1461 1234);
1462 mmf_int32_int32.Add(*entry_int32_int32);
1463 EXPECT_EQ(1234, message.map_int32_int32().at(4321));
1464
1465 entry_int32_double->GetReflection()->SetInt32(
1466 entry_int32_double.get(), fd_map_int32_double->message_type()->field(0),
1467 4321);
1468 entry_int32_double->GetReflection()->SetDouble(
1469 entry_int32_double.get(), fd_map_int32_double->message_type()->field(1),
1470 1234.0);
1471 mmf_int32_double.Add(*entry_int32_double);
1472 EXPECT_EQ(1234.0, message.map_int32_double().at(4321));
1473
1474 entry_string_string->GetReflection()->SetString(
1475 entry_string_string.get(),
1476 fd_map_string_string->message_type()->field(0), "4321");
1477 entry_string_string->GetReflection()->SetString(
1478 entry_string_string.get(), fd_map_string_string->message_type()->field(1),
1479 "1234");
1480 mmf_string_string.Add(*entry_string_string);
1481 EXPECT_EQ("1234", message.map_string_string().at("4321"));
1482
1483 entry_int32_foreign_message->GetReflection()->SetInt32(
1484 entry_int32_foreign_message.get(),
1485 fd_map_int32_foreign_message->message_type()->field(0), 4321);
1486 Message* value_message =
1487 entry_int32_foreign_message->GetReflection()->MutableMessage(
1488 entry_int32_foreign_message.get(),
1489 fd_map_int32_foreign_message->message_type()->field(1));
1490 ForeignMessage foreign_message;
1491 foreign_message.set_c(1234);
1492 value_message->CopyFrom(foreign_message);
1493
1494 mmf_int32_foreign_message.Add(*entry_int32_foreign_message);
1495 EXPECT_EQ(1234, message.map_int32_foreign_message().at(4321).c());
1496
1497 // Test Reflection::AddAllocatedMessage
1498 Message* free_entry_string_string = MessageFactory::generated_factory()
1499 ->GetPrototype(fd_map_string_string->message_type())
1500 ->New();
1501 entry_string_string->GetReflection()->SetString(
1502 free_entry_string_string,
1503 fd_map_string_string->message_type()->field(0), "4321");
1504 entry_string_string->GetReflection()->SetString(
1505 free_entry_string_string, fd_map_string_string->message_type()->field(1),
1506 "1234");
1507 refl->AddAllocatedMessage(&message, fd_map_string_string,
1508 free_entry_string_string);
1509
1510 // Test MutableRepeatedFieldRef::RemoveLast()
1511 mmf_int32_int32.RemoveLast();
1512 mmf_int32_double.RemoveLast();
1513 mmf_string_string.RemoveLast();
1514 mmf_int32_foreign_message.RemoveLast();
1515 EXPECT_EQ(10, message.map_int32_int32().size());
1516 EXPECT_EQ(10, message.map_int32_double().size());
1517 EXPECT_EQ(11, message.map_string_string().size());
1518 EXPECT_EQ(10, message.map_int32_foreign_message().size());
1519
1520 // Test MutableRepeatedFieldRef::SwapElements()
1521 {
1522 const Message& message0a = mmf_int32_int32.Get(0, entry_int32_int32.get());
1523 int32 int32_value0a =
1524 message0a.GetReflection()->GetInt32(message0a, fd_map_int32_in32_value);
1525 const Message& message9a = mmf_int32_int32.Get(9, entry_int32_int32.get());
1526 int32 int32_value9a =
1527 message9a.GetReflection()->GetInt32(message9a, fd_map_int32_in32_value);
1528
1529 mmf_int32_int32.SwapElements(0, 9);
1530
1531 const Message& message0b = mmf_int32_int32.Get(0, entry_int32_int32.get());
1532 int32 int32_value0b =
1533 message0b.GetReflection()->GetInt32(message0b, fd_map_int32_in32_value);
1534 const Message& message9b = mmf_int32_int32.Get(9, entry_int32_int32.get());
1535 int32 int32_value9b =
1536 message9b.GetReflection()->GetInt32(message9b, fd_map_int32_in32_value);
1537
1538 EXPECT_EQ(int32_value9a, int32_value0b);
1539 EXPECT_EQ(int32_value0a, int32_value9b);
1540 }
1541
1542 {
1543 const Message& message0a =
1544 mmf_int32_double.Get(0, entry_int32_double.get());
1545 double double_value0a = message0a.GetReflection()->GetDouble(
1546 message0a, fd_map_int32_double_value);
1547 const Message& message9a =
1548 mmf_int32_double.Get(9, entry_int32_double.get());
1549 double double_value9a = message9a.GetReflection()->GetDouble(
1550 message9a, fd_map_int32_double_value);
1551
1552 mmf_int32_double.SwapElements(0, 9);
1553
1554 const Message& message0b =
1555 mmf_int32_double.Get(0, entry_int32_double.get());
1556 double double_value0b = message0b.GetReflection()->GetDouble(
1557 message0b, fd_map_int32_double_value);
1558 const Message& message9b =
1559 mmf_int32_double.Get(9, entry_int32_double.get());
1560 double double_value9b = message9b.GetReflection()->GetDouble(
1561 message9b, fd_map_int32_double_value);
1562
1563 EXPECT_EQ(double_value9a, double_value0b);
1564 EXPECT_EQ(double_value0a, double_value9b);
1565 }
1566
1567 {
1568 const Message& message0a =
1569 mmf_string_string.Get(0, entry_string_string.get());
1570 string string_value0a = message0a.GetReflection()->GetString(
1571 message0a, fd_map_string_string_value);
1572 const Message& message9a =
1573 mmf_string_string.Get(9, entry_string_string.get());
1574 string string_value9a = message9a.GetReflection()->GetString(
1575 message9a, fd_map_string_string_value);
1576
1577 mmf_string_string.SwapElements(0, 9);
1578
1579 const Message& message0b =
1580 mmf_string_string.Get(0, entry_string_string.get());
1581 string string_value0b = message0b.GetReflection()->GetString(
1582 message0b, fd_map_string_string_value);
1583 const Message& message9b =
1584 mmf_string_string.Get(9, entry_string_string.get());
1585 string string_value9b = message9b.GetReflection()->GetString(
1586 message9b, fd_map_string_string_value);
1587
1588 EXPECT_EQ(string_value9a, string_value0b);
1589 EXPECT_EQ(string_value0a, string_value9b);
1590 }
1591
1592 {
1593 const Message& message0a =
1594 mmf_int32_foreign_message.Get(0, entry_int32_foreign_message.get());
1595 const ForeignMessage& sub_message0a = down_cast<const ForeignMessage&>(
1596 message0a.GetReflection()
1597 ->GetMessage(message0a, fd_map_int32_foreign_message_value));
1598 int32 int32_value0a = sub_message0a.c();
1599 const Message& message9a =
1600 mmf_int32_foreign_message.Get(9, entry_int32_foreign_message.get());
1601 const ForeignMessage& sub_message9a = down_cast<const ForeignMessage&>(
1602 message9a.GetReflection()
1603 ->GetMessage(message9a, fd_map_int32_foreign_message_value));
1604 int32 int32_value9a = sub_message9a.c();
1605
1606 mmf_int32_foreign_message.SwapElements(0, 9);
1607
1608 const Message& message0b =
1609 mmf_int32_foreign_message.Get(0, entry_int32_foreign_message.get());
1610 const ForeignMessage& sub_message0b = down_cast<const ForeignMessage&>(
1611 message0b.GetReflection()
1612 ->GetMessage(message0b, fd_map_int32_foreign_message_value));
1613 int32 int32_value0b = sub_message0b.c();
1614 const Message& message9b =
1615 mmf_int32_foreign_message.Get(9, entry_int32_foreign_message.get());
1616 const ForeignMessage& sub_message9b = down_cast<const ForeignMessage&>(
1617 message9b.GetReflection()
1618 ->GetMessage(message9b, fd_map_int32_foreign_message_value));
1619 int32 int32_value9b = sub_message9b.c();
1620
1621 EXPECT_EQ(int32_value9a, int32_value0b);
1622 EXPECT_EQ(int32_value0a, int32_value9b);
1623 }
1624 }
1625
TEST_F(MapFieldReflectionTest,RepeatedFieldRefMergeFromAndSwap)1626 TEST_F(MapFieldReflectionTest, RepeatedFieldRefMergeFromAndSwap) {
1627 // Set-up message content.
1628 TestMap m0, m1, m2;
1629 for (int i = 0; i < 10; ++i) {
1630 (*m0.mutable_map_int32_int32())[i] = Func(i, 1);
1631 (*m0.mutable_map_int32_double())[i] = Func(i, 2);
1632 (*m0.mutable_map_string_string())[StrFunc(i, 1)] = StrFunc(i, 5);
1633 (*m0.mutable_map_int32_foreign_message())[i].set_c(Func(i, 6));
1634 (*m1.mutable_map_int32_int32())[i + 10] = Func(i, 11);
1635 (*m1.mutable_map_int32_double())[i + 10] = Func(i, 12);
1636 (*m1.mutable_map_string_string())[StrFunc(i + 10, 1)] = StrFunc(i, 15);
1637 (*m1.mutable_map_int32_foreign_message())[i + 10].set_c(Func(i, 16));
1638 (*m2.mutable_map_int32_int32())[i + 20] = Func(i, 21);
1639 (*m2.mutable_map_int32_double())[i + 20] = Func(i, 22);
1640 (*m2.mutable_map_string_string())[StrFunc(i + 20, 1)] = StrFunc(i, 25);
1641 (*m2.mutable_map_int32_foreign_message())[i + 20].set_c(Func(i, 26));
1642 }
1643
1644 const Reflection* refl = m0.GetReflection();
1645 const Descriptor* desc = m0.GetDescriptor();
1646
1647 // Get FieldDescriptors for all the fields of interest.
1648 const FieldDescriptor* fd_map_int32_int32 =
1649 desc->FindFieldByName("map_int32_int32");
1650 const FieldDescriptor* fd_map_int32_double =
1651 desc->FindFieldByName("map_int32_double");
1652 const FieldDescriptor* fd_map_string_string =
1653 desc->FindFieldByName("map_string_string");
1654 const FieldDescriptor* fd_map_int32_foreign_message =
1655 desc->FindFieldByName("map_int32_foreign_message");
1656
1657 // Get MutableRepeatedFieldRef objects for all fields of interest.
1658 const MutableRepeatedFieldRef<Message> mmf_int32_int32 =
1659 refl->GetMutableRepeatedFieldRef<Message>(
1660 &m0, fd_map_int32_int32);
1661 const MutableRepeatedFieldRef<Message> mmf_int32_double =
1662 refl->GetMutableRepeatedFieldRef<Message>(
1663 &m0, fd_map_int32_double);
1664 const MutableRepeatedFieldRef<Message> mmf_string_string =
1665 refl->GetMutableRepeatedFieldRef<Message>(
1666 &m0, fd_map_string_string);
1667 const MutableRepeatedFieldRef<Message>
1668 mmf_int32_foreign_message =
1669 refl->GetMutableRepeatedFieldRef<Message>(
1670 &m0, fd_map_int32_foreign_message);
1671
1672 // Test MutableRepeatedRef::CopyFrom
1673 mmf_int32_int32.CopyFrom(
1674 refl->GetRepeatedFieldRef<Message>(
1675 m1, fd_map_int32_int32));
1676 mmf_int32_double.CopyFrom(
1677 refl->GetRepeatedFieldRef<Message>(
1678 m1, fd_map_int32_double));
1679 mmf_string_string.CopyFrom(
1680 refl->GetRepeatedFieldRef<Message>(
1681 m1, fd_map_string_string));
1682 mmf_int32_foreign_message.CopyFrom(
1683 refl->GetRepeatedFieldRef<Message>(
1684 m1, fd_map_int32_foreign_message));
1685
1686 for (int i = 0; i < 10; ++i) {
1687 EXPECT_EQ(Func(i, 11), m0.map_int32_int32().at(i + 10));
1688 EXPECT_EQ(Func(i, 12), m0.map_int32_double().at(i + 10));
1689 EXPECT_EQ(StrFunc(i, 15), m0.map_string_string().at(StrFunc(i + 10, 1)));
1690 EXPECT_EQ(Func(i, 16), m0.map_int32_foreign_message().at(i + 10).c());
1691 }
1692
1693 // Test MutableRepeatedRef::MergeFrom
1694 mmf_int32_int32.MergeFrom(
1695 refl->GetRepeatedFieldRef<Message>(
1696 m2, fd_map_int32_int32));
1697 mmf_int32_double.MergeFrom(
1698 refl->GetRepeatedFieldRef<Message>(
1699 m2, fd_map_int32_double));
1700 mmf_string_string.MergeFrom(
1701 refl->GetRepeatedFieldRef<Message>(
1702 m2, fd_map_string_string));
1703 mmf_int32_foreign_message.MergeFrom(
1704 refl->GetRepeatedFieldRef<Message>(
1705 m2, fd_map_int32_foreign_message));
1706 for (int i = 0; i < 10; ++i) {
1707 EXPECT_EQ(Func(i, 21), m0.map_int32_int32().at(i + 20));
1708 EXPECT_EQ(Func(i, 22), m0.map_int32_double().at(i + 20));
1709 EXPECT_EQ(StrFunc(i, 25), m0.map_string_string().at(StrFunc(i + 20, 1)));
1710 EXPECT_EQ(Func(i, 26), m0.map_int32_foreign_message().at(i + 20).c());
1711 }
1712
1713 // Test MutableRepeatedRef::Swap
1714 // Swap between m0 and m2.
1715 mmf_int32_int32.Swap(
1716 refl->GetMutableRepeatedFieldRef<Message>(
1717 &m2, fd_map_int32_int32));
1718 mmf_int32_double.Swap(
1719 refl->GetMutableRepeatedFieldRef<Message>(
1720 &m2, fd_map_int32_double));
1721 mmf_string_string.Swap(
1722 refl->GetMutableRepeatedFieldRef<Message>(
1723 &m2, fd_map_string_string));
1724 mmf_int32_foreign_message.Swap(
1725 refl->GetMutableRepeatedFieldRef<Message>(
1726 &m2, fd_map_int32_foreign_message));
1727 for (int i = 0; i < 10; ++i) {
1728 // Check the content of m0.
1729 EXPECT_EQ(Func(i, 21), m0.map_int32_int32().at(i + 20));
1730 EXPECT_EQ(Func(i, 22), m0.map_int32_double().at(i + 20));
1731 EXPECT_EQ(StrFunc(i, 25), m0.map_string_string().at(StrFunc(i + 20, 1)));
1732 EXPECT_EQ(Func(i, 26), m0.map_int32_foreign_message().at(i + 20).c());
1733
1734 // Check the content of m2.
1735 EXPECT_EQ(Func(i, 11), m2.map_int32_int32().at(i + 10));
1736 EXPECT_EQ(Func(i, 12), m2.map_int32_double().at(i + 10));
1737 EXPECT_EQ(StrFunc(i, 15), m2.map_string_string().at(StrFunc(i + 10, 1)));
1738 EXPECT_EQ(Func(i, 16), m2.map_int32_foreign_message().at(i + 10).c());
1739 EXPECT_EQ(Func(i, 21), m2.map_int32_int32().at(i + 20));
1740 EXPECT_EQ(Func(i, 22), m2.map_int32_double().at(i + 20));
1741 EXPECT_EQ(StrFunc(i, 25), m2.map_string_string().at(StrFunc(i + 20, 1)));
1742 EXPECT_EQ(Func(i, 26), m2.map_int32_foreign_message().at(i + 20).c());
1743 }
1744
1745 // TODO(teboring): add test for duplicated key
1746 }
1747
1748 // Generated Message Test ===========================================
1749
TEST(GeneratedMapFieldTest,Accessors)1750 TEST(GeneratedMapFieldTest, Accessors) {
1751 unittest::TestMap message;
1752
1753 MapTestUtil::SetMapFields(&message);
1754 MapTestUtil::ExpectMapFieldsSet(message);
1755
1756 MapTestUtil::ModifyMapFields(&message);
1757 MapTestUtil::ExpectMapFieldsModified(message);
1758 }
1759
TEST(GeneratedMapFieldTest,SetMapFieldsInitialized)1760 TEST(GeneratedMapFieldTest, SetMapFieldsInitialized) {
1761 unittest::TestMap message;
1762
1763 MapTestUtil::SetMapFieldsInitialized(&message);
1764 MapTestUtil::ExpectMapFieldsSetInitialized(message);
1765 }
1766
TEST(GeneratedMapFieldTest,Proto2SetMapFieldsInitialized)1767 TEST(GeneratedMapFieldTest, Proto2SetMapFieldsInitialized) {
1768 unittest::TestEnumMap message;
1769 EXPECT_EQ(unittest::PROTO2_MAP_ENUM_FOO,
1770 (*message.mutable_known_map_field())[0]);
1771 }
1772
TEST(GeneratedMapFieldTest,Clear)1773 TEST(GeneratedMapFieldTest, Clear) {
1774 unittest::TestMap message;
1775
1776 MapTestUtil::SetMapFields(&message);
1777 message.Clear();
1778 MapTestUtil::ExpectClear(message);
1779 }
1780
TEST(GeneratedMapFieldTest,ClearMessageMap)1781 TEST(GeneratedMapFieldTest, ClearMessageMap) {
1782 unittest::TestMessageMap message;
1783
1784 // Creates a TestAllTypes with default value
1785 TestUtil::ExpectClear((*message.mutable_map_int32_message())[0]);
1786 }
1787
TEST(GeneratedMapFieldTest,CopyFrom)1788 TEST(GeneratedMapFieldTest, CopyFrom) {
1789 unittest::TestMap message1, message2;
1790
1791 MapTestUtil::SetMapFields(&message1);
1792 message2.CopyFrom(message1);
1793 MapTestUtil::ExpectMapFieldsSet(message2);
1794
1795 // Copying from self should be a no-op.
1796 message2.CopyFrom(message2);
1797 MapTestUtil::ExpectMapFieldsSet(message2);
1798 }
1799
TEST(GeneratedMapFieldTest,CopyFromMessageMap)1800 TEST(GeneratedMapFieldTest, CopyFromMessageMap) {
1801 unittest::TestMessageMap message1, message2;
1802
1803 (*message1.mutable_map_int32_message())[0].add_repeated_int32(100);
1804 (*message2.mutable_map_int32_message())[0].add_repeated_int32(101);
1805
1806 message1.CopyFrom(message2);
1807
1808 // Checks repeated field is overwritten.
1809 EXPECT_EQ(1, message1.map_int32_message().at(0).repeated_int32_size());
1810 EXPECT_EQ(101, message1.map_int32_message().at(0).repeated_int32(0));
1811 }
1812
TEST(GeneratedMapFieldTest,SwapWithEmpty)1813 TEST(GeneratedMapFieldTest, SwapWithEmpty) {
1814 unittest::TestMap message1, message2;
1815
1816 MapTestUtil::SetMapFields(&message1);
1817 MapTestUtil::ExpectMapFieldsSet(message1);
1818 MapTestUtil::ExpectClear(message2);
1819
1820 message1.Swap(&message2);
1821 MapTestUtil::ExpectMapFieldsSet(message2);
1822 MapTestUtil::ExpectClear(message1);
1823 }
1824
TEST(GeneratedMapFieldTest,SwapWithSelf)1825 TEST(GeneratedMapFieldTest, SwapWithSelf) {
1826 unittest::TestMap message;
1827
1828 MapTestUtil::SetMapFields(&message);
1829 MapTestUtil::ExpectMapFieldsSet(message);
1830
1831 message.Swap(&message);
1832 MapTestUtil::ExpectMapFieldsSet(message);
1833 }
1834
TEST(GeneratedMapFieldTest,SwapWithOther)1835 TEST(GeneratedMapFieldTest, SwapWithOther) {
1836 unittest::TestMap message1, message2;
1837
1838 MapTestUtil::SetMapFields(&message1);
1839 MapTestUtil::SetMapFields(&message2);
1840 MapTestUtil::ModifyMapFields(&message2);
1841
1842 message1.Swap(&message2);
1843 MapTestUtil::ExpectMapFieldsModified(message1);
1844 MapTestUtil::ExpectMapFieldsSet(message2);
1845 }
1846
TEST(GeneratedMapFieldTest,CopyConstructor)1847 TEST(GeneratedMapFieldTest, CopyConstructor) {
1848 unittest::TestMap message1;
1849 MapTestUtil::SetMapFields(&message1);
1850
1851 unittest::TestMap message2(message1);
1852 MapTestUtil::ExpectMapFieldsSet(message2);
1853 }
1854
TEST(GeneratedMapFieldTest,CopyAssignmentOperator)1855 TEST(GeneratedMapFieldTest, CopyAssignmentOperator) {
1856 unittest::TestMap message1;
1857 MapTestUtil::SetMapFields(&message1);
1858
1859 unittest::TestMap message2;
1860 message2 = message1;
1861 MapTestUtil::ExpectMapFieldsSet(message2);
1862
1863 // Make sure that self-assignment does something sane.
1864 message2.operator=(message2);
1865 MapTestUtil::ExpectMapFieldsSet(message2);
1866 }
1867
1868 #if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \
1869 !defined(GOOGLE_PROTOBUF_NO_RTTI)
TEST(GeneratedMapFieldTest,UpcastCopyFrom)1870 TEST(GeneratedMapFieldTest, UpcastCopyFrom) {
1871 // Test the CopyFrom method that takes in the generic const Message&
1872 // parameter.
1873 unittest::TestMap message1, message2;
1874
1875 MapTestUtil::SetMapFields(&message1);
1876
1877 const Message* source = implicit_cast<const Message*>(&message1);
1878 message2.CopyFrom(*source);
1879
1880 MapTestUtil::ExpectMapFieldsSet(message2);
1881 }
1882 #endif
1883
1884 #ifndef PROTOBUF_TEST_NO_DESCRIPTORS
1885
TEST(GeneratedMapFieldTest,CopyFromDynamicMessage)1886 TEST(GeneratedMapFieldTest, CopyFromDynamicMessage) {
1887 // Test copying from a DynamicMessage, which must fall back to using
1888 // reflection.
1889 unittest::TestMap message2;
1890
1891 // Construct a new version of the dynamic message via the factory.
1892 DynamicMessageFactory factory;
1893 google::protobuf::scoped_ptr<Message> message1;
1894 message1.reset(
1895 factory.GetPrototype(unittest::TestMap::descriptor())->New());
1896 MapReflectionTester reflection_tester(
1897 unittest::TestMap::descriptor());
1898 reflection_tester.SetMapFieldsViaReflection(message1.get());
1899 reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
1900 reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get());
1901 message2.CopyFrom(*message1);
1902 MapTestUtil::ExpectMapFieldsSet(message2);
1903 }
1904
TEST(GeneratedMapFieldTest,CopyFromDynamicMessageMapReflection)1905 TEST(GeneratedMapFieldTest, CopyFromDynamicMessageMapReflection) {
1906 unittest::TestMap message2;
1907
1908 // Construct a new version of the dynamic message via the factory.
1909 DynamicMessageFactory factory;
1910 google::protobuf::scoped_ptr<Message> message1;
1911 message1.reset(
1912 factory.GetPrototype(unittest::TestMap::descriptor())->New());
1913 MapReflectionTester reflection_tester(
1914 unittest::TestMap::descriptor());
1915 reflection_tester.SetMapFieldsViaMapReflection(message1.get());
1916 reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
1917 reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get());
1918 message2.CopyFrom(*message1);
1919 MapTestUtil::ExpectMapFieldsSet(message2);
1920 }
1921
TEST(GeneratedMapFieldTest,DynamicMessageCopyFrom)1922 TEST(GeneratedMapFieldTest, DynamicMessageCopyFrom) {
1923 // Test copying to a DynamicMessage, which must fall back to using reflection.
1924 unittest::TestMap message2;
1925 MapTestUtil::SetMapFields(&message2);
1926
1927 // Construct a new version of the dynamic message via the factory.
1928 DynamicMessageFactory factory;
1929 google::protobuf::scoped_ptr<Message> message1;
1930 message1.reset(
1931 factory.GetPrototype(unittest::TestMap::descriptor())->New());
1932
1933 MapReflectionTester reflection_tester(
1934 unittest::TestMap::descriptor());
1935 message1->MergeFrom(message2);
1936 reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
1937 reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get());
1938 }
1939
TEST(GeneratedMapFieldTest,DynamicMessageCopyFromMapReflection)1940 TEST(GeneratedMapFieldTest, DynamicMessageCopyFromMapReflection) {
1941 MapReflectionTester reflection_tester(
1942 unittest::TestMap::descriptor());
1943 unittest::TestMap message2;
1944 reflection_tester.SetMapFieldsViaMapReflection(&message2);
1945
1946 // Construct a dynamic message via the factory.
1947 DynamicMessageFactory factory;
1948 google::protobuf::scoped_ptr<Message> message1;
1949 message1.reset(
1950 factory.GetPrototype(unittest::TestMap::descriptor())->New());
1951
1952 message1->MergeFrom(message2);
1953 reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get());
1954 reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
1955 }
1956
TEST(GeneratedMapFieldTest,SyncDynamicMapWithRepeatedField)1957 TEST(GeneratedMapFieldTest, SyncDynamicMapWithRepeatedField) {
1958 // Construct a dynamic message via the factory.
1959 MapReflectionTester reflection_tester(
1960 unittest::TestMap::descriptor());
1961 DynamicMessageFactory factory;
1962 google::protobuf::scoped_ptr<Message> message;
1963 message.reset(
1964 factory.GetPrototype(unittest::TestMap::descriptor())->New());
1965 reflection_tester.SetMapFieldsViaReflection(message.get());
1966 reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message.get());
1967 reflection_tester.ExpectMapFieldsSetViaReflection(*message);
1968 }
1969
1970 #endif // !PROTOBUF_TEST_NO_DESCRIPTORS
1971
TEST(GeneratedMapFieldTest,NonEmptyMergeFrom)1972 TEST(GeneratedMapFieldTest, NonEmptyMergeFrom) {
1973 unittest::TestMap message1, message2;
1974
1975 MapTestUtil::SetMapFields(&message1);
1976
1977 // This field will test merging into an empty spot.
1978 (*message2.mutable_map_int32_int32())[1] = 1;
1979 message1.mutable_map_int32_int32()->erase(1);
1980
1981 // This tests overwriting.
1982 (*message2.mutable_map_int32_double())[1] = 1;
1983 (*message1.mutable_map_int32_double())[1] = 2;
1984
1985 message1.MergeFrom(message2);
1986 MapTestUtil::ExpectMapFieldsSet(message1);
1987 }
1988
TEST(GeneratedMapFieldTest,MergeFromMessageMap)1989 TEST(GeneratedMapFieldTest, MergeFromMessageMap) {
1990 unittest::TestMessageMap message1, message2;
1991
1992 (*message1.mutable_map_int32_message())[0].add_repeated_int32(100);
1993 (*message2.mutable_map_int32_message())[0].add_repeated_int32(101);
1994
1995 message1.MergeFrom(message2);
1996
1997 // Checks repeated field is overwritten.
1998 EXPECT_EQ(1, message1.map_int32_message().at(0).repeated_int32_size());
1999 EXPECT_EQ(101, message1.map_int32_message().at(0).repeated_int32(0));
2000 }
2001
2002 // Test the generated SerializeWithCachedSizesToArray()
TEST(GeneratedMapFieldTest,SerializationToArray)2003 TEST(GeneratedMapFieldTest, SerializationToArray) {
2004 unittest::TestMap message1, message2;
2005 string data;
2006 MapTestUtil::SetMapFields(&message1);
2007 int size = message1.ByteSize();
2008 data.resize(size);
2009 uint8* start = reinterpret_cast<uint8*>(string_as_array(&data));
2010 uint8* end = message1.SerializeWithCachedSizesToArray(start);
2011 EXPECT_EQ(size, end - start);
2012 EXPECT_TRUE(message2.ParseFromString(data));
2013 MapTestUtil::ExpectMapFieldsSet(message2);
2014 }
2015
2016 // Test the generated SerializeWithCachedSizes()
TEST(GeneratedMapFieldTest,SerializationToStream)2017 TEST(GeneratedMapFieldTest, SerializationToStream) {
2018 unittest::TestMap message1, message2;
2019 MapTestUtil::SetMapFields(&message1);
2020 int size = message1.ByteSize();
2021 string data;
2022 data.resize(size);
2023 {
2024 // Allow the output stream to buffer only one byte at a time.
2025 io::ArrayOutputStream array_stream(string_as_array(&data), size, 1);
2026 io::CodedOutputStream output_stream(&array_stream);
2027 message1.SerializeWithCachedSizes(&output_stream);
2028 EXPECT_FALSE(output_stream.HadError());
2029 EXPECT_EQ(size, output_stream.ByteCount());
2030 }
2031 EXPECT_TRUE(message2.ParseFromString(data));
2032 MapTestUtil::ExpectMapFieldsSet(message2);
2033 }
2034
2035
TEST(GeneratedMapFieldTest,SameTypeMaps)2036 TEST(GeneratedMapFieldTest, SameTypeMaps) {
2037 const Descriptor* map1 = unittest::TestSameTypeMap::descriptor()
2038 ->FindFieldByName("map1")
2039 ->message_type();
2040 const Descriptor* map2 = unittest::TestSameTypeMap::descriptor()
2041 ->FindFieldByName("map2")
2042 ->message_type();
2043
2044 const Message* map1_entry =
2045 MessageFactory::generated_factory()->GetPrototype(map1);
2046 const Message* map2_entry =
2047 MessageFactory::generated_factory()->GetPrototype(map2);
2048
2049 EXPECT_EQ(map1, map1_entry->GetDescriptor());
2050 EXPECT_EQ(map2, map2_entry->GetDescriptor());
2051 }
2052
TEST(GeneratedMapFieldTest,Proto2UnknownEnum)2053 TEST(GeneratedMapFieldTest, Proto2UnknownEnum) {
2054 unittest::TestEnumMapPlusExtra from;
2055 (*from.mutable_known_map_field())[0] = unittest::E_PROTO2_MAP_ENUM_FOO;
2056 (*from.mutable_unknown_map_field())[0] = unittest::E_PROTO2_MAP_ENUM_EXTRA;
2057 string data;
2058 from.SerializeToString(&data);
2059
2060 unittest::TestEnumMap to;
2061 EXPECT_TRUE(to.ParseFromString(data));
2062 EXPECT_EQ(0, to.unknown_map_field().size());
2063 const UnknownFieldSet& unknown_field_set =
2064 to.GetReflection()->GetUnknownFields(to);
2065 EXPECT_EQ(1, unknown_field_set.field_count());
2066 EXPECT_EQ(1, to.known_map_field().size());
2067 EXPECT_EQ(unittest::PROTO2_MAP_ENUM_FOO, to.known_map_field().at(0));
2068
2069 data.clear();
2070 from.Clear();
2071 to.SerializeToString(&data);
2072 EXPECT_TRUE(from.ParseFromString(data));
2073 EXPECT_EQ(0, from.GetReflection()->GetUnknownFields(from).field_count());
2074 EXPECT_EQ(1, from.known_map_field().size());
2075 EXPECT_EQ(unittest::E_PROTO2_MAP_ENUM_FOO, from.known_map_field().at(0));
2076 EXPECT_EQ(1, from.unknown_map_field().size());
2077 EXPECT_EQ(unittest::E_PROTO2_MAP_ENUM_EXTRA, from.unknown_map_field().at(0));
2078 }
2079
TEST(GeneratedMapFieldTest,StandardWireFormat)2080 TEST(GeneratedMapFieldTest, StandardWireFormat) {
2081 unittest::TestMap message;
2082 string data = "\x0A\x04\x08\x01\x10\x01";
2083
2084 EXPECT_TRUE(message.ParseFromString(data));
2085 EXPECT_EQ(1, message.map_int32_int32().size());
2086 EXPECT_EQ(1, message.map_int32_int32().at(1));
2087 }
2088
TEST(GeneratedMapFieldTest,UnorderedWireFormat)2089 TEST(GeneratedMapFieldTest, UnorderedWireFormat) {
2090 unittest::TestMap message;
2091
2092 // put value before key in wire format
2093 string data = "\x0A\x04\x10\x01\x08\x02";
2094
2095 EXPECT_TRUE(message.ParseFromString(data));
2096 EXPECT_EQ(1, message.map_int32_int32().size());
2097 EXPECT_EQ(1, message.map_int32_int32().at(2));
2098 }
2099
TEST(GeneratedMapFieldTest,DuplicatedKeyWireFormat)2100 TEST(GeneratedMapFieldTest, DuplicatedKeyWireFormat) {
2101 unittest::TestMap message;
2102
2103 // Two key fields in wire format
2104 string data = "\x0A\x06\x08\x01\x08\x02\x10\x01";
2105
2106 EXPECT_TRUE(message.ParseFromString(data));
2107 EXPECT_EQ(1, message.map_int32_int32().size());
2108 EXPECT_EQ(1, message.map_int32_int32().at(2));
2109 }
2110
TEST(GeneratedMapFieldTest,DuplicatedValueWireFormat)2111 TEST(GeneratedMapFieldTest, DuplicatedValueWireFormat) {
2112 unittest::TestMap message;
2113
2114 // Two value fields in wire format
2115 string data = "\x0A\x06\x08\x01\x10\x01\x10\x02";
2116
2117 EXPECT_TRUE(message.ParseFromString(data));
2118 EXPECT_EQ(1, message.map_int32_int32().size());
2119 EXPECT_EQ(2, message.map_int32_int32().at(1));
2120 }
2121
TEST(GeneratedMapFieldTest,MissedKeyWireFormat)2122 TEST(GeneratedMapFieldTest, MissedKeyWireFormat) {
2123 unittest::TestMap message;
2124
2125 // No key field in wire format
2126 string data = "\x0A\x02\x10\x01";
2127
2128 EXPECT_TRUE(message.ParseFromString(data));
2129 EXPECT_EQ(1, message.map_int32_int32().size());
2130 EXPECT_EQ(1, message.map_int32_int32().at(0));
2131 }
2132
TEST(GeneratedMapFieldTest,MissedValueWireFormat)2133 TEST(GeneratedMapFieldTest, MissedValueWireFormat) {
2134 unittest::TestMap message;
2135
2136 // No value field in wire format
2137 string data = "\x0A\x02\x08\x01";
2138
2139 EXPECT_TRUE(message.ParseFromString(data));
2140 EXPECT_EQ(1, message.map_int32_int32().size());
2141 EXPECT_EQ(0, message.map_int32_int32().at(1));
2142 }
2143
TEST(GeneratedMapFieldTest,MissedValueTextFormat)2144 TEST(GeneratedMapFieldTest, MissedValueTextFormat) {
2145 unittest::TestMap message;
2146
2147 // No value field in text format
2148 string text =
2149 "map_int32_foreign_message {\n"
2150 " key: 1234567890\n"
2151 "}";
2152
2153 EXPECT_TRUE(google::protobuf::TextFormat::ParseFromString(text, &message));
2154 EXPECT_EQ(1, message.map_int32_foreign_message().size());
2155 EXPECT_EQ(11, message.ByteSize());
2156 }
2157
TEST(GeneratedMapFieldTest,UnknownFieldWireFormat)2158 TEST(GeneratedMapFieldTest, UnknownFieldWireFormat) {
2159 unittest::TestMap message;
2160
2161 // Unknown field in wire format
2162 string data = "\x0A\x06\x08\x02\x10\x03\x18\x01";
2163
2164 EXPECT_TRUE(message.ParseFromString(data));
2165 EXPECT_EQ(1, message.map_int32_int32().size());
2166 EXPECT_EQ(3, message.map_int32_int32().at(2));
2167 }
2168
TEST(GeneratedMapFieldTest,CorruptedWireFormat)2169 TEST(GeneratedMapFieldTest, CorruptedWireFormat) {
2170 unittest::TestMap message;
2171
2172 // corrupted data in wire format
2173 string data = "\x0A\x06\x08\x02\x11\x03";
2174
2175 EXPECT_FALSE(message.ParseFromString(data));
2176 }
2177
TEST(GeneratedMapFieldTest,IsInitialized)2178 TEST(GeneratedMapFieldTest, IsInitialized) {
2179 unittest::TestRequiredMessageMap map_message;
2180
2181 // Add an uninitialized message.
2182 (*map_message.mutable_map_field())[0];
2183 EXPECT_FALSE(map_message.IsInitialized());
2184
2185 // Initialize uninitialized message
2186 (*map_message.mutable_map_field())[0].set_a(0);
2187 (*map_message.mutable_map_field())[0].set_b(0);
2188 (*map_message.mutable_map_field())[0].set_c(0);
2189 EXPECT_TRUE(map_message.IsInitialized());
2190 }
2191
2192 // Generated Message Reflection Test ================================
2193
TEST(GeneratedMapFieldReflectionTest,SpaceUsed)2194 TEST(GeneratedMapFieldReflectionTest, SpaceUsed) {
2195 unittest::TestMap message;
2196 MapReflectionTester reflection_tester(
2197 unittest::TestMap::descriptor());
2198 reflection_tester.SetMapFieldsViaReflection(&message);
2199
2200 EXPECT_LT(0, message.GetReflection()->SpaceUsed(message));
2201 }
2202
TEST(GeneratedMapFieldReflectionTest,Accessors)2203 TEST(GeneratedMapFieldReflectionTest, Accessors) {
2204 // Set every field to a unique value then go back and check all those
2205 // values.
2206 unittest::TestMap message;
2207 MapReflectionTester reflection_tester(
2208 unittest::TestMap::descriptor());
2209 reflection_tester.SetMapFieldsViaReflection(&message);
2210 MapTestUtil::ExpectMapFieldsSet(message);
2211 reflection_tester.ExpectMapFieldsSetViaReflection(message);
2212 reflection_tester.ExpectMapFieldsSetViaReflectionIterator(&message);
2213
2214 reflection_tester.ModifyMapFieldsViaReflection(&message);
2215 MapTestUtil::ExpectMapFieldsModified(message);
2216 }
2217
TEST(GeneratedMapFieldReflectionTest,Swap)2218 TEST(GeneratedMapFieldReflectionTest, Swap) {
2219 unittest::TestMap message1;
2220 unittest::TestMap message2;
2221
2222 MapTestUtil::SetMapFields(&message1);
2223
2224 const Reflection* reflection = message1.GetReflection();
2225 reflection->Swap(&message1, &message2);
2226
2227 MapTestUtil::ExpectClear(message1);
2228 MapTestUtil::ExpectMapFieldsSet(message2);
2229 }
2230
TEST(GeneratedMapFieldReflectionTest,SwapWithBothSet)2231 TEST(GeneratedMapFieldReflectionTest, SwapWithBothSet) {
2232 unittest::TestMap message1;
2233 unittest::TestMap message2;
2234
2235 MapTestUtil::SetMapFields(&message1);
2236 MapTestUtil::SetMapFields(&message2);
2237 MapTestUtil::ModifyMapFields(&message2);
2238
2239 const Reflection* reflection = message1.GetReflection();
2240 reflection->Swap(&message1, &message2);
2241
2242 MapTestUtil::ExpectMapFieldsModified(message1);
2243 MapTestUtil::ExpectMapFieldsSet(message2);
2244 }
2245
TEST(GeneratedMapFieldReflectionTest,SwapFields)2246 TEST(GeneratedMapFieldReflectionTest, SwapFields) {
2247 unittest::TestMap message1;
2248 unittest::TestMap message2;
2249
2250 MapTestUtil::SetMapFields(&message2);
2251
2252 vector<const FieldDescriptor*> fields;
2253 const Reflection* reflection = message1.GetReflection();
2254 reflection->ListFields(message2, &fields);
2255 reflection->SwapFields(&message1, &message2, fields);
2256
2257 MapTestUtil::ExpectMapFieldsSet(message1);
2258 MapTestUtil::ExpectClear(message2);
2259 }
2260
TEST(GeneratedMapFieldReflectionTest,ClearField)2261 TEST(GeneratedMapFieldReflectionTest, ClearField) {
2262 unittest::TestMap message;
2263 MapTestUtil::SetMapFields(&message);
2264 MapTestUtil::ExpectMapFieldsSet(message);
2265
2266 MapReflectionTester reflection_tester(
2267 unittest::TestMap::descriptor());
2268 reflection_tester.ClearMapFieldsViaReflection(&message);
2269 reflection_tester.ExpectClearViaReflection(message);
2270 reflection_tester.ExpectClearViaReflectionIterator(&message);
2271 }
2272
TEST(GeneratedMapFieldReflectionTest,RemoveLast)2273 TEST(GeneratedMapFieldReflectionTest, RemoveLast) {
2274 unittest::TestMap message;
2275 MapReflectionTester reflection_tester(
2276 unittest::TestMap::descriptor());
2277
2278 MapTestUtil::SetMapFields(&message);
2279 MapTestUtil::ExpectMapsSize(message, 2);
2280 std::vector<const Message*> expected_entries =
2281 MapTestUtil::GetMapEntries(message, 0);
2282
2283 reflection_tester.RemoveLastMapsViaReflection(&message);
2284
2285 MapTestUtil::ExpectMapsSize(message, 1);
2286 std::vector<const Message*> remained_entries =
2287 MapTestUtil::GetMapEntries(message, 0);
2288 EXPECT_TRUE(expected_entries == remained_entries);
2289 }
2290
TEST(GeneratedMapFieldReflectionTest,ReleaseLast)2291 TEST(GeneratedMapFieldReflectionTest, ReleaseLast) {
2292 unittest::TestMap message;
2293 const Descriptor* descriptor = message.GetDescriptor();
2294 MapReflectionTester reflection_tester(descriptor);
2295
2296 MapTestUtil::SetMapFields(&message);
2297
2298 MapTestUtil::ExpectMapsSize(message, 2);
2299
2300 reflection_tester.ReleaseLastMapsViaReflection(&message);
2301
2302 MapTestUtil::ExpectMapsSize(message, 1);
2303
2304 // Now test that we actually release the right message.
2305 message.Clear();
2306 MapTestUtil::SetMapFields(&message);
2307
2308 MapTestUtil::ExpectMapsSize(message, 2);
2309 std::vector<const Message*> expect_last =
2310 MapTestUtil::GetMapEntries(message, 1);
2311 std::vector<const Message*> release_last =
2312 MapTestUtil::GetMapEntriesFromRelease(&message);
2313 MapTestUtil::ExpectMapsSize(message, 1);
2314 EXPECT_TRUE(expect_last == release_last);
2315 for (std::vector<const Message*>::iterator it = release_last.begin();
2316 it != release_last.end(); ++it) {
2317 delete *it;
2318 }
2319 }
2320
TEST(GeneratedMapFieldReflectionTest,SwapElements)2321 TEST(GeneratedMapFieldReflectionTest, SwapElements) {
2322 unittest::TestMap message;
2323 MapReflectionTester reflection_tester(
2324 unittest::TestMap::descriptor());
2325
2326 MapTestUtil::SetMapFields(&message);
2327
2328 // Get pointers of map entries at their original position
2329 std::vector<const Message*> entries0 = MapTestUtil::GetMapEntries(message, 0);
2330 std::vector<const Message*> entries1 = MapTestUtil::GetMapEntries(message, 1);
2331
2332 // Swap the first time.
2333 reflection_tester.SwapMapsViaReflection(&message);
2334
2335 // Get pointer of map entry after swap once.
2336 std::vector<const Message*> entries0_once =
2337 MapTestUtil::GetMapEntries(message, 0);
2338 std::vector<const Message*> entries1_once =
2339 MapTestUtil::GetMapEntries(message, 1);
2340
2341 // Test map entries are swapped.
2342 MapTestUtil::ExpectMapsSize(message, 2);
2343 EXPECT_TRUE(entries0 == entries1_once);
2344 EXPECT_TRUE(entries1 == entries0_once);
2345
2346 // Swap the second time.
2347 reflection_tester.SwapMapsViaReflection(&message);
2348
2349 // Get pointer of map entry after swap once.
2350 std::vector<const Message*> entries0_twice =
2351 MapTestUtil::GetMapEntries(message, 0);
2352 std::vector<const Message*> entries1_twice =
2353 MapTestUtil::GetMapEntries(message, 1);
2354
2355 // Test map entries are swapped back.
2356 MapTestUtil::ExpectMapsSize(message, 2);
2357 EXPECT_TRUE(entries0 == entries0_twice);
2358 EXPECT_TRUE(entries1 == entries1_twice);
2359 }
2360
TEST(GeneratedMapFieldReflectionTest,MutableUnknownFields)2361 TEST(GeneratedMapFieldReflectionTest, MutableUnknownFields) {
2362 unittest::TestMap message;
2363 MapReflectionTester reflection_tester(
2364 unittest::TestMap::descriptor());
2365 reflection_tester.MutableUnknownFieldsOfMapFieldsViaReflection(&message);
2366 }
2367
TEST(GeneratedMapFieldReflectionTest,EmbedProto2Message)2368 TEST(GeneratedMapFieldReflectionTest, EmbedProto2Message) {
2369 unittest::TestMessageMap message;
2370
2371 const FieldDescriptor* map_field =
2372 unittest::TestMessageMap::descriptor()->FindFieldByName(
2373 "map_int32_message");
2374 const FieldDescriptor* value =
2375 map_field->message_type()->FindFieldByName("value");
2376
2377 Message* entry_message =
2378 message.GetReflection()->AddMessage(&message, map_field);
2379 EXPECT_EQ(
2380 &entry_message->GetReflection()->GetMessage(*entry_message, value),
2381 reinterpret_cast<const Message*>(&TestAllTypes::default_instance()));
2382
2383 Message* proto2_message =
2384 entry_message->GetReflection()->MutableMessage(entry_message, value);
2385 EXPECT_EQ(unittest::TestAllTypes::descriptor(),
2386 proto2_message->GetDescriptor());
2387 ASSERT_EQ(1, message.map_int32_message().size());
2388 }
2389
TEST(GeneratedMapFieldReflectionTest,MergeFromClearMapEntry)2390 TEST(GeneratedMapFieldReflectionTest, MergeFromClearMapEntry) {
2391 unittest::TestMap message;
2392 const FieldDescriptor* map_field =
2393 unittest::TestMap::descriptor()->FindFieldByName("map_int32_int32");
2394 const FieldDescriptor* key =
2395 map_field->message_type()->FindFieldByName("key");
2396 const FieldDescriptor* value =
2397 map_field->message_type()->FindFieldByName("value");
2398
2399 Message* entry_message1 =
2400 message.GetReflection()->AddMessage(&message, map_field);
2401 EXPECT_FALSE(entry_message1->GetReflection()->HasField(*entry_message1, key));
2402 EXPECT_FALSE(
2403 entry_message1->GetReflection()->HasField(*entry_message1, value));
2404
2405 Message* entry_message2 =
2406 message.GetReflection()->AddMessage(&message, map_field);
2407 EXPECT_FALSE(entry_message2->GetReflection()->HasField(*entry_message2, key));
2408 EXPECT_FALSE(
2409 entry_message2->GetReflection()->HasField(*entry_message2, value));
2410
2411 entry_message1->MergeFrom(*entry_message2);
2412 EXPECT_FALSE(entry_message1->GetReflection()->HasField(*entry_message1, key));
2413 EXPECT_FALSE(
2414 entry_message1->GetReflection()->HasField(*entry_message1, value));
2415 }
2416
TEST(GeneratedMapFieldReflectionTest,MapEntryClear)2417 TEST(GeneratedMapFieldReflectionTest, MapEntryClear) {
2418 unittest::TestMap message;
2419 MapReflectionTester reflection_tester(
2420 unittest::TestMap::descriptor());
2421 reflection_tester.MutableUnknownFieldsOfMapFieldsViaReflection(&message);
2422 }
2423
TEST(GeneratedMapFieldReflectionTest,Proto2MapEntryClear)2424 TEST(GeneratedMapFieldReflectionTest, Proto2MapEntryClear) {
2425 unittest::TestEnumMap message;
2426 const Descriptor* descriptor = message.GetDescriptor();
2427 const FieldDescriptor* field_descriptor =
2428 descriptor->FindFieldByName("known_map_field");
2429 const FieldDescriptor* value_descriptor =
2430 field_descriptor->message_type()->FindFieldByName("value");
2431 Message* sub_message =
2432 message.GetReflection()->AddMessage(&message, field_descriptor);
2433 EXPECT_EQ(0, sub_message->GetReflection()->GetEnumValue(*sub_message,
2434 value_descriptor));
2435 }
2436
2437 // Map Reflection API Test =========================================
2438
TEST(GeneratedMapFieldReflectionTest,SetViaMapReflection)2439 TEST(GeneratedMapFieldReflectionTest, SetViaMapReflection) {
2440 unittest::TestMap message;
2441 MapReflectionTester reflection_tester(
2442 unittest::TestMap::descriptor());
2443 reflection_tester.SetMapFieldsViaMapReflection(&message);
2444 reflection_tester.ExpectMapFieldsSetViaReflection(message);
2445 reflection_tester.ExpectMapFieldsSetViaReflectionIterator(&message);
2446 }
2447
2448 // Dynamic Message Test =============================================
2449
2450 class MapFieldInDynamicMessageTest : public testing::Test {
2451 protected:
2452 const DescriptorPool* pool_;
2453 DynamicMessageFactory factory_;
2454 const Descriptor* map_descriptor_;
2455 const Descriptor* recursive_map_descriptor_;
2456 const Message* map_prototype_;
2457
MapFieldInDynamicMessageTest()2458 MapFieldInDynamicMessageTest()
2459 : pool_(DescriptorPool::generated_pool()), factory_(pool_) {}
2460
SetUp()2461 virtual void SetUp() {
2462 map_descriptor_ =
2463 pool_->FindMessageTypeByName("protobuf_unittest.TestMap");
2464 recursive_map_descriptor_ =
2465 pool_->FindMessageTypeByName("protobuf_unittest.TestRecursiveMapMessage");
2466 ASSERT_TRUE(map_descriptor_ != NULL);
2467 ASSERT_TRUE(recursive_map_descriptor_ != NULL);
2468 map_prototype_ = factory_.GetPrototype(map_descriptor_);
2469 }
2470 };
2471
TEST_F(MapFieldInDynamicMessageTest,MapIndependentOffsets)2472 TEST_F(MapFieldInDynamicMessageTest, MapIndependentOffsets) {
2473 // Check that all fields have independent offsets by setting each
2474 // one to a unique value then checking that they all still have those
2475 // unique values (i.e. they don't stomp each other).
2476 google::protobuf::scoped_ptr<Message> message(map_prototype_->New());
2477 MapReflectionTester reflection_tester(map_descriptor_);
2478
2479 reflection_tester.SetMapFieldsViaReflection(message.get());
2480 reflection_tester.ExpectMapFieldsSetViaReflection(*message);
2481 }
2482
TEST_F(MapFieldInDynamicMessageTest,DynamicMapReflection)2483 TEST_F(MapFieldInDynamicMessageTest, DynamicMapReflection) {
2484 // Check that map fields work properly.
2485 google::protobuf::scoped_ptr<Message> message(map_prototype_->New());
2486
2487 // Check set functions.
2488 MapReflectionTester reflection_tester(map_descriptor_);
2489 reflection_tester.SetMapFieldsViaMapReflection(message.get());
2490 reflection_tester.ExpectMapFieldsSetViaReflection(*message);
2491 }
2492
TEST_F(MapFieldInDynamicMessageTest,MapSpaceUsed)2493 TEST_F(MapFieldInDynamicMessageTest, MapSpaceUsed) {
2494 // Test that SpaceUsed() works properly
2495
2496 // Since we share the implementation with generated messages, we don't need
2497 // to test very much here. Just make sure it appears to be working.
2498
2499 google::protobuf::scoped_ptr<Message> message(map_prototype_->New());
2500 MapReflectionTester reflection_tester(map_descriptor_);
2501
2502 int initial_space_used = message->SpaceUsed();
2503
2504 reflection_tester.SetMapFieldsViaReflection(message.get());
2505 EXPECT_LT(initial_space_used, message->SpaceUsed());
2506 }
2507
TEST_F(MapFieldInDynamicMessageTest,RecursiveMap)2508 TEST_F(MapFieldInDynamicMessageTest, RecursiveMap) {
2509 TestRecursiveMapMessage from;
2510 (*from.mutable_a())[""];
2511 string data = from.SerializeAsString();
2512 google::protobuf::scoped_ptr<Message> to(
2513 factory_.GetPrototype(recursive_map_descriptor_)->New());
2514 ASSERT_TRUE(to->ParseFromString(data));
2515 }
2516
2517 // ReflectionOps Test ===============================================
2518
TEST(ReflectionOpsForMapFieldTest,MapSanityCheck)2519 TEST(ReflectionOpsForMapFieldTest, MapSanityCheck) {
2520 unittest::TestMap message;
2521
2522 MapTestUtil::SetMapFields(&message);
2523 MapTestUtil::ExpectMapFieldsSet(message);
2524 }
2525
TEST(ReflectionOpsForMapFieldTest,MapCopy)2526 TEST(ReflectionOpsForMapFieldTest, MapCopy) {
2527 unittest::TestMap message, message2;
2528
2529 MapTestUtil::SetMapFields(&message);
2530
2531 ReflectionOps::Copy(message, &message2);
2532
2533 MapTestUtil::ExpectMapFieldsSet(message2);
2534
2535 // Copying from self should be a no-op.
2536 ReflectionOps::Copy(message2, &message2);
2537 MapTestUtil::ExpectMapFieldsSet(message2);
2538 }
2539
TEST(ReflectionOpsForMapFieldTest,MergeMap)2540 TEST(ReflectionOpsForMapFieldTest, MergeMap) {
2541 // Note: Copy is implemented in terms of Merge() so technically the Copy
2542 // test already tested most of this.
2543
2544 unittest::TestMap message, message2;
2545
2546 MapTestUtil::SetMapFields(&message);
2547
2548 ReflectionOps::Merge(message2, &message);
2549
2550 MapTestUtil::ExpectMapFieldsSet(message);
2551 }
2552
TEST(ReflectionOpsForMapFieldTest,ClearMap)2553 TEST(ReflectionOpsForMapFieldTest, ClearMap) {
2554 unittest::TestMap message;
2555
2556 MapTestUtil::SetMapFields(&message);
2557
2558 ReflectionOps::Clear(&message);
2559
2560 MapTestUtil::ExpectClear(message);
2561 }
2562
TEST(ReflectionOpsForMapFieldTest,MapDiscardUnknownFields)2563 TEST(ReflectionOpsForMapFieldTest, MapDiscardUnknownFields) {
2564 unittest::TestMap message;
2565 MapTestUtil::SetMapFields(&message);
2566
2567 // Set some unknown fields in message.
2568 message.GetReflection()->MutableUnknownFields(&message)->
2569 AddVarint(123456, 654321);
2570
2571 // Discard them.
2572 ReflectionOps::DiscardUnknownFields(&message);
2573 MapTestUtil::ExpectMapFieldsSet(message);
2574
2575 EXPECT_EQ(0, message.GetReflection()->
2576 GetUnknownFields(message).field_count());
2577 }
2578
2579 // Wire Format Test =================================================
2580
TEST(WireFormatForMapFieldTest,ParseMap)2581 TEST(WireFormatForMapFieldTest, ParseMap) {
2582 unittest::TestMap source, dest;
2583 string data;
2584
2585 // Serialize using the generated code.
2586 MapTestUtil::SetMapFields(&source);
2587 source.SerializeToString(&data);
2588
2589 // Parse using WireFormat.
2590 io::ArrayInputStream raw_input(data.data(), data.size());
2591 io::CodedInputStream input(&raw_input);
2592 WireFormat::ParseAndMergePartial(&input, &dest);
2593
2594 // Check.
2595 MapTestUtil::ExpectMapFieldsSet(dest);
2596 }
2597
TEST(WireFormatForMapFieldTest,MapByteSize)2598 TEST(WireFormatForMapFieldTest, MapByteSize) {
2599 unittest::TestMap message;
2600 MapTestUtil::SetMapFields(&message);
2601
2602 EXPECT_EQ(message.ByteSize(), WireFormat::ByteSize(message));
2603 message.Clear();
2604 EXPECT_EQ(0, message.ByteSize());
2605 EXPECT_EQ(0, WireFormat::ByteSize(message));
2606 }
2607
TEST(WireFormatForMapFieldTest,SerializeMap)2608 TEST(WireFormatForMapFieldTest, SerializeMap) {
2609 unittest::TestMap message;
2610 string generated_data;
2611 string dynamic_data;
2612
2613 MapTestUtil::SetMapFields(&message);
2614
2615 // Serialize using the generated code.
2616 {
2617 message.ByteSize();
2618 io::StringOutputStream raw_output(&generated_data);
2619 io::CodedOutputStream output(&raw_output);
2620 message.SerializeWithCachedSizes(&output);
2621 ASSERT_FALSE(output.HadError());
2622 }
2623
2624 // Serialize using WireFormat.
2625 {
2626 io::StringOutputStream raw_output(&dynamic_data);
2627 io::CodedOutputStream output(&raw_output);
2628 int size = WireFormat::ByteSize(message);
2629 WireFormat::SerializeWithCachedSizes(message, size, &output);
2630 ASSERT_FALSE(output.HadError());
2631 }
2632
2633 // Should be the same.
2634 // Don't use EXPECT_EQ here because we're comparing raw binary data and
2635 // we really don't want it dumped to stdout on failure.
2636 EXPECT_TRUE(dynamic_data == generated_data);
2637 }
2638
TEST(WireFormatForMapFieldTest,MapParseHelpers)2639 TEST(WireFormatForMapFieldTest, MapParseHelpers) {
2640 string data;
2641
2642 {
2643 // Set up.
2644 protobuf_unittest::TestMap message;
2645 MapTestUtil::SetMapFields(&message);
2646 message.SerializeToString(&data);
2647 }
2648
2649 {
2650 // Test ParseFromString.
2651 protobuf_unittest::TestMap message;
2652 EXPECT_TRUE(message.ParseFromString(data));
2653 MapTestUtil::ExpectMapFieldsSet(message);
2654 }
2655
2656 {
2657 // Test ParseFromIstream.
2658 protobuf_unittest::TestMap message;
2659 stringstream stream(data);
2660 EXPECT_TRUE(message.ParseFromIstream(&stream));
2661 EXPECT_TRUE(stream.eof());
2662 MapTestUtil::ExpectMapFieldsSet(message);
2663 }
2664
2665 {
2666 // Test ParseFromBoundedZeroCopyStream.
2667 string data_with_junk(data);
2668 data_with_junk.append("some junk on the end");
2669 io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size());
2670 protobuf_unittest::TestMap message;
2671 EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size()));
2672 MapTestUtil::ExpectMapFieldsSet(message);
2673 }
2674
2675 {
2676 // Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if
2677 // EOF is reached before the expected number of bytes.
2678 io::ArrayInputStream stream(data.data(), data.size());
2679 protobuf_unittest::TestAllTypes message;
2680 EXPECT_FALSE(
2681 message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1));
2682 }
2683 }
2684
2685 // Text Format Test =================================================
2686
TEST(TextFormatMapTest,SerializeAndParse)2687 TEST(TextFormatMapTest, SerializeAndParse) {
2688 unittest::TestMap source;
2689 unittest::TestMap dest;
2690 MapTestUtil::SetMapFields(&source);
2691 string output;
2692
2693 // Test compact ASCII
2694 TextFormat::Printer printer;
2695 printer.PrintToString(source, &output);
2696 TextFormat::Parser parser;
2697 EXPECT_TRUE(parser.ParseFromString(output, &dest));
2698 MapTestUtil::ExpectMapFieldsSet(dest);
2699 }
2700
TEST(TextFormatMapTest,Sorted)2701 TEST(TextFormatMapTest, Sorted) {
2702 unittest::TestMap message;
2703 MapReflectionTester tester(message.GetDescriptor());
2704 tester.SetMapFieldsViaReflection(&message);
2705
2706 string expected_text;
2707 GOOGLE_CHECK_OK(File::GetContents(
2708 TestSourceDir() +
2709 "/google/protobuf/"
2710 "testdata/map_test_data.txt",
2711 &expected_text, true));
2712
2713 EXPECT_EQ(message.DebugString(), expected_text);
2714
2715 // Test again on the reverse order.
2716 unittest::TestMap message2;
2717 tester.SetMapFieldsViaReflection(&message2);
2718 tester.SwapMapsViaReflection(&message2);
2719 EXPECT_EQ(message2.DebugString(), expected_text);
2720 }
2721
2722
2723 // arena support =================================================
TEST(ArenaTest,ParsingAndSerializingNoHeapAllocation)2724 TEST(ArenaTest, ParsingAndSerializingNoHeapAllocation) {
2725 // Allocate a large initial block to avoid mallocs during hooked test.
2726 std::vector<char> arena_block(128 * 1024);
2727 ArenaOptions options;
2728 options.initial_block = &arena_block[0];
2729 options.initial_block_size = arena_block.size();
2730 Arena arena(options);
2731 string data;
2732 data.reserve(128 * 1024);
2733
2734 {
2735 // TODO(teboring): Enable no heap check when ArenaStringPtr is used in map.
2736 // NoHeapChecker no_heap;
2737
2738 unittest::TestArenaMap* from =
2739 Arena::CreateMessage<unittest::TestArenaMap>(&arena);
2740 MapTestUtil::SetArenaMapFields(from);
2741 from->SerializeToString(&data);
2742
2743 unittest::TestArenaMap* to =
2744 Arena::CreateMessage<unittest::TestArenaMap>(&arena);
2745 to->ParseFromString(data);
2746 MapTestUtil::ExpectArenaMapFieldsSet(*to);
2747 }
2748 }
2749
2750 // Use text format parsing and serializing to test reflection api.
TEST(ArenaTest,RelfectionInTextFormat)2751 TEST(ArenaTest, RelfectionInTextFormat) {
2752 Arena arena;
2753 string data;
2754
2755 TextFormat::Printer printer;
2756 TextFormat::Parser parser;
2757
2758 unittest::TestArenaMap* from =
2759 Arena::CreateMessage<unittest::TestArenaMap>(&arena);
2760 unittest::TestArenaMap* to =
2761 Arena::CreateMessage<unittest::TestArenaMap>(&arena);
2762
2763 MapTestUtil::SetArenaMapFields(from);
2764 printer.PrintToString(*from, &data);
2765
2766 EXPECT_TRUE(parser.ParseFromString(data, to));
2767 MapTestUtil::ExpectArenaMapFieldsSet(*to);
2768 }
2769
2770 // Make sure the memory allocated for string in map is deallocated.
TEST(ArenaTest,StringMapNoLeak)2771 TEST(ArenaTest, StringMapNoLeak) {
2772 Arena arena;
2773 unittest::TestArenaMap* message =
2774 Arena::CreateMessage<unittest::TestArenaMap>(&arena);
2775 string data;
2776 // String with length less than 16 will not be allocated from heap.
2777 int original_capacity = data.capacity();
2778 while (data.capacity() <= original_capacity) {
2779 data.append("a");
2780 }
2781 (*message->mutable_map_string_string())[data] = data;
2782 // We rely on heap checkers to detect memory leak for us.
2783 ASSERT_FALSE(message == NULL);
2784 }
2785
2786 } // namespace internal
2787 } // namespace protobuf
2788 } // namespace google
2789