• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef PDFIUM_THIRD_PARTY_BASE_STL_UTIL_H_
6 #define PDFIUM_THIRD_PARTY_BASE_STL_UTIL_H_
7 
8 #include <algorithm>
9 #include <memory>
10 #include <set>
11 
12 #include "third_party/base/numerics/safe_conversions.h"
13 
14 namespace pdfium {
15 
16 // Test to see if a set, map, hash_set or hash_map contains a particular key.
17 // Returns true if the key is in the collection.
18 template <typename Collection, typename Key>
ContainsKey(const Collection & collection,const Key & key)19 bool ContainsKey(const Collection& collection, const Key& key) {
20   return collection.find(key) != collection.end();
21 }
22 
23 // Test to see if a collection like a vector contains a particular value.
24 // Returns true if the value is in the collection.
25 template <typename Collection, typename Value>
ContainsValue(const Collection & collection,const Value & value)26 bool ContainsValue(const Collection& collection, const Value& value) {
27   return std::find(collection.begin(), collection.end(), value) !=
28          collection.end();
29 }
30 
31 // Means of generating a key for searching STL collections of std::unique_ptr
32 // that avoids the side effect of deleting the pointer.
33 template <class T>
34 class FakeUniquePtr : public std::unique_ptr<T> {
35  public:
36   using std::unique_ptr<T>::unique_ptr;
~FakeUniquePtr()37   ~FakeUniquePtr() { std::unique_ptr<T>::release(); }
38 };
39 
40 // Convenience routine for "int-fected" code, so that the stl collection
41 // size_t size() method return values will be checked.
42 template <typename ResultType, typename Collection>
CollectionSize(const Collection & collection)43 ResultType CollectionSize(const Collection& collection) {
44   return pdfium::base::checked_cast<ResultType>(collection.size());
45 }
46 
47 // Track the addition of an object to a set, removing it automatically when
48 // the ScopedSetInsertion goes out of scope.
49 template <typename T>
50 class ScopedSetInsertion {
51  public:
ScopedSetInsertion(std::set<T> * org_set,T elem)52   ScopedSetInsertion(std::set<T>* org_set, T elem)
53       : m_Set(org_set), m_Entry(elem) {
54     m_Set->insert(m_Entry);
55   }
~ScopedSetInsertion()56   ~ScopedSetInsertion() { m_Set->erase(m_Entry); }
57 
58  private:
59   std::set<T>* const m_Set;
60   const T m_Entry;
61 };
62 
63 }  // namespace pdfium
64 
65 #endif  // PDFIUM_THIRD_PARTY_BASE_STL_UTIL_H_
66