• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 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 // Derived from google3/util/gtl/stl_util.h
6 
7 #ifndef BASE_STL_UTIL_H_
8 #define BASE_STL_UTIL_H_
9 
10 #include <algorithm>
11 #include <functional>
12 #include <iterator>
13 #include <string>
14 #include <vector>
15 
16 #include "base/logging.h"
17 
18 // Clears internal memory of an STL object.
19 // STL clear()/reserve(0) does not always free internal memory allocated
20 // This function uses swap/destructor to ensure the internal memory is freed.
21 template<class T>
STLClearObject(T * obj)22 void STLClearObject(T* obj) {
23   T tmp;
24   tmp.swap(*obj);
25   // Sometimes "T tmp" allocates objects with memory (arena implementation?).
26   // Hence using additional reserve(0) even if it doesn't always work.
27   obj->reserve(0);
28 }
29 
30 // For a range within a container of pointers, calls delete (non-array version)
31 // on these pointers.
32 // NOTE: for these three functions, we could just implement a DeleteObject
33 // functor and then call for_each() on the range and functor, but this
34 // requires us to pull in all of algorithm.h, which seems expensive.
35 // For hash_[multi]set, it is important that this deletes behind the iterator
36 // because the hash_set may call the hash function on the iterator when it is
37 // advanced, which could result in the hash function trying to deference a
38 // stale pointer.
39 template <class ForwardIterator>
STLDeleteContainerPointers(ForwardIterator begin,ForwardIterator end)40 void STLDeleteContainerPointers(ForwardIterator begin, ForwardIterator end) {
41   while (begin != end) {
42     ForwardIterator temp = begin;
43     ++begin;
44     delete *temp;
45   }
46 }
47 
48 // For a range within a container of pairs, calls delete (non-array version) on
49 // BOTH items in the pairs.
50 // NOTE: Like STLDeleteContainerPointers, it is important that this deletes
51 // behind the iterator because if both the key and value are deleted, the
52 // container may call the hash function on the iterator when it is advanced,
53 // which could result in the hash function trying to dereference a stale
54 // pointer.
55 template <class ForwardIterator>
STLDeleteContainerPairPointers(ForwardIterator begin,ForwardIterator end)56 void STLDeleteContainerPairPointers(ForwardIterator begin,
57                                     ForwardIterator end) {
58   while (begin != end) {
59     ForwardIterator temp = begin;
60     ++begin;
61     delete temp->first;
62     delete temp->second;
63   }
64 }
65 
66 // For a range within a container of pairs, calls delete (non-array version) on
67 // the FIRST item in the pairs.
68 // NOTE: Like STLDeleteContainerPointers, deleting behind the iterator.
69 template <class ForwardIterator>
STLDeleteContainerPairFirstPointers(ForwardIterator begin,ForwardIterator end)70 void STLDeleteContainerPairFirstPointers(ForwardIterator begin,
71                                          ForwardIterator end) {
72   while (begin != end) {
73     ForwardIterator temp = begin;
74     ++begin;
75     delete temp->first;
76   }
77 }
78 
79 // For a range within a container of pairs, calls delete.
80 // NOTE: Like STLDeleteContainerPointers, deleting behind the iterator.
81 // Deleting the value does not always invalidate the iterator, but it may
82 // do so if the key is a pointer into the value object.
83 template <class ForwardIterator>
STLDeleteContainerPairSecondPointers(ForwardIterator begin,ForwardIterator end)84 void STLDeleteContainerPairSecondPointers(ForwardIterator begin,
85                                           ForwardIterator end) {
86   while (begin != end) {
87     ForwardIterator temp = begin;
88     ++begin;
89     delete temp->second;
90   }
91 }
92 
93 // Counts the number of instances of val in a container.
94 template <typename Container, typename T>
95 typename std::iterator_traits<
96     typename Container::const_iterator>::difference_type
STLCount(const Container & container,const T & val)97 STLCount(const Container& container, const T& val) {
98   return std::count(container.begin(), container.end(), val);
99 }
100 
101 // Return a mutable char* pointing to a string's internal buffer,
102 // which may not be null-terminated. Writing through this pointer will
103 // modify the string.
104 //
105 // string_as_array(&str)[i] is valid for 0 <= i < str.size() until the
106 // next call to a string method that invalidates iterators.
107 //
108 // As of 2006-04, there is no standard-blessed way of getting a
109 // mutable reference to a string's internal buffer. However, issue 530
110 // (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#530)
111 // proposes this as the method. According to Matt Austern, this should
112 // already work on all current implementations.
string_as_array(std::string * str)113 inline char* string_as_array(std::string* str) {
114   // DO NOT USE const_cast<char*>(str->data())
115   return str->empty() ? NULL : &*str->begin();
116 }
117 
118 // The following functions are useful for cleaning up STL containers whose
119 // elements point to allocated memory.
120 
121 // STLDeleteElements() deletes all the elements in an STL container and clears
122 // the container.  This function is suitable for use with a vector, set,
123 // hash_set, or any other STL container which defines sensible begin(), end(),
124 // and clear() methods.
125 //
126 // If container is NULL, this function is a no-op.
127 //
128 // As an alternative to calling STLDeleteElements() directly, consider
129 // STLElementDeleter (defined below), which ensures that your container's
130 // elements are deleted when the STLElementDeleter goes out of scope.
131 template <class T>
STLDeleteElements(T * container)132 void STLDeleteElements(T* container) {
133   if (!container)
134     return;
135   STLDeleteContainerPointers(container->begin(), container->end());
136   container->clear();
137 }
138 
139 // Given an STL container consisting of (key, value) pairs, STLDeleteValues
140 // deletes all the "value" components and clears the container.  Does nothing
141 // in the case it's given a NULL pointer.
142 template <class T>
STLDeleteValues(T * container)143 void STLDeleteValues(T* container) {
144   if (!container)
145     return;
146   STLDeleteContainerPairSecondPointers(container->begin(), container->end());
147   container->clear();
148 }
149 
150 
151 // The following classes provide a convenient way to delete all elements or
152 // values from STL containers when they goes out of scope.  This greatly
153 // simplifies code that creates temporary objects and has multiple return
154 // statements.  Example:
155 //
156 // vector<MyProto *> tmp_proto;
157 // STLElementDeleter<vector<MyProto *> > d(&tmp_proto);
158 // if (...) return false;
159 // ...
160 // return success;
161 
162 // Given a pointer to an STL container this class will delete all the element
163 // pointers when it goes out of scope.
164 template<class T>
165 class STLElementDeleter {
166  public:
container_(container)167   STLElementDeleter<T>(T* container) : container_(container) {}
168   ~STLElementDeleter<T>() { STLDeleteElements(container_); }
169 
170  private:
171   T* container_;
172 };
173 
174 // Given a pointer to an STL container this class will delete all the value
175 // pointers when it goes out of scope.
176 template<class T>
177 class STLValueDeleter {
178  public:
container_(container)179   STLValueDeleter<T>(T* container) : container_(container) {}
180   ~STLValueDeleter<T>() { STLDeleteValues(container_); }
181 
182  private:
183   T* container_;
184 };
185 
186 // Test to see if a set, map, hash_set or hash_map contains a particular key.
187 // Returns true if the key is in the collection.
188 template <typename Collection, typename Key>
ContainsKey(const Collection & collection,const Key & key)189 bool ContainsKey(const Collection& collection, const Key& key) {
190   return collection.find(key) != collection.end();
191 }
192 
193 // Test to see if a collection like a vector contains a particular value.
194 // Returns true if the value is in the collection.
195 template <typename Collection, typename Value>
ContainsValue(const Collection & collection,const Value & value)196 bool ContainsValue(const Collection& collection, const Value& value) {
197   return std::find(collection.begin(), collection.end(), value) !=
198       collection.end();
199 }
200 
201 namespace base {
202 
203 // Returns true if the container is sorted.
204 template <typename Container>
STLIsSorted(const Container & cont)205 bool STLIsSorted(const Container& cont) {
206   // Note: Use reverse iterator on container to ensure we only require
207   // value_type to implement operator<.
208   return std::adjacent_find(cont.rbegin(), cont.rend(),
209                             std::less<typename Container::value_type>())
210       == cont.rend();
211 }
212 
213 // Returns a new ResultType containing the difference of two sorted containers.
214 template <typename ResultType, typename Arg1, typename Arg2>
STLSetDifference(const Arg1 & a1,const Arg2 & a2)215 ResultType STLSetDifference(const Arg1& a1, const Arg2& a2) {
216   DCHECK(STLIsSorted(a1));
217   DCHECK(STLIsSorted(a2));
218   ResultType difference;
219   std::set_difference(a1.begin(), a1.end(),
220                       a2.begin(), a2.end(),
221                       std::inserter(difference, difference.end()));
222   return difference;
223 }
224 
225 // Returns a new ResultType containing the union of two sorted containers.
226 template <typename ResultType, typename Arg1, typename Arg2>
STLSetUnion(const Arg1 & a1,const Arg2 & a2)227 ResultType STLSetUnion(const Arg1& a1, const Arg2& a2) {
228   DCHECK(STLIsSorted(a1));
229   DCHECK(STLIsSorted(a2));
230   ResultType result;
231   std::set_union(a1.begin(), a1.end(),
232                  a2.begin(), a2.end(),
233                  std::inserter(result, result.end()));
234   return result;
235 }
236 
237 // Returns a new ResultType containing the intersection of two sorted
238 // containers.
239 template <typename ResultType, typename Arg1, typename Arg2>
STLSetIntersection(const Arg1 & a1,const Arg2 & a2)240 ResultType STLSetIntersection(const Arg1& a1, const Arg2& a2) {
241   DCHECK(STLIsSorted(a1));
242   DCHECK(STLIsSorted(a2));
243   ResultType result;
244   std::set_intersection(a1.begin(), a1.end(),
245                         a2.begin(), a2.end(),
246                         std::inserter(result, result.end()));
247   return result;
248 }
249 
250 // Returns true if the sorted container |a1| contains all elements of the sorted
251 // container |a2|.
252 template <typename Arg1, typename Arg2>
STLIncludes(const Arg1 & a1,const Arg2 & a2)253 bool STLIncludes(const Arg1& a1, const Arg2& a2) {
254   DCHECK(STLIsSorted(a1));
255   DCHECK(STLIsSorted(a2));
256   return std::includes(a1.begin(), a1.end(),
257                        a2.begin(), a2.end());
258 }
259 
260 }  // namespace base
261 
262 #endif  // BASE_STL_UTIL_H_
263