map.h 44 KB

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