map.h 44 KB

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