You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

map_util.h 37 kB

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