map.h 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  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. // This file defines the map container and its helpers to support protobuf maps.
  31. //
  32. // The Map and MapIterator types are provided by this header file.
  33. // Please avoid using other types defined here, unless they are public
  34. // types within Map or MapIterator, such as Map::value_type.
  35. #ifndef GOOGLE_PROTOBUF_MAP_H__
  36. #define GOOGLE_PROTOBUF_MAP_H__
  37. #include <initializer_list>
  38. #include <iterator>
  39. #include <limits> // To support Visual Studio 2008
  40. #include <set>
  41. #include <utility>
  42. #include <google/protobuf/stubs/common.h>
  43. #include <google/protobuf/arena.h>
  44. #include <google/protobuf/generated_enum_util.h>
  45. #include <google/protobuf/map_type_handler.h>
  46. #include <google/protobuf/stubs/hash.h>
  47. namespace google {
  48. namespace protobuf {
  49. template <typename Key, typename T>
  50. class Map;
  51. class MapIterator;
  52. template <typename Enum> struct is_proto_enum;
  53. namespace internal {
  54. template <typename Derived, typename Key, typename T,
  55. WireFormatLite::FieldType key_wire_type,
  56. WireFormatLite::FieldType value_wire_type, int default_enum_value>
  57. class MapFieldLite;
  58. template <typename Derived, typename Key, typename T,
  59. WireFormatLite::FieldType key_wire_type,
  60. WireFormatLite::FieldType value_wire_type, int default_enum_value>
  61. class MapField;
  62. template <typename Key, typename T>
  63. class TypeDefinedMapFieldBase;
  64. class DynamicMapField;
  65. class GeneratedMessageReflection;
  66. } // namespace internal
  67. // This is the class for google::protobuf::Map's internal value_type. Instead of using
  68. // std::pair as value_type, we use this class which provides us more control of
  69. // its process of construction and destruction.
  70. template <typename Key, typename T>
  71. class MapPair {
  72. public:
  73. typedef const Key first_type;
  74. typedef T second_type;
  75. MapPair(const Key& other_first, const T& other_second)
  76. : first(other_first), second(other_second) {}
  77. explicit MapPair(const Key& other_first) : first(other_first), second() {}
  78. MapPair(const MapPair& other)
  79. : first(other.first), second(other.second) {}
  80. ~MapPair() {}
  81. // Implicitly convertible to std::pair of compatible types.
  82. template <typename T1, typename T2>
  83. operator std::pair<T1, T2>() const {
  84. return std::pair<T1, T2>(first, second);
  85. }
  86. const Key first;
  87. T second;
  88. private:
  89. friend class ::google::protobuf::Arena;
  90. friend class Map<Key, T>;
  91. };
  92. // google::protobuf::Map is an associative container type used to store protobuf map
  93. // fields. Each Map instance may or may not use a different hash function, a
  94. // different iteration order, and so on. E.g., please don't examine
  95. // implementation details to decide if the following would work:
  96. // Map<int, int> m0, m1;
  97. // m0[0] = m1[0] = m0[1] = m1[1] = 0;
  98. // assert(m0.begin()->first == m1.begin()->first); // Bug!
  99. //
  100. // Map's interface is similar to std::unordered_map, except that Map is not
  101. // designed to play well with exceptions.
  102. template <typename Key, typename T>
  103. class Map {
  104. public:
  105. typedef Key key_type;
  106. typedef T mapped_type;
  107. typedef MapPair<Key, T> value_type;
  108. typedef value_type* pointer;
  109. typedef const value_type* const_pointer;
  110. typedef value_type& reference;
  111. typedef const value_type& const_reference;
  112. typedef size_t size_type;
  113. typedef hash<Key> hasher;
  114. Map() : arena_(NULL), default_enum_value_(0) { Init(); }
  115. explicit Map(Arena* arena) : arena_(arena), default_enum_value_(0) { Init(); }
  116. Map(const Map& other)
  117. : arena_(NULL), default_enum_value_(other.default_enum_value_) {
  118. Init();
  119. insert(other.begin(), other.end());
  120. }
  121. Map(Map&& other) noexcept : Map() {
  122. if (other.arena_) {
  123. *this = other;
  124. } else {
  125. swap(other);
  126. }
  127. }
  128. Map& operator=(Map&& other) noexcept {
  129. if (this != &other) {
  130. if (arena_ != other.arena_) {
  131. *this = other;
  132. } else {
  133. swap(other);
  134. }
  135. }
  136. return *this;
  137. }
  138. template <class InputIt>
  139. Map(const InputIt& first, const InputIt& last)
  140. : arena_(NULL), default_enum_value_(0) {
  141. Init();
  142. insert(first, last);
  143. }
  144. ~Map() {
  145. clear();
  146. if (arena_ == NULL) {
  147. delete elements_;
  148. }
  149. }
  150. private:
  151. void Init() {
  152. elements_ = Arena::Create<InnerMap>(arena_, 0u, hasher(), Allocator(arena_));
  153. }
  154. // re-implement std::allocator to use arena allocator for memory allocation.
  155. // Used for google::protobuf::Map implementation. Users should not use this class
  156. // directly.
  157. template <typename U>
  158. class MapAllocator {
  159. public:
  160. typedef U value_type;
  161. typedef value_type* pointer;
  162. typedef const value_type* const_pointer;
  163. typedef value_type& reference;
  164. typedef const value_type& const_reference;
  165. typedef size_t size_type;
  166. typedef ptrdiff_t difference_type;
  167. MapAllocator() : arena_(NULL) {}
  168. explicit MapAllocator(Arena* arena) : arena_(arena) {}
  169. template <typename X>
  170. MapAllocator(const MapAllocator<X>& allocator)
  171. : arena_(allocator.arena()) {}
  172. pointer allocate(size_type n, const void* /* hint */ = 0) {
  173. // If arena is not given, malloc needs to be called which doesn't
  174. // construct element object.
  175. if (arena_ == NULL) {
  176. return static_cast<pointer>(::operator new(n * sizeof(value_type)));
  177. } else {
  178. return reinterpret_cast<pointer>(
  179. Arena::CreateArray<uint8>(arena_, n * sizeof(value_type)));
  180. }
  181. }
  182. void deallocate(pointer p, size_type n) {
  183. if (arena_ == NULL) {
  184. #if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
  185. ::operator delete(p, n * sizeof(value_type));
  186. #else
  187. (void)n;
  188. ::operator delete(p);
  189. #endif
  190. }
  191. }
  192. #if __cplusplus >= 201103L && !defined(GOOGLE_PROTOBUF_OS_APPLE) && \
  193. !defined(GOOGLE_PROTOBUF_OS_NACL) && \
  194. !defined(GOOGLE_PROTOBUF_OS_EMSCRIPTEN)
  195. template<class NodeType, class... Args>
  196. void construct(NodeType* p, Args&&... args) {
  197. // Clang 3.6 doesn't compile static casting to void* directly. (Issue
  198. // #1266) According C++ standard 5.2.9/1: "The static_cast operator shall
  199. // not cast away constness". So first the maybe const pointer is casted to
  200. // const void* and after the const void* is const casted.
  201. new (const_cast<void*>(static_cast<const void*>(p)))
  202. NodeType(std::forward<Args>(args)...);
  203. }
  204. template<class NodeType>
  205. void destroy(NodeType* p) {
  206. p->~NodeType();
  207. }
  208. #else
  209. void construct(pointer p, const_reference t) { new (p) value_type(t); }
  210. void destroy(pointer p) { p->~value_type(); }
  211. #endif
  212. template <typename X>
  213. struct rebind {
  214. typedef MapAllocator<X> other;
  215. };
  216. template <typename X>
  217. bool operator==(const MapAllocator<X>& other) const {
  218. return arena_ == other.arena_;
  219. }
  220. template <typename X>
  221. bool operator!=(const MapAllocator<X>& other) const {
  222. return arena_ != other.arena_;
  223. }
  224. // To support Visual Studio 2008
  225. size_type max_size() const {
  226. // parentheses around (std::...:max) prevents macro warning of max()
  227. return (std::numeric_limits<size_type>::max)();
  228. }
  229. // To support gcc-4.4, which does not properly
  230. // support templated friend classes
  231. Arena* arena() const {
  232. return arena_;
  233. }
  234. private:
  235. typedef void DestructorSkippable_;
  236. Arena* const arena_;
  237. };
  238. // InnerMap's key type is Key and its value type is value_type*. We use a
  239. // custom class here and for Node, below, to ensure that k_ is at offset 0,
  240. // allowing safe conversion from pointer to Node to pointer to Key, and vice
  241. // versa when appropriate.
  242. class KeyValuePair {
  243. public:
  244. KeyValuePair(const Key& k, value_type* v) : k_(k), v_(v) {}
  245. const Key& key() const { return k_; }
  246. Key& key() { return k_; }
  247. value_type* value() const { return v_; }
  248. value_type*& value() { return v_; }
  249. private:
  250. Key k_;
  251. value_type* v_;
  252. };
  253. typedef MapAllocator<KeyValuePair> Allocator;
  254. // InnerMap is a generic hash-based map. It doesn't contain any
  255. // protocol-buffer-specific logic. It is a chaining hash map with the
  256. // additional feature that some buckets can be converted to use an ordered
  257. // container. This ensures O(lg n) bounds on find, insert, and erase, while
  258. // avoiding the overheads of ordered containers most of the time.
  259. //
  260. // The implementation doesn't need the full generality of unordered_map,
  261. // and it doesn't have it. More bells and whistles can be added as needed.
  262. // Some implementation details:
  263. // 1. The hash function has type hasher and the equality function
  264. // equal_to<Key>. We inherit from hasher to save space
  265. // (empty-base-class optimization).
  266. // 2. The number of buckets is a power of two.
  267. // 3. Buckets are converted to trees in pairs: if we convert bucket b then
  268. // buckets b and b^1 will share a tree. Invariant: buckets b and b^1 have
  269. // the same non-NULL value iff they are sharing a tree. (An alternative
  270. // implementation strategy would be to have a tag bit per bucket.)
  271. // 4. As is typical for hash_map and such, the Keys and Values are always
  272. // stored in linked list nodes. Pointers to elements are never invalidated
  273. // until the element is deleted.
  274. // 5. The trees' payload type is pointer to linked-list node. Tree-converting
  275. // a bucket doesn't copy Key-Value pairs.
  276. // 6. Once we've tree-converted a bucket, it is never converted back. However,
  277. // the items a tree contains may wind up assigned to trees or lists upon a
  278. // rehash.
  279. // 7. The code requires no C++ features from C++11 or later.
  280. // 8. Mutations to a map do not invalidate the map's iterators, pointers to
  281. // elements, or references to elements.
  282. // 9. Except for erase(iterator), any non-const method can reorder iterators.
  283. class InnerMap : private hasher {
  284. public:
  285. typedef value_type* Value;
  286. InnerMap(size_type n, hasher h, Allocator alloc)
  287. : hasher(h),
  288. num_elements_(0),
  289. seed_(Seed()),
  290. table_(NULL),
  291. alloc_(alloc) {
  292. n = TableSize(n);
  293. table_ = CreateEmptyTable(n);
  294. num_buckets_ = index_of_first_non_null_ = n;
  295. }
  296. ~InnerMap() {
  297. if (table_ != NULL) {
  298. clear();
  299. Dealloc<void*>(table_, num_buckets_);
  300. }
  301. }
  302. private:
  303. enum { kMinTableSize = 8 };
  304. // Linked-list nodes, as one would expect for a chaining hash table.
  305. struct Node {
  306. KeyValuePair kv;
  307. Node* next;
  308. };
  309. // This is safe only if the given pointer is known to point to a Key that is
  310. // part of a Node.
  311. static Node* NodePtrFromKeyPtr(Key* k) {
  312. return reinterpret_cast<Node*>(k);
  313. }
  314. static Key* KeyPtrFromNodePtr(Node* node) { return &node->kv.key(); }
  315. // Trees. The payload type is pointer to Key, so that we can query the tree
  316. // with Keys that are not in any particular data structure. When we insert,
  317. // though, the pointer is always pointing to a Key that is inside a Node.
  318. struct KeyCompare {
  319. bool operator()(const Key* n0, const Key* n1) const { return *n0 < *n1; }
  320. };
  321. typedef typename Allocator::template rebind<Key*>::other KeyPtrAllocator;
  322. typedef std::set<Key*, KeyCompare, KeyPtrAllocator> Tree;
  323. typedef typename Tree::iterator TreeIterator;
  324. // iterator and const_iterator are instantiations of iterator_base.
  325. template <typename KeyValueType>
  326. struct iterator_base {
  327. typedef KeyValueType& reference;
  328. typedef KeyValueType* pointer;
  329. // Invariants:
  330. // node_ is always correct. This is handy because the most common
  331. // operations are operator* and operator-> and they only use node_.
  332. // When node_ is set to a non-NULL value, all the other non-const fields
  333. // are updated to be correct also, but those fields can become stale
  334. // if the underlying map is modified. When those fields are needed they
  335. // are rechecked, and updated if necessary.
  336. iterator_base() : node_(NULL), m_(NULL), bucket_index_(0) {}
  337. explicit iterator_base(const InnerMap* m) : m_(m) {
  338. SearchFrom(m->index_of_first_non_null_);
  339. }
  340. // Any iterator_base can convert to any other. This is overkill, and we
  341. // rely on the enclosing class to use it wisely. The standard "iterator
  342. // can convert to const_iterator" is OK but the reverse direction is not.
  343. template <typename U>
  344. explicit iterator_base(const iterator_base<U>& it)
  345. : node_(it.node_), m_(it.m_), bucket_index_(it.bucket_index_) {}
  346. iterator_base(Node* n, const InnerMap* m, size_type index)
  347. : node_(n), m_(m), bucket_index_(index) {}
  348. iterator_base(TreeIterator tree_it, const InnerMap* m, size_type index)
  349. : node_(NodePtrFromKeyPtr(*tree_it)), m_(m), bucket_index_(index) {
  350. // Invariant: iterators that use buckets with trees have an even
  351. // bucket_index_.
  352. GOOGLE_DCHECK_EQ(bucket_index_ % 2, 0);
  353. }
  354. // Advance through buckets, looking for the first that isn't empty.
  355. // If nothing non-empty is found then leave node_ == NULL.
  356. void SearchFrom(size_type start_bucket) {
  357. GOOGLE_DCHECK(m_->index_of_first_non_null_ == m_->num_buckets_ ||
  358. m_->table_[m_->index_of_first_non_null_] != NULL);
  359. node_ = NULL;
  360. for (bucket_index_ = start_bucket; bucket_index_ < m_->num_buckets_;
  361. bucket_index_++) {
  362. if (m_->TableEntryIsNonEmptyList(bucket_index_)) {
  363. node_ = static_cast<Node*>(m_->table_[bucket_index_]);
  364. break;
  365. } else if (m_->TableEntryIsTree(bucket_index_)) {
  366. Tree* tree = static_cast<Tree*>(m_->table_[bucket_index_]);
  367. GOOGLE_DCHECK(!tree->empty());
  368. node_ = NodePtrFromKeyPtr(*tree->begin());
  369. break;
  370. }
  371. }
  372. }
  373. reference operator*() const { return node_->kv; }
  374. pointer operator->() const { return &(operator*()); }
  375. friend bool operator==(const iterator_base& a, const iterator_base& b) {
  376. return a.node_ == b.node_;
  377. }
  378. friend bool operator!=(const iterator_base& a, const iterator_base& b) {
  379. return a.node_ != b.node_;
  380. }
  381. iterator_base& operator++() {
  382. if (node_->next == NULL) {
  383. TreeIterator tree_it;
  384. const bool is_list = revalidate_if_necessary(&tree_it);
  385. if (is_list) {
  386. SearchFrom(bucket_index_ + 1);
  387. } else {
  388. GOOGLE_DCHECK_EQ(bucket_index_ & 1, 0);
  389. Tree* tree = static_cast<Tree*>(m_->table_[bucket_index_]);
  390. if (++tree_it == tree->end()) {
  391. SearchFrom(bucket_index_ + 2);
  392. } else {
  393. node_ = NodePtrFromKeyPtr(*tree_it);
  394. }
  395. }
  396. } else {
  397. node_ = node_->next;
  398. }
  399. return *this;
  400. }
  401. iterator_base operator++(int /* unused */) {
  402. iterator_base tmp = *this;
  403. ++*this;
  404. return tmp;
  405. }
  406. // Assumes node_ and m_ are correct and non-NULL, but other fields may be
  407. // stale. Fix them as needed. Then return true iff node_ points to a
  408. // Node in a list. If false is returned then *it is modified to be
  409. // a valid iterator for node_.
  410. bool revalidate_if_necessary(TreeIterator* it) {
  411. GOOGLE_DCHECK(node_ != NULL && m_ != NULL);
  412. // Force bucket_index_ to be in range.
  413. bucket_index_ &= (m_->num_buckets_ - 1);
  414. // Common case: the bucket we think is relevant points to node_.
  415. if (m_->table_[bucket_index_] == static_cast<void*>(node_))
  416. return true;
  417. // Less common: the bucket is a linked list with node_ somewhere in it,
  418. // but not at the head.
  419. if (m_->TableEntryIsNonEmptyList(bucket_index_)) {
  420. Node* l = static_cast<Node*>(m_->table_[bucket_index_]);
  421. while ((l = l->next) != NULL) {
  422. if (l == node_) {
  423. return true;
  424. }
  425. }
  426. }
  427. // Well, bucket_index_ still might be correct, but probably
  428. // not. Revalidate just to be sure. This case is rare enough that we
  429. // don't worry about potential optimizations, such as having a custom
  430. // find-like method that compares Node* instead of const Key&.
  431. iterator_base i(m_->find(*KeyPtrFromNodePtr(node_), it));
  432. bucket_index_ = i.bucket_index_;
  433. return m_->TableEntryIsList(bucket_index_);
  434. }
  435. Node* node_;
  436. const InnerMap* m_;
  437. size_type bucket_index_;
  438. };
  439. public:
  440. typedef iterator_base<KeyValuePair> iterator;
  441. typedef iterator_base<const KeyValuePair> const_iterator;
  442. iterator begin() { return iterator(this); }
  443. iterator end() { return iterator(); }
  444. const_iterator begin() const { return const_iterator(this); }
  445. const_iterator end() const { return const_iterator(); }
  446. void clear() {
  447. for (size_type b = 0; b < num_buckets_; b++) {
  448. if (TableEntryIsNonEmptyList(b)) {
  449. Node* node = static_cast<Node*>(table_[b]);
  450. table_[b] = NULL;
  451. do {
  452. Node* next = node->next;
  453. DestroyNode(node);
  454. node = next;
  455. } while (node != NULL);
  456. } else if (TableEntryIsTree(b)) {
  457. Tree* tree = static_cast<Tree*>(table_[b]);
  458. GOOGLE_DCHECK(table_[b] == table_[b + 1] && (b & 1) == 0);
  459. table_[b] = table_[b + 1] = NULL;
  460. typename Tree::iterator tree_it = tree->begin();
  461. do {
  462. Node* node = NodePtrFromKeyPtr(*tree_it);
  463. typename Tree::iterator next = tree_it;
  464. ++next;
  465. tree->erase(tree_it);
  466. DestroyNode(node);
  467. tree_it = next;
  468. } while (tree_it != tree->end());
  469. DestroyTree(tree);
  470. b++;
  471. }
  472. }
  473. num_elements_ = 0;
  474. index_of_first_non_null_ = num_buckets_;
  475. }
  476. const hasher& hash_function() const { return *this; }
  477. static size_type max_size() {
  478. return static_cast<size_type>(1) << (sizeof(void**) >= 8 ? 60 : 28);
  479. }
  480. size_type size() const { return num_elements_; }
  481. bool empty() const { return size() == 0; }
  482. iterator find(const Key& k) { return iterator(FindHelper(k).first); }
  483. const_iterator find(const Key& k) const { return find(k, NULL); }
  484. // In traditional C++ style, this performs "insert if not present."
  485. std::pair<iterator, bool> insert(const KeyValuePair& kv) {
  486. std::pair<const_iterator, size_type> p = FindHelper(kv.key());
  487. // Case 1: key was already present.
  488. if (p.first.node_ != NULL)
  489. return std::make_pair(iterator(p.first), false);
  490. // Case 2: insert.
  491. if (ResizeIfLoadIsOutOfRange(num_elements_ + 1)) {
  492. p = FindHelper(kv.key());
  493. }
  494. const size_type b = p.second; // bucket number
  495. Node* node = Alloc<Node>(1);
  496. alloc_.construct(&node->kv, kv);
  497. iterator result = InsertUnique(b, node);
  498. ++num_elements_;
  499. return std::make_pair(result, true);
  500. }
  501. // The same, but if an insertion is necessary then the value portion of the
  502. // inserted key-value pair is left uninitialized.
  503. std::pair<iterator, bool> insert(const Key& k) {
  504. std::pair<const_iterator, size_type> p = FindHelper(k);
  505. // Case 1: key was already present.
  506. if (p.first.node_ != NULL)
  507. return std::make_pair(iterator(p.first), false);
  508. // Case 2: insert.
  509. if (ResizeIfLoadIsOutOfRange(num_elements_ + 1)) {
  510. p = FindHelper(k);
  511. }
  512. const size_type b = p.second; // bucket number
  513. Node* node = Alloc<Node>(1);
  514. typedef typename Allocator::template rebind<Key>::other KeyAllocator;
  515. KeyAllocator(alloc_).construct(&node->kv.key(), k);
  516. iterator result = InsertUnique(b, node);
  517. ++num_elements_;
  518. return std::make_pair(result, true);
  519. }
  520. Value& operator[](const Key& k) {
  521. KeyValuePair kv(k, Value());
  522. return insert(kv).first->value();
  523. }
  524. void erase(iterator it) {
  525. GOOGLE_DCHECK_EQ(it.m_, this);
  526. typename Tree::iterator tree_it;
  527. const bool is_list = it.revalidate_if_necessary(&tree_it);
  528. size_type b = it.bucket_index_;
  529. Node* const item = it.node_;
  530. if (is_list) {
  531. GOOGLE_DCHECK(TableEntryIsNonEmptyList(b));
  532. Node* head = static_cast<Node*>(table_[b]);
  533. head = EraseFromLinkedList(item, head);
  534. table_[b] = static_cast<void*>(head);
  535. } else {
  536. GOOGLE_DCHECK(TableEntryIsTree(b));
  537. Tree* tree = static_cast<Tree*>(table_[b]);
  538. tree->erase(*tree_it);
  539. if (tree->empty()) {
  540. // Force b to be the minimum of b and b ^ 1. This is important
  541. // only because we want index_of_first_non_null_ to be correct.
  542. b &= ~static_cast<size_type>(1);
  543. DestroyTree(tree);
  544. table_[b] = table_[b + 1] = NULL;
  545. }
  546. }
  547. DestroyNode(item);
  548. --num_elements_;
  549. if (GOOGLE_PREDICT_FALSE(b == index_of_first_non_null_)) {
  550. while (index_of_first_non_null_ < num_buckets_ &&
  551. table_[index_of_first_non_null_] == NULL) {
  552. ++index_of_first_non_null_;
  553. }
  554. }
  555. }
  556. private:
  557. const_iterator find(const Key& k, TreeIterator* it) const {
  558. return FindHelper(k, it).first;
  559. }
  560. std::pair<const_iterator, size_type> FindHelper(const Key& k) const {
  561. return FindHelper(k, NULL);
  562. }
  563. std::pair<const_iterator, size_type> FindHelper(const Key& k,
  564. TreeIterator* it) const {
  565. size_type b = BucketNumber(k);
  566. if (TableEntryIsNonEmptyList(b)) {
  567. Node* node = static_cast<Node*>(table_[b]);
  568. do {
  569. if (IsMatch(*KeyPtrFromNodePtr(node), k)) {
  570. return std::make_pair(const_iterator(node, this, b), b);
  571. } else {
  572. node = node->next;
  573. }
  574. } while (node != NULL);
  575. } else if (TableEntryIsTree(b)) {
  576. GOOGLE_DCHECK_EQ(table_[b], table_[b ^ 1]);
  577. b &= ~static_cast<size_t>(1);
  578. Tree* tree = static_cast<Tree*>(table_[b]);
  579. Key* key = const_cast<Key*>(&k);
  580. typename Tree::iterator tree_it = tree->find(key);
  581. if (tree_it != tree->end()) {
  582. if (it != NULL) *it = tree_it;
  583. return std::make_pair(const_iterator(tree_it, this, b), b);
  584. }
  585. }
  586. return std::make_pair(end(), b);
  587. }
  588. // Insert the given Node in bucket b. If that would make bucket b too big,
  589. // and bucket b is not a tree, create a tree for buckets b and b^1 to share.
  590. // Requires count(*KeyPtrFromNodePtr(node)) == 0 and that b is the correct
  591. // bucket. num_elements_ is not modified.
  592. iterator InsertUnique(size_type b, Node* node) {
  593. GOOGLE_DCHECK(index_of_first_non_null_ == num_buckets_ ||
  594. table_[index_of_first_non_null_] != NULL);
  595. // In practice, the code that led to this point may have already
  596. // determined whether we are inserting into an empty list, a short list,
  597. // or whatever. But it's probably cheap enough to recompute that here;
  598. // it's likely that we're inserting into an empty or short list.
  599. iterator result;
  600. GOOGLE_DCHECK(find(*KeyPtrFromNodePtr(node)) == end());
  601. if (TableEntryIsEmpty(b)) {
  602. result = InsertUniqueInList(b, node);
  603. } else if (TableEntryIsNonEmptyList(b)) {
  604. if (GOOGLE_PREDICT_FALSE(TableEntryIsTooLong(b))) {
  605. TreeConvert(b);
  606. result = InsertUniqueInTree(b, node);
  607. GOOGLE_DCHECK_EQ(result.bucket_index_, b & ~static_cast<size_type>(1));
  608. } else {
  609. // Insert into a pre-existing list. This case cannot modify
  610. // index_of_first_non_null_, so we skip the code to update it.
  611. return InsertUniqueInList(b, node);
  612. }
  613. } else {
  614. // Insert into a pre-existing tree. This case cannot modify
  615. // index_of_first_non_null_, so we skip the code to update it.
  616. return InsertUniqueInTree(b, node);
  617. }
  618. // parentheses around (std::min) prevents macro expansion of min(...)
  619. index_of_first_non_null_ =
  620. (std::min)(index_of_first_non_null_, result.bucket_index_);
  621. return result;
  622. }
  623. // Helper for InsertUnique. Handles the case where bucket b is a
  624. // not-too-long linked list.
  625. iterator InsertUniqueInList(size_type b, Node* node) {
  626. node->next = static_cast<Node*>(table_[b]);
  627. table_[b] = static_cast<void*>(node);
  628. return iterator(node, this, b);
  629. }
  630. // Helper for InsertUnique. Handles the case where bucket b points to a
  631. // Tree.
  632. iterator InsertUniqueInTree(size_type b, Node* node) {
  633. GOOGLE_DCHECK_EQ(table_[b], table_[b ^ 1]);
  634. // Maintain the invariant that node->next is NULL for all Nodes in Trees.
  635. node->next = NULL;
  636. return iterator(static_cast<Tree*>(table_[b])
  637. ->insert(KeyPtrFromNodePtr(node))
  638. .first,
  639. this, b & ~static_cast<size_t>(1));
  640. }
  641. // Returns whether it did resize. Currently this is only used when
  642. // num_elements_ increases, though it could be used in other situations.
  643. // It checks for load too low as well as load too high: because any number
  644. // of erases can occur between inserts, the load could be as low as 0 here.
  645. // Resizing to a lower size is not always helpful, but failing to do so can
  646. // destroy the expected big-O bounds for some operations. By having the
  647. // policy that sometimes we resize down as well as up, clients can easily
  648. // keep O(size()) = O(number of buckets) if they want that.
  649. bool ResizeIfLoadIsOutOfRange(size_type new_size) {
  650. const size_type kMaxMapLoadTimes16 = 12; // controls RAM vs CPU tradeoff
  651. const size_type hi_cutoff = num_buckets_ * kMaxMapLoadTimes16 / 16;
  652. const size_type lo_cutoff = hi_cutoff / 4;
  653. // We don't care how many elements are in trees. If a lot are,
  654. // we may resize even though there are many empty buckets. In
  655. // practice, this seems fine.
  656. if (GOOGLE_PREDICT_FALSE(new_size >= hi_cutoff)) {
  657. if (num_buckets_ <= max_size() / 2) {
  658. Resize(num_buckets_ * 2);
  659. return true;
  660. }
  661. } else if (GOOGLE_PREDICT_FALSE(new_size <= lo_cutoff &&
  662. num_buckets_ > kMinTableSize)) {
  663. size_type lg2_of_size_reduction_factor = 1;
  664. // It's possible we want to shrink a lot here... size() could even be 0.
  665. // So, estimate how much to shrink by making sure we don't shrink so
  666. // much that we would need to grow the table after a few inserts.
  667. const size_type hypothetical_size = new_size * 5 / 4 + 1;
  668. while ((hypothetical_size << lg2_of_size_reduction_factor) <
  669. hi_cutoff) {
  670. ++lg2_of_size_reduction_factor;
  671. }
  672. size_type new_num_buckets = std::max<size_type>(
  673. kMinTableSize, num_buckets_ >> lg2_of_size_reduction_factor);
  674. if (new_num_buckets != num_buckets_) {
  675. Resize(new_num_buckets);
  676. return true;
  677. }
  678. }
  679. return false;
  680. }
  681. // Resize to the given number of buckets.
  682. void Resize(size_t new_num_buckets) {
  683. GOOGLE_DCHECK_GE(new_num_buckets, kMinTableSize);
  684. void** const old_table = table_;
  685. const size_type old_table_size = num_buckets_;
  686. num_buckets_ = new_num_buckets;
  687. table_ = CreateEmptyTable(num_buckets_);
  688. const size_type start = index_of_first_non_null_;
  689. index_of_first_non_null_ = num_buckets_;
  690. for (size_type i = start; i < old_table_size; i++) {
  691. if (TableEntryIsNonEmptyList(old_table, i)) {
  692. TransferList(old_table, i);
  693. } else if (TableEntryIsTree(old_table, i)) {
  694. TransferTree(old_table, i++);
  695. }
  696. }
  697. Dealloc<void*>(old_table, old_table_size);
  698. }
  699. void TransferList(void* const* table, size_type index) {
  700. Node* node = static_cast<Node*>(table[index]);
  701. do {
  702. Node* next = node->next;
  703. InsertUnique(BucketNumber(*KeyPtrFromNodePtr(node)), node);
  704. node = next;
  705. } while (node != NULL);
  706. }
  707. void TransferTree(void* const* table, size_type index) {
  708. Tree* tree = static_cast<Tree*>(table[index]);
  709. typename Tree::iterator tree_it = tree->begin();
  710. do {
  711. Node* node = NodePtrFromKeyPtr(*tree_it);
  712. InsertUnique(BucketNumber(**tree_it), node);
  713. } while (++tree_it != tree->end());
  714. DestroyTree(tree);
  715. }
  716. Node* EraseFromLinkedList(Node* item, Node* head) {
  717. if (head == item) {
  718. return head->next;
  719. } else {
  720. head->next = EraseFromLinkedList(item, head->next);
  721. return head;
  722. }
  723. }
  724. bool TableEntryIsEmpty(size_type b) const {
  725. return TableEntryIsEmpty(table_, b);
  726. }
  727. bool TableEntryIsNonEmptyList(size_type b) const {
  728. return TableEntryIsNonEmptyList(table_, b);
  729. }
  730. bool TableEntryIsTree(size_type b) const {
  731. return TableEntryIsTree(table_, b);
  732. }
  733. bool TableEntryIsList(size_type b) const {
  734. return TableEntryIsList(table_, b);
  735. }
  736. static bool TableEntryIsEmpty(void* const* table, size_type b) {
  737. return table[b] == NULL;
  738. }
  739. static bool TableEntryIsNonEmptyList(void* const* table, size_type b) {
  740. return table[b] != NULL && table[b] != table[b ^ 1];
  741. }
  742. static bool TableEntryIsTree(void* const* table, size_type b) {
  743. return !TableEntryIsEmpty(table, b) &&
  744. !TableEntryIsNonEmptyList(table, b);
  745. }
  746. static bool TableEntryIsList(void* const* table, size_type b) {
  747. return !TableEntryIsTree(table, b);
  748. }
  749. void TreeConvert(size_type b) {
  750. GOOGLE_DCHECK(!TableEntryIsTree(b) && !TableEntryIsTree(b ^ 1));
  751. typename Allocator::template rebind<Tree>::other tree_allocator(alloc_);
  752. Tree* tree = tree_allocator.allocate(1);
  753. // We want to use the three-arg form of construct, if it exists, but we
  754. // create a temporary and use the two-arg construct that's known to exist.
  755. // It's clunky, but the compiler should be able to generate more-or-less
  756. // the same code.
  757. tree_allocator.construct(tree,
  758. Tree(KeyCompare(), KeyPtrAllocator(alloc_)));
  759. // Now the tree is ready to use.
  760. size_type count = CopyListToTree(b, tree) + CopyListToTree(b ^ 1, tree);
  761. GOOGLE_DCHECK_EQ(count, tree->size());
  762. table_[b] = table_[b ^ 1] = static_cast<void*>(tree);
  763. }
  764. // Copy a linked list in the given bucket to a tree.
  765. // Returns the number of things it copied.
  766. size_type CopyListToTree(size_type b, Tree* tree) {
  767. size_type count = 0;
  768. Node* node = static_cast<Node*>(table_[b]);
  769. while (node != NULL) {
  770. tree->insert(KeyPtrFromNodePtr(node));
  771. ++count;
  772. Node* next = node->next;
  773. node->next = NULL;
  774. node = next;
  775. }
  776. return count;
  777. }
  778. // Return whether table_[b] is a linked list that seems awfully long.
  779. // Requires table_[b] to point to a non-empty linked list.
  780. bool TableEntryIsTooLong(size_type b) {
  781. const size_type kMaxLength = 8;
  782. size_type count = 0;
  783. Node* node = static_cast<Node*>(table_[b]);
  784. do {
  785. ++count;
  786. node = node->next;
  787. } while (node != NULL);
  788. // Invariant: no linked list ever is more than kMaxLength in length.
  789. GOOGLE_DCHECK_LE(count, kMaxLength);
  790. return count >= kMaxLength;
  791. }
  792. size_type BucketNumber(const Key& k) const {
  793. // We inherit from hasher, so one-arg operator() provides a hash function.
  794. size_type h = (*const_cast<InnerMap*>(this))(k);
  795. return (h + seed_) & (num_buckets_ - 1);
  796. }
  797. bool IsMatch(const Key& k0, const Key& k1) const {
  798. return std::equal_to<Key>()(k0, k1);
  799. }
  800. // Return a power of two no less than max(kMinTableSize, n).
  801. // Assumes either n < kMinTableSize or n is a power of two.
  802. size_type TableSize(size_type n) {
  803. return n < static_cast<size_type>(kMinTableSize)
  804. ? static_cast<size_type>(kMinTableSize)
  805. : n;
  806. }
  807. // Use alloc_ to allocate an array of n objects of type U.
  808. template <typename U>
  809. U* Alloc(size_type n) {
  810. typedef typename Allocator::template rebind<U>::other alloc_type;
  811. return alloc_type(alloc_).allocate(n);
  812. }
  813. // Use alloc_ to deallocate an array of n objects of type U.
  814. template <typename U>
  815. void Dealloc(U* t, size_type n) {
  816. typedef typename Allocator::template rebind<U>::other alloc_type;
  817. alloc_type(alloc_).deallocate(t, n);
  818. }
  819. void DestroyNode(Node* node) {
  820. alloc_.destroy(&node->kv);
  821. Dealloc<Node>(node, 1);
  822. }
  823. void DestroyTree(Tree* tree) {
  824. typename Allocator::template rebind<Tree>::other tree_allocator(alloc_);
  825. tree_allocator.destroy(tree);
  826. tree_allocator.deallocate(tree, 1);
  827. }
  828. void** CreateEmptyTable(size_type n) {
  829. GOOGLE_DCHECK(n >= kMinTableSize);
  830. GOOGLE_DCHECK_EQ(n & (n - 1), 0);
  831. void** result = Alloc<void*>(n);
  832. memset(result, 0, n * sizeof(result[0]));
  833. return result;
  834. }
  835. // Return a randomish value.
  836. size_type Seed() const {
  837. size_type s = static_cast<size_type>(reinterpret_cast<uintptr_t>(this));
  838. #if defined(__x86_64__) && defined(__GNUC__)
  839. uint32 hi, lo;
  840. asm("rdtsc" : "=a" (lo), "=d" (hi));
  841. s += ((static_cast<uint64>(hi) << 32) | lo);
  842. #endif
  843. return s;
  844. }
  845. size_type num_elements_;
  846. size_type num_buckets_;
  847. size_type seed_;
  848. size_type index_of_first_non_null_;
  849. void** table_; // an array with num_buckets_ entries
  850. Allocator alloc_;
  851. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(InnerMap);
  852. }; // end of class InnerMap
  853. public:
  854. // Iterators
  855. class const_iterator {
  856. typedef typename InnerMap::const_iterator InnerIt;
  857. public:
  858. typedef std::forward_iterator_tag iterator_category;
  859. typedef typename Map::value_type value_type;
  860. typedef ptrdiff_t difference_type;
  861. typedef const value_type* pointer;
  862. typedef const value_type& reference;
  863. const_iterator() {}
  864. explicit const_iterator(const InnerIt& it) : it_(it) {}
  865. const_reference operator*() const {
  866. return *it_->value();
  867. }
  868. const_pointer operator->() const { return &(operator*()); }
  869. const_iterator& operator++() {
  870. ++it_;
  871. return *this;
  872. }
  873. const_iterator operator++(int) { return const_iterator(it_++); }
  874. friend bool operator==(const const_iterator& a, const const_iterator& b) {
  875. return a.it_ == b.it_;
  876. }
  877. friend bool operator!=(const const_iterator& a, const const_iterator& b) {
  878. return !(a == b);
  879. }
  880. private:
  881. InnerIt it_;
  882. };
  883. class iterator {
  884. typedef typename InnerMap::iterator InnerIt;
  885. public:
  886. typedef std::forward_iterator_tag iterator_category;
  887. typedef typename Map::value_type value_type;
  888. typedef ptrdiff_t difference_type;
  889. typedef value_type* pointer;
  890. typedef value_type& reference;
  891. iterator() {}
  892. explicit iterator(const InnerIt& it) : it_(it) {}
  893. reference operator*() const { return *it_->value(); }
  894. pointer operator->() const { return &(operator*()); }
  895. iterator& operator++() {
  896. ++it_;
  897. return *this;
  898. }
  899. iterator operator++(int) { return iterator(it_++); }
  900. // Allow implicit conversion to const_iterator.
  901. operator const_iterator() const {
  902. return const_iterator(typename InnerMap::const_iterator(it_));
  903. }
  904. friend bool operator==(const iterator& a, const iterator& b) {
  905. return a.it_ == b.it_;
  906. }
  907. friend bool operator!=(const iterator& a, const iterator& b) {
  908. return !(a == b);
  909. }
  910. private:
  911. friend class Map;
  912. InnerIt it_;
  913. };
  914. iterator begin() { return iterator(elements_->begin()); }
  915. iterator end() { return iterator(elements_->end()); }
  916. const_iterator begin() const {
  917. return const_iterator(iterator(elements_->begin()));
  918. }
  919. const_iterator end() const {
  920. return const_iterator(iterator(elements_->end()));
  921. }
  922. const_iterator cbegin() const { return begin(); }
  923. const_iterator cend() const { return end(); }
  924. // Capacity
  925. size_type size() const { return elements_->size(); }
  926. bool empty() const { return size() == 0; }
  927. // Element access
  928. T& operator[](const key_type& key) {
  929. value_type** value = &(*elements_)[key];
  930. if (*value == NULL) {
  931. *value = CreateValueTypeInternal(key);
  932. internal::MapValueInitializer<google::protobuf::is_proto_enum<T>::value,
  933. T>::Initialize((*value)->second,
  934. default_enum_value_);
  935. }
  936. return (*value)->second;
  937. }
  938. const T& at(const key_type& key) const {
  939. const_iterator it = find(key);
  940. GOOGLE_CHECK(it != end()) << "key not found: " << key;
  941. return it->second;
  942. }
  943. T& at(const key_type& key) {
  944. iterator it = find(key);
  945. GOOGLE_CHECK(it != end()) << "key not found: " << key;
  946. return it->second;
  947. }
  948. // Lookup
  949. size_type count(const key_type& key) const {
  950. const_iterator it = find(key);
  951. GOOGLE_DCHECK(it == end() || key == it->first);
  952. return it == end() ? 0 : 1;
  953. }
  954. const_iterator find(const key_type& key) const {
  955. return const_iterator(iterator(elements_->find(key)));
  956. }
  957. iterator find(const key_type& key) { return iterator(elements_->find(key)); }
  958. std::pair<const_iterator, const_iterator> equal_range(
  959. const key_type& key) const {
  960. const_iterator it = find(key);
  961. if (it == end()) {
  962. return std::pair<const_iterator, const_iterator>(it, it);
  963. } else {
  964. const_iterator begin = it++;
  965. return std::pair<const_iterator, const_iterator>(begin, it);
  966. }
  967. }
  968. std::pair<iterator, iterator> equal_range(const key_type& key) {
  969. iterator it = find(key);
  970. if (it == end()) {
  971. return std::pair<iterator, iterator>(it, it);
  972. } else {
  973. iterator begin = it++;
  974. return std::pair<iterator, iterator>(begin, it);
  975. }
  976. }
  977. // insert
  978. std::pair<iterator, bool> insert(const value_type& value) {
  979. std::pair<typename InnerMap::iterator, bool> p =
  980. elements_->insert(value.first);
  981. if (p.second) {
  982. p.first->value() = CreateValueTypeInternal(value);
  983. }
  984. return std::pair<iterator, bool>(iterator(p.first), p.second);
  985. }
  986. template <class InputIt>
  987. void insert(InputIt first, InputIt last) {
  988. for (InputIt it = first; it != last; ++it) {
  989. iterator exist_it = find(it->first);
  990. if (exist_it == end()) {
  991. operator[](it->first) = it->second;
  992. }
  993. }
  994. }
  995. void insert(std::initializer_list<value_type> values) {
  996. insert(values.begin(), values.end());
  997. }
  998. // Erase and clear
  999. size_type erase(const key_type& key) {
  1000. iterator it = find(key);
  1001. if (it == end()) {
  1002. return 0;
  1003. } else {
  1004. erase(it);
  1005. return 1;
  1006. }
  1007. }
  1008. iterator erase(iterator pos) {
  1009. if (arena_ == NULL) delete pos.operator->();
  1010. iterator i = pos++;
  1011. elements_->erase(i.it_);
  1012. return pos;
  1013. }
  1014. void erase(iterator first, iterator last) {
  1015. while (first != last) {
  1016. first = erase(first);
  1017. }
  1018. }
  1019. void clear() { erase(begin(), end()); }
  1020. // Assign
  1021. Map& operator=(const Map& other) {
  1022. if (this != &other) {
  1023. clear();
  1024. insert(other.begin(), other.end());
  1025. }
  1026. return *this;
  1027. }
  1028. void swap(Map& other) {
  1029. if (arena_ == other.arena_) {
  1030. std::swap(default_enum_value_, other.default_enum_value_);
  1031. std::swap(elements_, other.elements_);
  1032. } else {
  1033. // TODO(zuguang): optimize this. The temporary copy can be allocated
  1034. // in the same arena as the other message, and the "other = copy" can
  1035. // be replaced with the fast-path swap above.
  1036. Map copy = *this;
  1037. *this = other;
  1038. other = copy;
  1039. }
  1040. }
  1041. // Access to hasher. Currently this returns a copy, but it may
  1042. // be modified to return a const reference in the future.
  1043. hasher hash_function() const { return elements_->hash_function(); }
  1044. private:
  1045. // Set default enum value only for proto2 map field whose value is enum type.
  1046. void SetDefaultEnumValue(int default_enum_value) {
  1047. default_enum_value_ = default_enum_value;
  1048. }
  1049. value_type* CreateValueTypeInternal(const Key& key) {
  1050. if (arena_ == NULL) {
  1051. return new value_type(key);
  1052. } else {
  1053. value_type* value = reinterpret_cast<value_type*>(
  1054. Arena::CreateArray<uint8>(arena_, sizeof(value_type)));
  1055. Arena::CreateInArenaStorage(const_cast<Key*>(&value->first), arena_);
  1056. Arena::CreateInArenaStorage(&value->second, arena_);
  1057. const_cast<Key&>(value->first) = key;
  1058. return value;
  1059. }
  1060. }
  1061. value_type* CreateValueTypeInternal(const value_type& value) {
  1062. if (arena_ == NULL) {
  1063. return new value_type(value);
  1064. } else {
  1065. value_type* p = reinterpret_cast<value_type*>(
  1066. Arena::CreateArray<uint8>(arena_, sizeof(value_type)));
  1067. Arena::CreateInArenaStorage(const_cast<Key*>(&p->first), arena_);
  1068. Arena::CreateInArenaStorage(&p->second, arena_);
  1069. const_cast<Key&>(p->first) = value.first;
  1070. p->second = value.second;
  1071. return p;
  1072. }
  1073. }
  1074. Arena* arena_;
  1075. int default_enum_value_;
  1076. InnerMap* elements_;
  1077. friend class ::google::protobuf::Arena;
  1078. typedef void InternalArenaConstructable_;
  1079. typedef void DestructorSkippable_;
  1080. template <typename Derived, typename K, typename V,
  1081. internal::WireFormatLite::FieldType key_wire_type,
  1082. internal::WireFormatLite::FieldType value_wire_type,
  1083. int default_enum_value>
  1084. friend class internal::MapFieldLite;
  1085. };
  1086. } // namespace protobuf
  1087. } // namespace google
  1088. #endif // GOOGLE_PROTOBUF_MAP_H__