map_util.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2014 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. // from google3/util/gtl/map_util.h
  31. // Author: Anton Carver
  32. #ifndef GOOGLE_PROTOBUF_STUBS_MAP_UTIL_H__
  33. #define GOOGLE_PROTOBUF_STUBS_MAP_UTIL_H__
  34. #include <stddef.h>
  35. #include <iterator>
  36. #include <string>
  37. #include <utility>
  38. #include <vector>
  39. #include <google/protobuf/stubs/common.h>
  40. namespace google {
  41. namespace protobuf {
  42. namespace internal {
  43. // Local implementation of RemoveConst to avoid including base/type_traits.h.
  44. template <class T> struct RemoveConst { typedef T type; };
  45. template <class T> struct RemoveConst<const T> : RemoveConst<T> {};
  46. } // namespace internal
  47. //
  48. // Find*()
  49. //
  50. // Returns a const reference to the value associated with the given key if it
  51. // exists. Crashes otherwise.
  52. //
  53. // This is intended as a replacement for operator[] as an rvalue (for reading)
  54. // when the key is guaranteed to exist.
  55. //
  56. // operator[] for lookup is discouraged for several reasons:
  57. // * It has a side-effect of inserting missing keys
  58. // * It is not thread-safe (even when it is not inserting, it can still
  59. // choose to resize the underlying storage)
  60. // * It invalidates iterators (when it chooses to resize)
  61. // * It default constructs a value object even if it doesn't need to
  62. //
  63. // This version assumes the key is printable, and includes it in the fatal log
  64. // message.
  65. template <class Collection>
  66. const typename Collection::value_type::second_type&
  67. FindOrDie(const Collection& collection,
  68. const typename Collection::value_type::first_type& key) {
  69. typename Collection::const_iterator it = collection.find(key);
  70. GOOGLE_CHECK(it != collection.end()) << "Map key not found: " << key;
  71. return it->second;
  72. }
  73. // Same as above, but returns a non-const reference.
  74. template <class Collection>
  75. typename Collection::value_type::second_type&
  76. FindOrDie(Collection& collection, // NOLINT
  77. const typename Collection::value_type::first_type& key) {
  78. typename Collection::iterator it = collection.find(key);
  79. GOOGLE_CHECK(it != collection.end()) << "Map key not found: " << key;
  80. return it->second;
  81. }
  82. // Same as FindOrDie above, but doesn't log the key on failure.
  83. template <class Collection>
  84. const typename Collection::value_type::second_type&
  85. FindOrDieNoPrint(const Collection& collection,
  86. const typename Collection::value_type::first_type& key) {
  87. typename Collection::const_iterator it = collection.find(key);
  88. GOOGLE_CHECK(it != collection.end()) << "Map key not found";
  89. return it->second;
  90. }
  91. // Same as above, but returns a non-const reference.
  92. template <class Collection>
  93. typename Collection::value_type::second_type&
  94. FindOrDieNoPrint(Collection& collection, // NOLINT
  95. const typename Collection::value_type::first_type& key) {
  96. typename Collection::iterator it = collection.find(key);
  97. GOOGLE_CHECK(it != collection.end()) << "Map key not found";
  98. return it->second;
  99. }
  100. // Returns a const reference to the value associated with the given key if it
  101. // exists, otherwise returns a const reference to the provided default value.
  102. //
  103. // WARNING: If a temporary object is passed as the default "value,"
  104. // this function will return a reference to that temporary object,
  105. // which will be destroyed at the end of the statement. A common
  106. // example: if you have a map with string values, and you pass a char*
  107. // as the default "value," either use the returned value immediately
  108. // or store it in a string (not string&).
  109. // Details: http://go/findwithdefault
  110. template <class Collection>
  111. const typename Collection::value_type::second_type&
  112. FindWithDefault(const Collection& collection,
  113. const typename Collection::value_type::first_type& key,
  114. const typename Collection::value_type::second_type& value) {
  115. typename Collection::const_iterator it = collection.find(key);
  116. if (it == collection.end()) {
  117. return value;
  118. }
  119. return it->second;
  120. }
  121. // Returns a pointer to the const value associated with the given key if it
  122. // exists, or nullptr otherwise.
  123. template <class Collection>
  124. const typename Collection::value_type::second_type*
  125. FindOrNull(const Collection& collection,
  126. const typename Collection::value_type::first_type& key) {
  127. typename Collection::const_iterator it = collection.find(key);
  128. if (it == collection.end()) {
  129. return 0;
  130. }
  131. return &it->second;
  132. }
  133. // Same as above but returns a pointer to the non-const value.
  134. template <class Collection>
  135. typename Collection::value_type::second_type*
  136. FindOrNull(Collection& collection, // NOLINT
  137. const typename Collection::value_type::first_type& key) {
  138. typename Collection::iterator it = collection.find(key);
  139. if (it == collection.end()) {
  140. return 0;
  141. }
  142. return &it->second;
  143. }
  144. // Returns the pointer value associated with the given key. If none is found,
  145. // nullptr is returned. The function is designed to be used with a map of keys to
  146. // pointers.
  147. //
  148. // This function does not distinguish between a missing key and a key mapped
  149. // to nullptr.
  150. template <class Collection>
  151. typename Collection::value_type::second_type
  152. FindPtrOrNull(const Collection& collection,
  153. const typename Collection::value_type::first_type& key) {
  154. typename Collection::const_iterator it = collection.find(key);
  155. if (it == collection.end()) {
  156. return typename Collection::value_type::second_type();
  157. }
  158. return it->second;
  159. }
  160. // Same as above, except takes non-const reference to collection.
  161. //
  162. // This function is needed for containers that propagate constness to the
  163. // pointee, such as boost::ptr_map.
  164. template <class Collection>
  165. typename Collection::value_type::second_type
  166. FindPtrOrNull(Collection& collection, // NOLINT
  167. const typename Collection::value_type::first_type& key) {
  168. typename Collection::iterator it = collection.find(key);
  169. if (it == collection.end()) {
  170. return typename Collection::value_type::second_type();
  171. }
  172. return it->second;
  173. }
  174. // Finds the pointer value associated with the given key in a map whose values
  175. // are linked_ptrs. Returns nullptr if key is not found.
  176. template <class Collection>
  177. typename Collection::value_type::second_type::element_type*
  178. FindLinkedPtrOrNull(const Collection& collection,
  179. const typename Collection::value_type::first_type& key) {
  180. typename Collection::const_iterator it = collection.find(key);
  181. if (it == collection.end()) {
  182. return 0;
  183. }
  184. // Since linked_ptr::get() is a const member returning a non const,
  185. // we do not need a version of this function taking a non const collection.
  186. return it->second.get();
  187. }
  188. // Same as above, but dies if the key is not found.
  189. template <class Collection>
  190. typename Collection::value_type::second_type::element_type&
  191. FindLinkedPtrOrDie(const Collection& collection,
  192. const typename Collection::value_type::first_type& key) {
  193. typename Collection::const_iterator it = collection.find(key);
  194. GOOGLE_CHECK(it != collection.end()) << "key not found: " << key;
  195. // Since linked_ptr::operator*() is a const member returning a non const,
  196. // we do not need a version of this function taking a non const collection.
  197. return *it->second;
  198. }
  199. // Finds the value associated with the given key and copies it to *value (if not
  200. // nullptr). Returns false if the key was not found, true otherwise.
  201. template <class Collection, class Key, class Value>
  202. bool FindCopy(const Collection& collection,
  203. const Key& key,
  204. Value* const value) {
  205. typename Collection::const_iterator it = collection.find(key);
  206. if (it == collection.end()) {
  207. return false;
  208. }
  209. if (value) {
  210. *value = it->second;
  211. }
  212. return true;
  213. }
  214. //
  215. // Contains*()
  216. //
  217. // Returns true if and only if the given collection contains the given key.
  218. template <class Collection, class Key>
  219. bool ContainsKey(const Collection& collection, const Key& key) {
  220. return collection.find(key) != collection.end();
  221. }
  222. // Returns true if and only if the given collection contains the given key-value
  223. // pair.
  224. template <class Collection, class Key, class Value>
  225. bool ContainsKeyValuePair(const Collection& collection,
  226. const Key& key,
  227. const Value& value) {
  228. typedef typename Collection::const_iterator const_iterator;
  229. std::pair<const_iterator, const_iterator> range = collection.equal_range(key);
  230. for (const_iterator it = range.first; it != range.second; ++it) {
  231. if (it->second == value) {
  232. return true;
  233. }
  234. }
  235. return false;
  236. }
  237. //
  238. // Insert*()
  239. //
  240. // Inserts the given key-value pair into the collection. Returns true if and
  241. // only if the key from the given pair didn't previously exist. Otherwise, the
  242. // value in the map is replaced with the value from the given pair.
  243. template <class Collection>
  244. bool InsertOrUpdate(Collection* const collection,
  245. const typename Collection::value_type& vt) {
  246. std::pair<typename Collection::iterator, bool> ret = collection->insert(vt);
  247. if (!ret.second) {
  248. // update
  249. ret.first->second = vt.second;
  250. return false;
  251. }
  252. return true;
  253. }
  254. // Same as above, except that the key and value are passed separately.
  255. template <class Collection>
  256. bool InsertOrUpdate(Collection* const collection,
  257. const typename Collection::value_type::first_type& key,
  258. const typename Collection::value_type::second_type& value) {
  259. return InsertOrUpdate(
  260. collection, typename Collection::value_type(key, value));
  261. }
  262. // Inserts/updates all the key-value pairs from the range defined by the
  263. // iterators "first" and "last" into the given collection.
  264. template <class Collection, class InputIterator>
  265. void InsertOrUpdateMany(Collection* const collection,
  266. InputIterator first, InputIterator last) {
  267. for (; first != last; ++first) {
  268. InsertOrUpdate(collection, *first);
  269. }
  270. }
  271. // Change the value associated with a particular key in a map or hash_map
  272. // of the form map<Key, Value*> which owns the objects pointed to by the
  273. // value pointers. If there was an existing value for the key, it is deleted.
  274. // True indicates an insert took place, false indicates an update + delete.
  275. template <class Collection>
  276. bool InsertAndDeleteExisting(
  277. Collection* const collection,
  278. const typename Collection::value_type::first_type& key,
  279. const typename Collection::value_type::second_type& value) {
  280. std::pair<typename Collection::iterator, bool> ret =
  281. collection->insert(typename Collection::value_type(key, value));
  282. if (!ret.second) {
  283. delete ret.first->second;
  284. ret.first->second = value;
  285. return false;
  286. }
  287. return true;
  288. }
  289. // Inserts the given key and value into the given collection if and only if the
  290. // given key did NOT already exist in the collection. If the key previously
  291. // existed in the collection, the value is not changed. Returns true if the
  292. // key-value pair was inserted; returns false if the key was already present.
  293. template <class Collection>
  294. bool InsertIfNotPresent(Collection* const collection,
  295. const typename Collection::value_type& vt) {
  296. return collection->insert(vt).second;
  297. }
  298. // Same as above except the key and value are passed separately.
  299. template <class Collection>
  300. bool InsertIfNotPresent(
  301. Collection* const collection,
  302. const typename Collection::value_type::first_type& key,
  303. const typename Collection::value_type::second_type& value) {
  304. return InsertIfNotPresent(
  305. collection, typename Collection::value_type(key, value));
  306. }
  307. // Same as above except dies if the key already exists in the collection.
  308. template <class Collection>
  309. void InsertOrDie(Collection* const collection,
  310. const typename Collection::value_type& value) {
  311. GOOGLE_CHECK(InsertIfNotPresent(collection, value))
  312. << "duplicate value: " << value;
  313. }
  314. // Same as above except doesn't log the value on error.
  315. template <class Collection>
  316. void InsertOrDieNoPrint(Collection* const collection,
  317. const typename Collection::value_type& value) {
  318. GOOGLE_CHECK(InsertIfNotPresent(collection, value)) << "duplicate value.";
  319. }
  320. // Inserts the key-value pair into the collection. Dies if key was already
  321. // present.
  322. template <class Collection>
  323. void InsertOrDie(Collection* const collection,
  324. const typename Collection::value_type::first_type& key,
  325. const typename Collection::value_type::second_type& data) {
  326. GOOGLE_CHECK(InsertIfNotPresent(collection, key, data))
  327. << "duplicate key: " << key;
  328. }
  329. // Same as above except doesn't log the key on error.
  330. template <class Collection>
  331. void InsertOrDieNoPrint(
  332. Collection* const collection,
  333. const typename Collection::value_type::first_type& key,
  334. const typename Collection::value_type::second_type& data) {
  335. GOOGLE_CHECK(InsertIfNotPresent(collection, key, data)) << "duplicate key.";
  336. }
  337. // Inserts a new key and default-initialized value. Dies if the key was already
  338. // present. Returns a reference to the value. Example usage:
  339. //
  340. // map<int, SomeProto> m;
  341. // SomeProto& proto = InsertKeyOrDie(&m, 3);
  342. // proto.set_field("foo");
  343. template <class Collection>
  344. typename Collection::value_type::second_type& InsertKeyOrDie(
  345. Collection* const collection,
  346. const typename Collection::value_type::first_type& key) {
  347. typedef typename Collection::value_type value_type;
  348. std::pair<typename Collection::iterator, bool> res =
  349. collection->insert(value_type(key, typename value_type::second_type()));
  350. GOOGLE_CHECK(res.second) << "duplicate key: " << key;
  351. return res.first->second;
  352. }
  353. //
  354. // Lookup*()
  355. //
  356. // Looks up a given key and value pair in a collection and inserts the key-value
  357. // pair if it's not already present. Returns a reference to the value associated
  358. // with the key.
  359. template <class Collection>
  360. typename Collection::value_type::second_type&
  361. LookupOrInsert(Collection* const collection,
  362. const typename Collection::value_type& vt) {
  363. return collection->insert(vt).first->second;
  364. }
  365. // Same as above except the key-value are passed separately.
  366. template <class Collection>
  367. typename Collection::value_type::second_type&
  368. LookupOrInsert(Collection* const collection,
  369. const typename Collection::value_type::first_type& key,
  370. const typename Collection::value_type::second_type& value) {
  371. return LookupOrInsert(
  372. collection, typename Collection::value_type(key, value));
  373. }
  374. // Counts the number of equivalent elements in the given "sequence", and stores
  375. // the results in "count_map" with element as the key and count as the value.
  376. //
  377. // Example:
  378. // vector<string> v = {"a", "b", "c", "a", "b"};
  379. // map<string, int> m;
  380. // AddTokenCounts(v, 1, &m);
  381. // assert(m["a"] == 2);
  382. // assert(m["b"] == 2);
  383. // assert(m["c"] == 1);
  384. template <typename Sequence, typename Collection>
  385. void AddTokenCounts(
  386. const Sequence& sequence,
  387. const typename Collection::value_type::second_type& increment,
  388. Collection* const count_map) {
  389. for (typename Sequence::const_iterator it = sequence.begin();
  390. it != sequence.end(); ++it) {
  391. typename Collection::value_type::second_type& value =
  392. LookupOrInsert(count_map, *it,
  393. typename Collection::value_type::second_type());
  394. value += increment;
  395. }
  396. }
  397. // Returns a reference to the value associated with key. If not found, a value
  398. // is default constructed on the heap and added to the map.
  399. //
  400. // This function is useful for containers of the form map<Key, Value*>, where
  401. // inserting a new key, value pair involves constructing a new heap-allocated
  402. // Value, and storing a pointer to that in the collection.
  403. template <class Collection>
  404. typename Collection::value_type::second_type&
  405. LookupOrInsertNew(Collection* const collection,
  406. const typename Collection::value_type::first_type& key) {
  407. typedef typename std::iterator_traits<
  408. typename Collection::value_type::second_type>::value_type Element;
  409. std::pair<typename Collection::iterator, bool> ret =
  410. collection->insert(typename Collection::value_type(
  411. key,
  412. static_cast<typename Collection::value_type::second_type>(nullptr)));
  413. if (ret.second) {
  414. ret.first->second = new Element();
  415. }
  416. return ret.first->second;
  417. }
  418. // Same as above but constructs the value using the single-argument constructor
  419. // and the given "arg".
  420. template <class Collection, class Arg>
  421. typename Collection::value_type::second_type&
  422. LookupOrInsertNew(Collection* const collection,
  423. const typename Collection::value_type::first_type& key,
  424. const Arg& arg) {
  425. typedef typename std::iterator_traits<
  426. typename Collection::value_type::second_type>::value_type Element;
  427. std::pair<typename Collection::iterator, bool> ret =
  428. collection->insert(typename Collection::value_type(
  429. key,
  430. static_cast<typename Collection::value_type::second_type>(nullptr)));
  431. if (ret.second) {
  432. ret.first->second = new Element(arg);
  433. }
  434. return ret.first->second;
  435. }
  436. // Lookup of linked/shared pointers is used in two scenarios:
  437. //
  438. // Use LookupOrInsertNewLinkedPtr if the container owns the elements.
  439. // In this case it is fine working with the raw pointer as long as it is
  440. // guaranteed that no other thread can delete/update an accessed element.
  441. // A mutex will need to lock the container operation as well as the use
  442. // of the returned elements. Finding an element may be performed using
  443. // FindLinkedPtr*().
  444. //
  445. // Use LookupOrInsertNewSharedPtr if the container does not own the elements
  446. // for their whole lifetime. This is typically the case when a reader allows
  447. // parallel updates to the container. In this case a Mutex only needs to lock
  448. // container operations, but all element operations must be performed on the
  449. // shared pointer. Finding an element must be performed using FindPtr*() and
  450. // cannot be done with FindLinkedPtr*() even though it compiles.
  451. // Lookup a key in a map or hash_map whose values are linked_ptrs. If it is
  452. // missing, set collection[key].reset(new Value::element_type) and return that.
  453. // Value::element_type must be default constructable.
  454. template <class Collection>
  455. typename Collection::value_type::second_type::element_type*
  456. LookupOrInsertNewLinkedPtr(
  457. Collection* const collection,
  458. const typename Collection::value_type::first_type& key) {
  459. typedef typename Collection::value_type::second_type Value;
  460. std::pair<typename Collection::iterator, bool> ret =
  461. collection->insert(typename Collection::value_type(key, Value()));
  462. if (ret.second) {
  463. ret.first->second.reset(new typename Value::element_type);
  464. }
  465. return ret.first->second.get();
  466. }
  467. // A variant of LookupOrInsertNewLinkedPtr where the value is constructed using
  468. // a single-parameter constructor. Note: the constructor argument is computed
  469. // even if it will not be used, so only values cheap to compute should be passed
  470. // here. On the other hand it does not matter how expensive the construction of
  471. // the actual stored value is, as that only occurs if necessary.
  472. template <class Collection, class Arg>
  473. typename Collection::value_type::second_type::element_type*
  474. LookupOrInsertNewLinkedPtr(
  475. Collection* const collection,
  476. const typename Collection::value_type::first_type& key,
  477. const Arg& arg) {
  478. typedef typename Collection::value_type::second_type Value;
  479. std::pair<typename Collection::iterator, bool> ret =
  480. collection->insert(typename Collection::value_type(key, Value()));
  481. if (ret.second) {
  482. ret.first->second.reset(new typename Value::element_type(arg));
  483. }
  484. return ret.first->second.get();
  485. }
  486. // Lookup a key in a map or hash_map whose values are shared_ptrs. If it is
  487. // missing, set collection[key].reset(new Value::element_type). Unlike
  488. // LookupOrInsertNewLinkedPtr, this function returns the shared_ptr instead of
  489. // the raw pointer. Value::element_type must be default constructable.
  490. template <class Collection>
  491. typename Collection::value_type::second_type&
  492. LookupOrInsertNewSharedPtr(
  493. Collection* const collection,
  494. const typename Collection::value_type::first_type& key) {
  495. typedef typename Collection::value_type::second_type SharedPtr;
  496. typedef typename Collection::value_type::second_type::element_type Element;
  497. std::pair<typename Collection::iterator, bool> ret =
  498. collection->insert(typename Collection::value_type(key, SharedPtr()));
  499. if (ret.second) {
  500. ret.first->second.reset(new Element());
  501. }
  502. return ret.first->second;
  503. }
  504. // A variant of LookupOrInsertNewSharedPtr where the value is constructed using
  505. // a single-parameter constructor. Note: the constructor argument is computed
  506. // even if it will not be used, so only values cheap to compute should be passed
  507. // here. On the other hand it does not matter how expensive the construction of
  508. // the actual stored value is, as that only occurs if necessary.
  509. template <class Collection, class Arg>
  510. typename Collection::value_type::second_type&
  511. LookupOrInsertNewSharedPtr(
  512. Collection* const collection,
  513. const typename Collection::value_type::first_type& key,
  514. const Arg& arg) {
  515. typedef typename Collection::value_type::second_type SharedPtr;
  516. typedef typename Collection::value_type::second_type::element_type Element;
  517. std::pair<typename Collection::iterator, bool> ret =
  518. collection->insert(typename Collection::value_type(key, SharedPtr()));
  519. if (ret.second) {
  520. ret.first->second.reset(new Element(arg));
  521. }
  522. return ret.first->second;
  523. }
  524. //
  525. // Misc Utility Functions
  526. //
  527. // Updates the value associated with the given key. If the key was not already
  528. // present, then the key-value pair are inserted and "previous" is unchanged. If
  529. // the key was already present, the value is updated and "*previous" will
  530. // contain a copy of the old value.
  531. //
  532. // InsertOrReturnExisting has complementary behavior that returns the
  533. // address of an already existing value, rather than updating it.
  534. template <class Collection>
  535. bool UpdateReturnCopy(Collection* const collection,
  536. const typename Collection::value_type::first_type& key,
  537. const typename Collection::value_type::second_type& value,
  538. typename Collection::value_type::second_type* previous) {
  539. std::pair<typename Collection::iterator, bool> ret =
  540. collection->insert(typename Collection::value_type(key, value));
  541. if (!ret.second) {
  542. // update
  543. if (previous) {
  544. *previous = ret.first->second;
  545. }
  546. ret.first->second = value;
  547. return true;
  548. }
  549. return false;
  550. }
  551. // Same as above except that the key and value are passed as a pair.
  552. template <class Collection>
  553. bool UpdateReturnCopy(Collection* const collection,
  554. const typename Collection::value_type& vt,
  555. typename Collection::value_type::second_type* previous) {
  556. std::pair<typename Collection::iterator, bool> ret = collection->insert(vt);
  557. if (!ret.second) {
  558. // update
  559. if (previous) {
  560. *previous = ret.first->second;
  561. }
  562. ret.first->second = vt.second;
  563. return true;
  564. }
  565. return false;
  566. }
  567. // Tries to insert the given key-value pair into the collection. Returns nullptr if
  568. // the insert succeeds. Otherwise, returns a pointer to the existing value.
  569. //
  570. // This complements UpdateReturnCopy in that it allows to update only after
  571. // verifying the old value and still insert quickly without having to look up
  572. // twice. Unlike UpdateReturnCopy this also does not come with the issue of an
  573. // undefined previous* in case new data was inserted.
  574. template <class Collection>
  575. typename Collection::value_type::second_type* InsertOrReturnExisting(
  576. Collection* const collection, const typename Collection::value_type& vt) {
  577. std::pair<typename Collection::iterator, bool> ret = collection->insert(vt);
  578. if (ret.second) {
  579. return nullptr; // Inserted, no existing previous value.
  580. } else {
  581. return &ret.first->second; // Return address of already existing value.
  582. }
  583. }
  584. // Same as above, except for explicit key and data.
  585. template <class Collection>
  586. typename Collection::value_type::second_type* InsertOrReturnExisting(
  587. Collection* const collection,
  588. const typename Collection::value_type::first_type& key,
  589. const typename Collection::value_type::second_type& data) {
  590. return InsertOrReturnExisting(collection,
  591. typename Collection::value_type(key, data));
  592. }
  593. // Erases the collection item identified by the given key, and returns the value
  594. // associated with that key. It is assumed that the value (i.e., the
  595. // mapped_type) is a pointer. Returns nullptr if the key was not found in the
  596. // collection.
  597. //
  598. // Examples:
  599. // map<string, MyType*> my_map;
  600. //
  601. // One line cleanup:
  602. // delete EraseKeyReturnValuePtr(&my_map, "abc");
  603. //
  604. // Use returned value:
  605. // std::unique_ptr<MyType> value_ptr(
  606. // EraseKeyReturnValuePtr(&my_map, "abc"));
  607. // if (value_ptr.get())
  608. // value_ptr->DoSomething();
  609. //
  610. template <class Collection>
  611. typename Collection::value_type::second_type EraseKeyReturnValuePtr(
  612. Collection* const collection,
  613. const typename Collection::value_type::first_type& key) {
  614. typename Collection::iterator it = collection->find(key);
  615. if (it == collection->end()) {
  616. return nullptr;
  617. }
  618. typename Collection::value_type::second_type v = it->second;
  619. collection->erase(it);
  620. return v;
  621. }
  622. // Inserts all the keys from map_container into key_container, which must
  623. // support insert(MapContainer::key_type).
  624. //
  625. // Note: any initial contents of the key_container are not cleared.
  626. template <class MapContainer, class KeyContainer>
  627. void InsertKeysFromMap(const MapContainer& map_container,
  628. KeyContainer* key_container) {
  629. GOOGLE_CHECK(key_container != nullptr);
  630. for (typename MapContainer::const_iterator it = map_container.begin();
  631. it != map_container.end(); ++it) {
  632. key_container->insert(it->first);
  633. }
  634. }
  635. // Appends all the keys from map_container into key_container, which must
  636. // support push_back(MapContainer::key_type).
  637. //
  638. // Note: any initial contents of the key_container are not cleared.
  639. template <class MapContainer, class KeyContainer>
  640. void AppendKeysFromMap(const MapContainer& map_container,
  641. KeyContainer* key_container) {
  642. GOOGLE_CHECK(key_container != nullptr);
  643. for (typename MapContainer::const_iterator it = map_container.begin();
  644. it != map_container.end(); ++it) {
  645. key_container->push_back(it->first);
  646. }
  647. }
  648. // A more specialized overload of AppendKeysFromMap to optimize reallocations
  649. // for the common case in which we're appending keys to a vector and hence can
  650. // (and sometimes should) call reserve() first.
  651. //
  652. // (It would be possible to play SFINAE games to call reserve() for any
  653. // container that supports it, but this seems to get us 99% of what we need
  654. // without the complexity of a SFINAE-based solution.)
  655. template <class MapContainer, class KeyType>
  656. void AppendKeysFromMap(const MapContainer& map_container,
  657. std::vector<KeyType>* key_container) {
  658. GOOGLE_CHECK(key_container != nullptr);
  659. // We now have the opportunity to call reserve(). Calling reserve() every
  660. // time is a bad idea for some use cases: libstdc++'s implementation of
  661. // vector<>::reserve() resizes the vector's backing store to exactly the
  662. // given size (unless it's already at least that big). Because of this,
  663. // the use case that involves appending a lot of small maps (total size
  664. // N) one by one to a vector would be O(N^2). But never calling reserve()
  665. // loses the opportunity to improve the use case of adding from a large
  666. // map to an empty vector (this improves performance by up to 33%). A
  667. // number of heuristics are possible; see the discussion in
  668. // cl/34081696. Here we use the simplest one.
  669. if (key_container->empty()) {
  670. key_container->reserve(map_container.size());
  671. }
  672. for (typename MapContainer::const_iterator it = map_container.begin();
  673. it != map_container.end(); ++it) {
  674. key_container->push_back(it->first);
  675. }
  676. }
  677. // Inserts all the values from map_container into value_container, which must
  678. // support push_back(MapContainer::mapped_type).
  679. //
  680. // Note: any initial contents of the value_container are not cleared.
  681. template <class MapContainer, class ValueContainer>
  682. void AppendValuesFromMap(const MapContainer& map_container,
  683. ValueContainer* value_container) {
  684. GOOGLE_CHECK(value_container != nullptr);
  685. for (typename MapContainer::const_iterator it = map_container.begin();
  686. it != map_container.end(); ++it) {
  687. value_container->push_back(it->second);
  688. }
  689. }
  690. // A more specialized overload of AppendValuesFromMap to optimize reallocations
  691. // for the common case in which we're appending values to a vector and hence
  692. // can (and sometimes should) call reserve() first.
  693. //
  694. // (It would be possible to play SFINAE games to call reserve() for any
  695. // container that supports it, but this seems to get us 99% of what we need
  696. // without the complexity of a SFINAE-based solution.)
  697. template <class MapContainer, class ValueType>
  698. void AppendValuesFromMap(const MapContainer& map_container,
  699. std::vector<ValueType>* value_container) {
  700. GOOGLE_CHECK(value_container != nullptr);
  701. // See AppendKeysFromMap for why this is done.
  702. if (value_container->empty()) {
  703. value_container->reserve(map_container.size());
  704. }
  705. for (typename MapContainer::const_iterator it = map_container.begin();
  706. it != map_container.end(); ++it) {
  707. value_container->push_back(it->second);
  708. }
  709. }
  710. } // namespace protobuf
  711. } // namespace google
  712. #endif // GOOGLE_PROTOBUF_STUBS_MAP_UTIL_H__