诸暨麻将添加redis
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

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