map.h 47 KB

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