map.h 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  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>(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. Node* node;
  609. // If K is not key_type, make the conversion to key_type explicit.
  610. using TypeToInit = typename std::conditional<
  611. std::is_same<typename std::decay<K>::type, key_type>::value, K&&,
  612. key_type>::type;
  613. if (alloc_.arena() == nullptr) {
  614. node = new Node{value_type(static_cast<TypeToInit>(std::forward<K>(k))),
  615. nullptr};
  616. } else {
  617. node = Alloc<Node>(1);
  618. Arena::CreateInArenaStorage(
  619. const_cast<Key*>(&node->kv.first), alloc_.arena(),
  620. static_cast<TypeToInit>(std::forward<K>(k)));
  621. Arena::CreateInArenaStorage(&node->kv.second, alloc_.arena());
  622. }
  623. iterator result = InsertUnique(b, node);
  624. ++num_elements_;
  625. return std::make_pair(result, true);
  626. }
  627. template <typename K>
  628. value_type& operator[](K&& k) {
  629. return *insert(std::forward<K>(k)).first;
  630. }
  631. void erase(iterator it) {
  632. GOOGLE_DCHECK_EQ(it.m_, this);
  633. typename Tree::iterator tree_it;
  634. const bool is_list = it.revalidate_if_necessary(&tree_it);
  635. size_type b = it.bucket_index_;
  636. Node* const item = it.node_;
  637. if (is_list) {
  638. GOOGLE_DCHECK(TableEntryIsNonEmptyList(b));
  639. Node* head = static_cast<Node*>(table_[b]);
  640. head = EraseFromLinkedList(item, head);
  641. table_[b] = static_cast<void*>(head);
  642. } else {
  643. GOOGLE_DCHECK(TableEntryIsTree(b));
  644. Tree* tree = static_cast<Tree*>(table_[b]);
  645. tree->erase(tree_it);
  646. if (tree->empty()) {
  647. // Force b to be the minimum of b and b ^ 1. This is important
  648. // only because we want index_of_first_non_null_ to be correct.
  649. b &= ~static_cast<size_type>(1);
  650. DestroyTree(tree);
  651. table_[b] = table_[b + 1] = nullptr;
  652. }
  653. }
  654. DestroyNode(item);
  655. --num_elements_;
  656. if (PROTOBUF_PREDICT_FALSE(b == index_of_first_non_null_)) {
  657. while (index_of_first_non_null_ < num_buckets_ &&
  658. table_[index_of_first_non_null_] == nullptr) {
  659. ++index_of_first_non_null_;
  660. }
  661. }
  662. }
  663. size_t SpaceUsedInternal() const {
  664. return internal::SpaceUsedInTable<Key>(table_, num_buckets_,
  665. num_elements_, sizeof(Node));
  666. }
  667. private:
  668. const_iterator find(const Key& k, TreeIterator* it) const {
  669. return FindHelper(k, it).first;
  670. }
  671. template <typename K>
  672. std::pair<const_iterator, size_type> FindHelper(const K& k) const {
  673. return FindHelper(k, nullptr);
  674. }
  675. template <typename K>
  676. std::pair<const_iterator, size_type> FindHelper(const K& k,
  677. TreeIterator* it) const {
  678. size_type b = BucketNumber(k);
  679. if (TableEntryIsNonEmptyList(b)) {
  680. Node* node = static_cast<Node*>(table_[b]);
  681. do {
  682. if (internal::TransparentSupport<Key>::Equals(node->kv.first, k)) {
  683. return std::make_pair(const_iterator(node, this, b), b);
  684. } else {
  685. node = node->next;
  686. }
  687. } while (node != nullptr);
  688. } else if (TableEntryIsTree(b)) {
  689. GOOGLE_DCHECK_EQ(table_[b], table_[b ^ 1]);
  690. b &= ~static_cast<size_t>(1);
  691. Tree* tree = static_cast<Tree*>(table_[b]);
  692. auto tree_it = tree->find(k);
  693. if (tree_it != tree->end()) {
  694. if (it != nullptr) *it = tree_it;
  695. return std::make_pair(const_iterator(tree_it, this, b), b);
  696. }
  697. }
  698. return std::make_pair(end(), b);
  699. }
  700. // Insert the given Node in bucket b. If that would make bucket b too big,
  701. // and bucket b is not a tree, create a tree for buckets b and b^1 to share.
  702. // Requires count(*KeyPtrFromNodePtr(node)) == 0 and that b is the correct
  703. // bucket. num_elements_ is not modified.
  704. iterator InsertUnique(size_type b, Node* node) {
  705. GOOGLE_DCHECK(index_of_first_non_null_ == num_buckets_ ||
  706. table_[index_of_first_non_null_] != nullptr);
  707. // In practice, the code that led to this point may have already
  708. // determined whether we are inserting into an empty list, a short list,
  709. // or whatever. But it's probably cheap enough to recompute that here;
  710. // it's likely that we're inserting into an empty or short list.
  711. iterator result;
  712. GOOGLE_DCHECK(find(node->kv.first) == end());
  713. if (TableEntryIsEmpty(b)) {
  714. result = InsertUniqueInList(b, node);
  715. } else if (TableEntryIsNonEmptyList(b)) {
  716. if (PROTOBUF_PREDICT_FALSE(TableEntryIsTooLong(b))) {
  717. TreeConvert(b);
  718. result = InsertUniqueInTree(b, node);
  719. GOOGLE_DCHECK_EQ(result.bucket_index_, b & ~static_cast<size_type>(1));
  720. } else {
  721. // Insert into a pre-existing list. This case cannot modify
  722. // index_of_first_non_null_, so we skip the code to update it.
  723. return InsertUniqueInList(b, node);
  724. }
  725. } else {
  726. // Insert into a pre-existing tree. This case cannot modify
  727. // index_of_first_non_null_, so we skip the code to update it.
  728. return InsertUniqueInTree(b, node);
  729. }
  730. // parentheses around (std::min) prevents macro expansion of min(...)
  731. index_of_first_non_null_ =
  732. (std::min)(index_of_first_non_null_, result.bucket_index_);
  733. return result;
  734. }
  735. // Returns whether we should insert after the head of the list. For
  736. // non-optimized builds, we randomly decide whether to insert right at the
  737. // head of the list or just after the head. This helps add a little bit of
  738. // non-determinism to the map ordering.
  739. bool ShouldInsertAfterHead(void* node) {
  740. #ifdef NDEBUG
  741. (void)node;
  742. return false;
  743. #else
  744. // Doing modulo with a prime mixes the bits more.
  745. return (reinterpret_cast<uintptr_t>(node) ^ seed_) % 13 > 6;
  746. #endif
  747. }
  748. // Helper for InsertUnique. Handles the case where bucket b is a
  749. // not-too-long linked list.
  750. iterator InsertUniqueInList(size_type b, Node* node) {
  751. if (table_[b] != nullptr && ShouldInsertAfterHead(node)) {
  752. Node* first = static_cast<Node*>(table_[b]);
  753. node->next = first->next;
  754. first->next = node;
  755. return iterator(node, this, b);
  756. }
  757. node->next = static_cast<Node*>(table_[b]);
  758. table_[b] = static_cast<void*>(node);
  759. return iterator(node, this, b);
  760. }
  761. // Helper for InsertUnique. Handles the case where bucket b points to a
  762. // Tree.
  763. iterator InsertUniqueInTree(size_type b, Node* node) {
  764. GOOGLE_DCHECK_EQ(table_[b], table_[b ^ 1]);
  765. // Maintain the invariant that node->next is null for all Nodes in Trees.
  766. node->next = nullptr;
  767. return iterator(
  768. static_cast<Tree*>(table_[b])->insert({node->kv.first, node}).first,
  769. this, b & ~static_cast<size_t>(1));
  770. }
  771. // Returns whether it did resize. Currently this is only used when
  772. // num_elements_ increases, though it could be used in other situations.
  773. // It checks for load too low as well as load too high: because any number
  774. // of erases can occur between inserts, the load could be as low as 0 here.
  775. // Resizing to a lower size is not always helpful, but failing to do so can
  776. // destroy the expected big-O bounds for some operations. By having the
  777. // policy that sometimes we resize down as well as up, clients can easily
  778. // keep O(size()) = O(number of buckets) if they want that.
  779. bool ResizeIfLoadIsOutOfRange(size_type new_size) {
  780. const size_type kMaxMapLoadTimes16 = 12; // controls RAM vs CPU tradeoff
  781. const size_type hi_cutoff = num_buckets_ * kMaxMapLoadTimes16 / 16;
  782. const size_type lo_cutoff = hi_cutoff / 4;
  783. // We don't care how many elements are in trees. If a lot are,
  784. // we may resize even though there are many empty buckets. In
  785. // practice, this seems fine.
  786. if (PROTOBUF_PREDICT_FALSE(new_size >= hi_cutoff)) {
  787. if (num_buckets_ <= max_size() / 2) {
  788. Resize(num_buckets_ * 2);
  789. return true;
  790. }
  791. } else if (PROTOBUF_PREDICT_FALSE(new_size <= lo_cutoff &&
  792. num_buckets_ > kMinTableSize)) {
  793. size_type lg2_of_size_reduction_factor = 1;
  794. // It's possible we want to shrink a lot here... size() could even be 0.
  795. // So, estimate how much to shrink by making sure we don't shrink so
  796. // much that we would need to grow the table after a few inserts.
  797. const size_type hypothetical_size = new_size * 5 / 4 + 1;
  798. while ((hypothetical_size << lg2_of_size_reduction_factor) <
  799. hi_cutoff) {
  800. ++lg2_of_size_reduction_factor;
  801. }
  802. size_type new_num_buckets = std::max<size_type>(
  803. kMinTableSize, num_buckets_ >> lg2_of_size_reduction_factor);
  804. if (new_num_buckets != num_buckets_) {
  805. Resize(new_num_buckets);
  806. return true;
  807. }
  808. }
  809. return false;
  810. }
  811. // Resize to the given number of buckets.
  812. void Resize(size_t new_num_buckets) {
  813. if (num_buckets_ == internal::kGlobalEmptyTableSize) {
  814. // This is the global empty array.
  815. // Just overwrite with a new one. No need to transfer or free anything.
  816. num_buckets_ = index_of_first_non_null_ = kMinTableSize;
  817. table_ = CreateEmptyTable(num_buckets_);
  818. seed_ = Seed();
  819. return;
  820. }
  821. GOOGLE_DCHECK_GE(new_num_buckets, kMinTableSize);
  822. void** const old_table = table_;
  823. const size_type old_table_size = num_buckets_;
  824. num_buckets_ = new_num_buckets;
  825. table_ = CreateEmptyTable(num_buckets_);
  826. const size_type start = index_of_first_non_null_;
  827. index_of_first_non_null_ = num_buckets_;
  828. for (size_type i = start; i < old_table_size; i++) {
  829. if (internal::TableEntryIsNonEmptyList(old_table, i)) {
  830. TransferList(old_table, i);
  831. } else if (internal::TableEntryIsTree(old_table, i)) {
  832. TransferTree(old_table, i++);
  833. }
  834. }
  835. Dealloc<void*>(old_table, old_table_size);
  836. }
  837. void TransferList(void* const* table, size_type index) {
  838. Node* node = static_cast<Node*>(table[index]);
  839. do {
  840. Node* next = node->next;
  841. InsertUnique(BucketNumber(node->kv.first), node);
  842. node = next;
  843. } while (node != nullptr);
  844. }
  845. void TransferTree(void* const* table, size_type index) {
  846. Tree* tree = static_cast<Tree*>(table[index]);
  847. typename Tree::iterator tree_it = tree->begin();
  848. do {
  849. InsertUnique(BucketNumber(std::cref(tree_it->first).get()),
  850. NodeFromTreeIterator(tree_it));
  851. } while (++tree_it != tree->end());
  852. DestroyTree(tree);
  853. }
  854. Node* EraseFromLinkedList(Node* item, Node* head) {
  855. if (head == item) {
  856. return head->next;
  857. } else {
  858. head->next = EraseFromLinkedList(item, head->next);
  859. return head;
  860. }
  861. }
  862. bool TableEntryIsEmpty(size_type b) const {
  863. return internal::TableEntryIsEmpty(table_, b);
  864. }
  865. bool TableEntryIsNonEmptyList(size_type b) const {
  866. return internal::TableEntryIsNonEmptyList(table_, b);
  867. }
  868. bool TableEntryIsTree(size_type b) const {
  869. return internal::TableEntryIsTree(table_, b);
  870. }
  871. bool TableEntryIsList(size_type b) const {
  872. return internal::TableEntryIsList(table_, b);
  873. }
  874. void TreeConvert(size_type b) {
  875. GOOGLE_DCHECK(!TableEntryIsTree(b) && !TableEntryIsTree(b ^ 1));
  876. Tree* tree =
  877. Arena::Create<Tree>(alloc_.arena(), typename Tree::key_compare(),
  878. typename Tree::allocator_type(alloc_));
  879. size_type count = CopyListToTree(b, tree) + CopyListToTree(b ^ 1, tree);
  880. GOOGLE_DCHECK_EQ(count, tree->size());
  881. table_[b] = table_[b ^ 1] = static_cast<void*>(tree);
  882. }
  883. // Copy a linked list in the given bucket to a tree.
  884. // Returns the number of things it copied.
  885. size_type CopyListToTree(size_type b, Tree* tree) {
  886. size_type count = 0;
  887. Node* node = static_cast<Node*>(table_[b]);
  888. while (node != nullptr) {
  889. tree->insert({node->kv.first, node});
  890. ++count;
  891. Node* next = node->next;
  892. node->next = nullptr;
  893. node = next;
  894. }
  895. return count;
  896. }
  897. // Return whether table_[b] is a linked list that seems awfully long.
  898. // Requires table_[b] to point to a non-empty linked list.
  899. bool TableEntryIsTooLong(size_type b) {
  900. const size_type kMaxLength = 8;
  901. size_type count = 0;
  902. Node* node = static_cast<Node*>(table_[b]);
  903. do {
  904. ++count;
  905. node = node->next;
  906. } while (node != nullptr);
  907. // Invariant: no linked list ever is more than kMaxLength in length.
  908. GOOGLE_DCHECK_LE(count, kMaxLength);
  909. return count >= kMaxLength;
  910. }
  911. template <typename K>
  912. size_type BucketNumber(const K& k) const {
  913. // We xor the hash value against the random seed so that we effectively
  914. // have a random hash function.
  915. uint64 h = hash_function()(k) ^ seed_;
  916. // We use the multiplication method to determine the bucket number from
  917. // the hash value. The constant kPhi (suggested by Knuth) is roughly
  918. // (sqrt(5) - 1) / 2 * 2^64.
  919. constexpr uint64 kPhi = uint64{0x9e3779b97f4a7c15};
  920. return ((kPhi * h) >> 32) & (num_buckets_ - 1);
  921. }
  922. // Return a power of two no less than max(kMinTableSize, n).
  923. // Assumes either n < kMinTableSize or n is a power of two.
  924. size_type TableSize(size_type n) {
  925. return n < static_cast<size_type>(kMinTableSize)
  926. ? static_cast<size_type>(kMinTableSize)
  927. : n;
  928. }
  929. // Use alloc_ to allocate an array of n objects of type U.
  930. template <typename U>
  931. U* Alloc(size_type n) {
  932. using alloc_type = typename Allocator::template rebind<U>::other;
  933. return alloc_type(alloc_).allocate(n);
  934. }
  935. // Use alloc_ to deallocate an array of n objects of type U.
  936. template <typename U>
  937. void Dealloc(U* t, size_type n) {
  938. using alloc_type = typename Allocator::template rebind<U>::other;
  939. alloc_type(alloc_).deallocate(t, n);
  940. }
  941. void DestroyNode(Node* node) {
  942. if (alloc_.arena() == nullptr) {
  943. delete node;
  944. }
  945. }
  946. void DestroyTree(Tree* tree) {
  947. if (alloc_.arena() == nullptr) {
  948. delete tree;
  949. }
  950. }
  951. void** CreateEmptyTable(size_type n) {
  952. GOOGLE_DCHECK(n >= kMinTableSize);
  953. GOOGLE_DCHECK_EQ(n & (n - 1), 0);
  954. void** result = Alloc<void*>(n);
  955. memset(result, 0, n * sizeof(result[0]));
  956. return result;
  957. }
  958. // Return a randomish value.
  959. size_type Seed() const {
  960. // We get a little bit of randomness from the address of the map. The
  961. // lower bits are not very random, due to alignment, so we discard them
  962. // and shift the higher bits into their place.
  963. size_type s = reinterpret_cast<uintptr_t>(this) >> 12;
  964. #if defined(__x86_64__) && defined(__GNUC__) && \
  965. !defined(GOOGLE_PROTOBUF_NO_RDTSC)
  966. uint32 hi, lo;
  967. asm volatile("rdtsc" : "=a"(lo), "=d"(hi));
  968. s += ((static_cast<uint64>(hi) << 32) | lo);
  969. #endif
  970. return s;
  971. }
  972. friend class Arena;
  973. using InternalArenaConstructable_ = void;
  974. using DestructorSkippable_ = void;
  975. size_type num_elements_;
  976. size_type num_buckets_;
  977. size_type seed_;
  978. size_type index_of_first_non_null_;
  979. void** table_; // an array with num_buckets_ entries
  980. Allocator alloc_;
  981. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(InnerMap);
  982. }; // end of class InnerMap
  983. template <typename LookupKey>
  984. using key_arg = typename internal::TransparentSupport<
  985. key_type>::template key_arg<LookupKey>;
  986. public:
  987. // Iterators
  988. class const_iterator {
  989. using InnerIt = typename InnerMap::const_iterator;
  990. public:
  991. using iterator_category = std::forward_iterator_tag;
  992. using value_type = typename Map::value_type;
  993. using difference_type = ptrdiff_t;
  994. using pointer = const value_type*;
  995. using reference = const value_type&;
  996. const_iterator() {}
  997. explicit const_iterator(const InnerIt& it) : it_(it) {}
  998. const_reference operator*() const { return *it_; }
  999. const_pointer operator->() const { return &(operator*()); }
  1000. const_iterator& operator++() {
  1001. ++it_;
  1002. return *this;
  1003. }
  1004. const_iterator operator++(int) { return const_iterator(it_++); }
  1005. friend bool operator==(const const_iterator& a, const const_iterator& b) {
  1006. return a.it_ == b.it_;
  1007. }
  1008. friend bool operator!=(const const_iterator& a, const const_iterator& b) {
  1009. return !(a == b);
  1010. }
  1011. private:
  1012. InnerIt it_;
  1013. };
  1014. class iterator {
  1015. using InnerIt = typename InnerMap::iterator;
  1016. public:
  1017. using iterator_category = std::forward_iterator_tag;
  1018. using value_type = typename Map::value_type;
  1019. using difference_type = ptrdiff_t;
  1020. using pointer = value_type*;
  1021. using reference = value_type&;
  1022. iterator() {}
  1023. explicit iterator(const InnerIt& it) : it_(it) {}
  1024. reference operator*() const { return *it_; }
  1025. pointer operator->() const { return &(operator*()); }
  1026. iterator& operator++() {
  1027. ++it_;
  1028. return *this;
  1029. }
  1030. iterator operator++(int) { return iterator(it_++); }
  1031. // Allow implicit conversion to const_iterator.
  1032. operator const_iterator() const { // NOLINT(runtime/explicit)
  1033. return const_iterator(typename InnerMap::const_iterator(it_));
  1034. }
  1035. friend bool operator==(const iterator& a, const iterator& b) {
  1036. return a.it_ == b.it_;
  1037. }
  1038. friend bool operator!=(const iterator& a, const iterator& b) {
  1039. return !(a == b);
  1040. }
  1041. private:
  1042. friend class Map;
  1043. InnerIt it_;
  1044. };
  1045. iterator begin() { return iterator(elements_.begin()); }
  1046. iterator end() { return iterator(elements_.end()); }
  1047. const_iterator begin() const { return const_iterator(elements_.begin()); }
  1048. const_iterator end() const { return const_iterator(elements_.end()); }
  1049. const_iterator cbegin() const { return begin(); }
  1050. const_iterator cend() const { return end(); }
  1051. // Capacity
  1052. size_type size() const { return elements_.size(); }
  1053. bool empty() const { return size() == 0; }
  1054. // Element access
  1055. template <typename K = key_type>
  1056. T& operator[](const key_arg<K>& key) {
  1057. return elements_[key].second;
  1058. }
  1059. template <
  1060. typename K = key_type,
  1061. // Disable for integral types to reduce code bloat.
  1062. typename = typename std::enable_if<!std::is_integral<K>::value>::type>
  1063. T& operator[](key_arg<K>&& key) {
  1064. return elements_[std::forward<K>(key)].second;
  1065. }
  1066. template <typename K = key_type>
  1067. const T& at(const key_arg<K>& key) const {
  1068. const_iterator it = find(key);
  1069. GOOGLE_CHECK(it != end()) << "key not found: " << static_cast<Key>(key);
  1070. return it->second;
  1071. }
  1072. template <typename K = key_type>
  1073. T& at(const key_arg<K>& key) {
  1074. iterator it = find(key);
  1075. GOOGLE_CHECK(it != end()) << "key not found: " << static_cast<Key>(key);
  1076. return it->second;
  1077. }
  1078. // Lookup
  1079. template <typename K = key_type>
  1080. size_type count(const key_arg<K>& key) const {
  1081. return find(key) == end() ? 0 : 1;
  1082. }
  1083. template <typename K = key_type>
  1084. const_iterator find(const key_arg<K>& key) const {
  1085. return const_iterator(elements_.find(key));
  1086. }
  1087. template <typename K = key_type>
  1088. iterator find(const key_arg<K>& key) {
  1089. return iterator(elements_.find(key));
  1090. }
  1091. template <typename K = key_type>
  1092. bool contains(const key_arg<K>& key) const {
  1093. return find(key) != end();
  1094. }
  1095. template <typename K = key_type>
  1096. std::pair<const_iterator, const_iterator> equal_range(
  1097. const key_arg<K>& key) const {
  1098. const_iterator it = find(key);
  1099. if (it == end()) {
  1100. return std::pair<const_iterator, const_iterator>(it, it);
  1101. } else {
  1102. const_iterator begin = it++;
  1103. return std::pair<const_iterator, const_iterator>(begin, it);
  1104. }
  1105. }
  1106. template <typename K = key_type>
  1107. std::pair<iterator, iterator> equal_range(const key_arg<K>& key) {
  1108. iterator it = find(key);
  1109. if (it == end()) {
  1110. return std::pair<iterator, iterator>(it, it);
  1111. } else {
  1112. iterator begin = it++;
  1113. return std::pair<iterator, iterator>(begin, it);
  1114. }
  1115. }
  1116. // insert
  1117. std::pair<iterator, bool> insert(const value_type& value) {
  1118. std::pair<typename InnerMap::iterator, bool> p =
  1119. elements_.insert(value.first);
  1120. if (p.second) {
  1121. p.first->second = value.second;
  1122. }
  1123. return std::pair<iterator, bool>(iterator(p.first), p.second);
  1124. }
  1125. template <class InputIt>
  1126. void insert(InputIt first, InputIt last) {
  1127. for (InputIt it = first; it != last; ++it) {
  1128. iterator exist_it = find(it->first);
  1129. if (exist_it == end()) {
  1130. operator[](it->first) = it->second;
  1131. }
  1132. }
  1133. }
  1134. void insert(std::initializer_list<value_type> values) {
  1135. insert(values.begin(), values.end());
  1136. }
  1137. // Erase and clear
  1138. template <typename K = key_type>
  1139. size_type erase(const key_arg<K>& key) {
  1140. iterator it = find(key);
  1141. if (it == end()) {
  1142. return 0;
  1143. } else {
  1144. erase(it);
  1145. return 1;
  1146. }
  1147. }
  1148. iterator erase(iterator pos) {
  1149. iterator i = pos++;
  1150. elements_.erase(i.it_);
  1151. return pos;
  1152. }
  1153. void erase(iterator first, iterator last) {
  1154. while (first != last) {
  1155. first = erase(first);
  1156. }
  1157. }
  1158. void clear() { elements_.clear(); }
  1159. // Assign
  1160. Map& operator=(const Map& other) {
  1161. if (this != &other) {
  1162. clear();
  1163. insert(other.begin(), other.end());
  1164. }
  1165. return *this;
  1166. }
  1167. void swap(Map& other) {
  1168. if (arena() == other.arena()) {
  1169. InternalSwap(other);
  1170. } else {
  1171. // TODO(zuguang): optimize this. The temporary copy can be allocated
  1172. // in the same arena as the other message, and the "other = copy" can
  1173. // be replaced with the fast-path swap above.
  1174. Map copy = *this;
  1175. *this = other;
  1176. other = copy;
  1177. }
  1178. }
  1179. void InternalSwap(Map& other) { elements_.Swap(&other.elements_); }
  1180. // Access to hasher. Currently this returns a copy, but it may
  1181. // be modified to return a const reference in the future.
  1182. hasher hash_function() const { return elements_.hash_function(); }
  1183. size_t SpaceUsedExcludingSelfLong() const {
  1184. if (empty()) return 0;
  1185. return elements_.SpaceUsedInternal() + internal::SpaceUsedInValues(this);
  1186. }
  1187. private:
  1188. Arena* arena() const { return elements_.arena(); }
  1189. InnerMap elements_;
  1190. friend class Arena;
  1191. using InternalArenaConstructable_ = void;
  1192. using DestructorSkippable_ = void;
  1193. template <typename Derived, typename K, typename V,
  1194. internal::WireFormatLite::FieldType key_wire_type,
  1195. internal::WireFormatLite::FieldType value_wire_type>
  1196. friend class internal::MapFieldLite;
  1197. };
  1198. } // namespace protobuf
  1199. } // namespace google
  1200. #include <google/protobuf/port_undef.inc>
  1201. #endif // GOOGLE_PROTOBUF_MAP_H__