诸暨麻将添加redis
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

3459 satır
127 KiB

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