1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style license that can be
5 // found in the LICENSE file.
7 // STL utility functions. Usually, these replace built-in, but slow(!),
8 // STL functions with more efficient versions.
10 #ifndef BASE_STL_UTIL_INL_H_
11 #define BASE_STL_UTIL_INL_H_
13 #include <string.h> // for memcpy
20 // Clear internal memory of an STL object.
21 // STL clear()/reserve(0) does not always free internal memory allocated
22 // This function uses swap/destructor to ensure the internal memory is freed.
24 void STLClearObject(T
* obj
) {
27 obj
->reserve(0); // this is because sometimes "T tmp" allocates objects with
28 // memory (arena implementation?). use reserve()
29 // to clear() even if it doesn't always work
32 // Reduce memory usage on behalf of object if it is using more than
33 // "bytes" bytes of space. By default, we clear objects over 1MB.
35 inline void STLClearIfBig(T
* obj
, size_t limit
= 1 << 20) {
36 if (obj
->capacity() >= limit
) {
43 // Reserve space for STL object.
44 // STL's reserve() will always copy.
45 // This function avoid the copy if we already have capacity
47 void STLReserveIfNeeded(T
* obj
, int new_size
) {
48 if (obj
->capacity() < new_size
) // increase capacity
49 obj
->reserve(new_size
);
50 else if (obj
->size() > new_size
) // reduce size
51 obj
->resize(new_size
);
54 // STLDeleteContainerPointers()
55 // For a range within a container of pointers, calls delete
56 // (non-array version) on these pointers.
57 // NOTE: for these three functions, we could just implement a DeleteObject
58 // functor and then call for_each() on the range and functor, but this
59 // requires us to pull in all of algorithm.h, which seems expensive.
60 // For hash_[multi]set, it is important that this deletes behind the iterator
61 // because the hash_set may call the hash function on the iterator when it is
62 // advanced, which could result in the hash function trying to deference a
64 template <class ForwardIterator
>
65 void STLDeleteContainerPointers(ForwardIterator begin
, ForwardIterator end
) {
66 while (begin
!= end
) {
67 ForwardIterator temp
= begin
;
73 // STLDeleteContainerPairPointers()
74 // For a range within a container of pairs, calls delete
75 // (non-array version) on BOTH items in the pairs.
76 // NOTE: Like STLDeleteContainerPointers, it is important that this deletes
77 // behind the iterator because if both the key and value are deleted, the
78 // container may call the hash function on the iterator when it is advanced,
79 // which could result in the hash function trying to dereference a stale
81 template <class ForwardIterator
>
82 void STLDeleteContainerPairPointers(ForwardIterator begin
,
83 ForwardIterator end
) {
84 while (begin
!= end
) {
85 ForwardIterator temp
= begin
;
92 // STLDeleteContainerPairFirstPointers()
93 // For a range within a container of pairs, calls delete (non-array version)
94 // on the FIRST item in the pairs.
95 // NOTE: Like STLDeleteContainerPointers, deleting behind the iterator.
96 template <class ForwardIterator
>
97 void STLDeleteContainerPairFirstPointers(ForwardIterator begin
,
98 ForwardIterator end
) {
99 while (begin
!= end
) {
100 ForwardIterator temp
= begin
;
106 // STLDeleteContainerPairSecondPointers()
107 // For a range within a container of pairs, calls delete
108 // (non-array version) on the SECOND item in the pairs.
109 template <class ForwardIterator
>
110 void STLDeleteContainerPairSecondPointers(ForwardIterator begin
,
111 ForwardIterator end
) {
112 while (begin
!= end
) {
113 delete begin
->second
;
118 template <typename T
>
119 inline void STLAssignToVector(std::vector
<T
>* vec
, const T
* ptr
, size_t n
) {
121 memcpy(&vec
->front(), ptr
, n
* sizeof(T
));
124 /***** Hack to allow faster assignment to a vector *****/
126 // This routine speeds up an assignment of 32 bytes to a vector from
127 // about 250 cycles per assignment to about 140 cycles.
130 // STLAssignToVectorChar(&vec, ptr, size);
131 // STLAssignToString(&str, ptr, size);
133 inline void STLAssignToVectorChar(std::vector
<char>* vec
, const char* ptr
,
135 STLAssignToVector(vec
, ptr
, n
);
138 inline void STLAssignToString(std::string
* str
, const char* ptr
, size_t n
) {
140 memcpy(&*str
->begin(), ptr
, n
);
143 // To treat a possibly-empty vector as an array, use these functions.
144 // If you know the array will never be empty, you can use &*v.begin()
145 // directly, but that is allowed to dump core if v is empty. This
146 // function is the most efficient code that will work, taking into
147 // account how our STL is actually implemented. THIS IS NON-PORTABLE
148 // CODE, so call us instead of repeating the nonportable code
149 // everywhere. If our STL implementation changes, we will need to
150 // change this as well.
152 template <typename T
>
153 inline T
* vector_as_array(std::vector
<T
>* v
) {
157 return v
->empty() ? NULL
: &*v
->begin();
161 template <typename T
>
162 inline const T
* vector_as_array(const std::vector
<T
>* v
) {
166 return v
->empty() ? NULL
: &*v
->begin();
170 // Return a mutable char* pointing to a string's internal buffer,
171 // which may not be null-terminated. Writing through this pointer will
172 // modify the string.
174 // string_as_array(&str)[i] is valid for 0 <= i < str.size() until the
175 // next call to a string method that invalidates iterators.
177 // As of 2006-04, there is no standard-blessed way of getting a
178 // mutable reference to a string's internal buffer. However, issue 530
179 // (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#530)
180 // proposes this as the method. According to Matt Austern, this should
181 // already work on all current implementations.
182 inline char* string_as_array(std::string
* str
) {
183 // DO NOT USE const_cast<char*>(str->data())! See the unittest for why.
184 return str
->empty() ? NULL
: &*str
->begin();
187 // These are methods that test two hash maps/sets for equality. These exist
188 // because the == operator in the STL can return false when the maps/sets
189 // contain identical elements. This is because it compares the internal hash
190 // tables which may be different if the order of insertions and deletions
193 template <class HashSet
>
194 inline bool HashSetEquality(const HashSet
& set_a
, const HashSet
& set_b
) {
195 if (set_a
.size() != set_b
.size()) return false;
196 for (typename
HashSet::const_iterator i
= set_a
.begin(); i
!= set_a
.end();
198 if (set_b
.find(*i
) == set_b
.end()) return false;
203 template <class HashMap
>
204 inline bool HashMapEquality(const HashMap
& map_a
, const HashMap
& map_b
) {
205 if (map_a
.size() != map_b
.size()) return false;
206 for (typename
HashMap::const_iterator i
= map_a
.begin(); i
!= map_a
.end();
208 typename
HashMap::const_iterator j
= map_b
.find(i
->first
);
209 if (j
== map_b
.end()) return false;
210 if (i
->second
!= j
->second
) return false;
215 // The following functions are useful for cleaning up STL containers
216 // whose elements point to allocated memory.
218 // STLDeleteElements() deletes all the elements in an STL container and clears
219 // the container. This function is suitable for use with a vector, set,
220 // hash_set, or any other STL container which defines sensible begin(), end(),
221 // and clear() methods.
223 // If container is NULL, this function is a no-op.
225 // As an alternative to calling STLDeleteElements() directly, consider
226 // STLElementDeleter (defined below), which ensures that your container's
227 // elements are deleted when the STLElementDeleter goes out of scope.
229 void STLDeleteElements(T
* container
) {
230 if (!container
) return;
231 STLDeleteContainerPointers(container
->begin(), container
->end());
235 // Given an STL container consisting of (key, value) pairs, STLDeleteValues
236 // deletes all the "value" components and clears the container. Does nothing
237 // in the case it's given a NULL pointer.
240 void STLDeleteValues(T
* v
) {
242 for (typename
T::iterator i
= v
->begin(); i
!= v
->end(); ++i
) {
248 // The following classes provide a convenient way to delete all elements or
249 // values from STL containers when they goes out of scope. This greatly
250 // simplifies code that creates temporary objects and has multiple return
251 // statements. Example:
253 // vector<MyProto *> tmp_proto;
254 // STLElementDeleter<vector<MyProto *> > d(&tmp_proto);
255 // if (...) return false;
259 // Given a pointer to an STL container this class will delete all the element
260 // pointers when it goes out of scope.
262 template <class STLContainer
>
263 class STLElementDeleter
{
265 explicit STLElementDeleter(STLContainer
* ptr
) : container_ptr_(ptr
) {}
266 ~STLElementDeleter() { STLDeleteElements(container_ptr_
); }
269 STLContainer
* container_ptr_
;
272 // Given a pointer to an STL container this class will delete all the value
273 // pointers when it goes out of scope.
275 template <class STLContainer
>
276 class STLValueDeleter
{
278 explicit STLValueDeleter(STLContainer
* ptr
) : container_ptr_(ptr
) {}
279 ~STLValueDeleter() { STLDeleteValues(container_ptr_
); }
282 STLContainer
* container_ptr_
;
285 // Forward declare some callback classes in callback.h for STLBinaryFunction
286 template <class R
, class T1
, class T2
>
287 class ResultCallback2
;
289 // STLBinaryFunction is a wrapper for the ResultCallback2 class in callback.h
290 // It provides an operator () method instead of a Run method, so it may be
291 // passed to STL functions in <algorithm>.
293 // The client should create callback with NewPermanentCallback, and should
294 // delete callback after it is done using the STLBinaryFunction.
296 template <class Result
, class Arg1
, class Arg2
>
297 class STLBinaryFunction
: public std::binary_function
<Arg1
, Arg2
, Result
> {
299 typedef ResultCallback2
<Result
, Arg1
, Arg2
> Callback
;
301 explicit STLBinaryFunction(Callback
* callback
) : callback_(callback
) {
305 Result
operator()(Arg1 arg1
, Arg2 arg2
) { return callback_
->Run(arg1
, arg2
); }
311 // STLBinaryPredicate is a specialized version of STLBinaryFunction, where the
312 // return type is bool and both arguments have type Arg. It can be used
313 // wherever STL requires a StrictWeakOrdering, such as in sort() or
316 // templated typedefs are not supported, so instead we use inheritance.
319 class STLBinaryPredicate
: public STLBinaryFunction
<bool, Arg
, Arg
> {
321 typedef typename STLBinaryPredicate
<Arg
>::Callback Callback
;
322 explicit STLBinaryPredicate(Callback
* callback
)
323 : STLBinaryFunction
<bool, Arg
, Arg
>(callback
) {}
326 // Functors that compose arbitrary unary and binary functions with a
327 // function that "projects" one of the members of a pair.
328 // Specifically, if p1 and p2, respectively, are the functions that
329 // map a pair to its first and second, respectively, members, the
330 // table below summarizes the functions that can be constructed:
332 // * UnaryOperate1st<pair>(f) returns the function x -> f(p1(x))
333 // * UnaryOperate2nd<pair>(f) returns the function x -> f(p2(x))
334 // * BinaryOperate1st<pair>(f) returns the function (x,y) -> f(p1(x),p1(y))
335 // * BinaryOperate2nd<pair>(f) returns the function (x,y) -> f(p2(x),p2(y))
337 // A typical usage for these functions would be when iterating over
338 // the contents of an STL map. For other sample usage, see the unittest.
340 template <typename Pair
, typename UnaryOp
>
341 class UnaryOperateOnFirst
342 : public std::unary_function
<Pair
, typename
UnaryOp::result_type
> {
344 UnaryOperateOnFirst() {}
346 explicit UnaryOperateOnFirst(const UnaryOp
& f
) : f_(f
) {}
348 typename
UnaryOp::result_type
operator()(const Pair
& p
) const {
356 template <typename Pair
, typename UnaryOp
>
357 UnaryOperateOnFirst
<Pair
, UnaryOp
> UnaryOperate1st(const UnaryOp
& f
) {
358 return UnaryOperateOnFirst
<Pair
, UnaryOp
>(f
);
361 template <typename Pair
, typename UnaryOp
>
362 class UnaryOperateOnSecond
363 : public std::unary_function
<Pair
, typename
UnaryOp::result_type
> {
365 UnaryOperateOnSecond() {}
367 explicit UnaryOperateOnSecond(const UnaryOp
& f
) : f_(f
) {}
369 typename
UnaryOp::result_type
operator()(const Pair
& p
) const {
377 template <typename Pair
, typename UnaryOp
>
378 UnaryOperateOnSecond
<Pair
, UnaryOp
> UnaryOperate2nd(const UnaryOp
& f
) {
379 return UnaryOperateOnSecond
<Pair
, UnaryOp
>(f
);
382 template <typename Pair
, typename BinaryOp
>
383 class BinaryOperateOnFirst
384 : public std::binary_function
<Pair
, Pair
, typename
BinaryOp::result_type
> {
386 BinaryOperateOnFirst() {}
388 explicit BinaryOperateOnFirst(const BinaryOp
& f
) : f_(f
) {}
390 typename
BinaryOp::result_type
operator()(const Pair
& p1
,
391 const Pair
& p2
) const {
392 return f_(p1
.first
, p2
.first
);
399 template <typename Pair
, typename BinaryOp
>
400 BinaryOperateOnFirst
<Pair
, BinaryOp
> BinaryOperate1st(const BinaryOp
& f
) {
401 return BinaryOperateOnFirst
<Pair
, BinaryOp
>(f
);
404 template <typename Pair
, typename BinaryOp
>
405 class BinaryOperateOnSecond
406 : public std::binary_function
<Pair
, Pair
, typename
BinaryOp::result_type
> {
408 BinaryOperateOnSecond() {}
410 explicit BinaryOperateOnSecond(const BinaryOp
& f
) : f_(f
) {}
412 typename
BinaryOp::result_type
operator()(const Pair
& p1
,
413 const Pair
& p2
) const {
414 return f_(p1
.second
, p2
.second
);
421 template <typename Pair
, typename BinaryOp
>
422 BinaryOperateOnSecond
<Pair
, BinaryOp
> BinaryOperate2nd(const BinaryOp
& f
) {
423 return BinaryOperateOnSecond
<Pair
, BinaryOp
>(f
);
426 // Translates a set into a vector.
427 template <typename T
>
428 std::vector
<T
> SetToVector(const std::set
<T
>& values
) {
429 std::vector
<T
> result
;
430 result
.reserve(values
.size());
431 result
.insert(result
.begin(), values
.begin(), values
.end());
435 #endif // BASE_STL_UTIL_INL_H_