blob: 47c0ce1a7009b22686aa07e65556d3c0dbd552b0 [file] [log] [blame]
[email protected]7286e3fc2011-07-19 22:13:241// 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_
[email protected]7286e3fc2011-07-19 22:13:249
[email protected]1dea7572012-12-05 21:40:2710#include <algorithm>
[email protected]7286e3fc2011-07-19 22:13:2411#include <string>
12#include <vector>
13
[email protected]1dea7572012-12-05 21:40:2714#include "base/logging.h"
15
[email protected]6ee951a2012-06-26 17:24:0516// Clears internal memory of an STL object.
[email protected]7286e3fc2011-07-19 22:13:2417// STL clear()/reserve(0) does not always free internal memory allocated
18// This function uses swap/destructor to ensure the internal memory is freed.
[email protected]6ee951a2012-06-26 17:24:0519template<class T>
20void STLClearObject(T* obj) {
[email protected]7286e3fc2011-07-19 22:13:2421 T tmp;
22 tmp.swap(*obj);
23 // Sometimes "T tmp" allocates objects with memory (arena implementation?).
24 // Hence using additional reserve(0) even if it doesn't always work.
25 obj->reserve(0);
26}
27
[email protected]6ee951a2012-06-26 17:24:0528// For a range within a container of pointers, calls delete (non-array version)
29// on these pointers.
[email protected]7286e3fc2011-07-19 22:13:2430// NOTE: for these three functions, we could just implement a DeleteObject
31// functor and then call for_each() on the range and functor, but this
32// requires us to pull in all of algorithm.h, which seems expensive.
33// For hash_[multi]set, it is important that this deletes behind the iterator
34// because the hash_set may call the hash function on the iterator when it is
35// advanced, which could result in the hash function trying to deference a
36// stale pointer.
37template <class ForwardIterator>
38void STLDeleteContainerPointers(ForwardIterator begin, ForwardIterator end) {
39 while (begin != end) {
40 ForwardIterator temp = begin;
41 ++begin;
42 delete *temp;
43 }
44}
45
[email protected]6ee951a2012-06-26 17:24:0546// For a range within a container of pairs, calls delete (non-array version) on
47// BOTH items in the pairs.
[email protected]7286e3fc2011-07-19 22:13:2448// NOTE: Like STLDeleteContainerPointers, it is important that this deletes
49// behind the iterator because if both the key and value are deleted, the
50// container may call the hash function on the iterator when it is advanced,
51// which could result in the hash function trying to dereference a stale
52// pointer.
53template <class ForwardIterator>
54void STLDeleteContainerPairPointers(ForwardIterator begin,
55 ForwardIterator end) {
56 while (begin != end) {
57 ForwardIterator temp = begin;
58 ++begin;
59 delete temp->first;
60 delete temp->second;
61 }
62}
63
[email protected]6ee951a2012-06-26 17:24:0564// For a range within a container of pairs, calls delete (non-array version) on
65// the FIRST item in the pairs.
[email protected]7286e3fc2011-07-19 22:13:2466// NOTE: Like STLDeleteContainerPointers, deleting behind the iterator.
67template <class ForwardIterator>
68void STLDeleteContainerPairFirstPointers(ForwardIterator begin,
69 ForwardIterator end) {
70 while (begin != end) {
71 ForwardIterator temp = begin;
72 ++begin;
73 delete temp->first;
74 }
75}
76
[email protected]6ee951a2012-06-26 17:24:0577// For a range within a container of pairs, calls delete.
[email protected]8b7ddc72011-07-21 08:39:5178// NOTE: Like STLDeleteContainerPointers, deleting behind the iterator.
79// Deleting the value does not always invalidate the iterator, but it may
80// do so if the key is a pointer into the value object.
[email protected]7286e3fc2011-07-19 22:13:2481template <class ForwardIterator>
82void STLDeleteContainerPairSecondPointers(ForwardIterator begin,
83 ForwardIterator end) {
84 while (begin != end) {
[email protected]8b7ddc72011-07-21 08:39:5185 ForwardIterator temp = begin;
[email protected]7286e3fc2011-07-19 22:13:2486 ++begin;
[email protected]8b7ddc72011-07-21 08:39:5187 delete temp->second;
[email protected]7286e3fc2011-07-19 22:13:2488 }
89}
90
91// To treat a possibly-empty vector as an array, use these functions.
92// If you know the array will never be empty, you can use &*v.begin()
[email protected]6ee951a2012-06-26 17:24:0593// directly, but that is undefined behaviour if |v| is empty.
[email protected]7286e3fc2011-07-19 22:13:2494template<typename T>
95inline T* vector_as_array(std::vector<T>* v) {
[email protected]7286e3fc2011-07-19 22:13:2496 return v->empty() ? NULL : &*v->begin();
[email protected]7286e3fc2011-07-19 22:13:2497}
98
99template<typename T>
100inline const T* vector_as_array(const std::vector<T>* v) {
[email protected]7286e3fc2011-07-19 22:13:24101 return v->empty() ? NULL : &*v->begin();
[email protected]7286e3fc2011-07-19 22:13:24102}
103
104// Return a mutable char* pointing to a string's internal buffer,
105// which may not be null-terminated. Writing through this pointer will
106// modify the string.
107//
108// string_as_array(&str)[i] is valid for 0 <= i < str.size() until the
109// next call to a string method that invalidates iterators.
110//
111// As of 2006-04, there is no standard-blessed way of getting a
112// mutable reference to a string's internal buffer. However, issue 530
113// (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#530)
114// proposes this as the method. According to Matt Austern, this should
115// already work on all current implementations.
116inline char* string_as_array(std::string* str) {
117 // DO NOT USE const_cast<char*>(str->data())
118 return str->empty() ? NULL : &*str->begin();
119}
120
[email protected]6ee951a2012-06-26 17:24:05121// The following functions are useful for cleaning up STL containers whose
122// elements point to allocated memory.
[email protected]7286e3fc2011-07-19 22:13:24123
124// STLDeleteElements() deletes all the elements in an STL container and clears
125// the container. This function is suitable for use with a vector, set,
126// hash_set, or any other STL container which defines sensible begin(), end(),
127// and clear() methods.
128//
129// If container is NULL, this function is a no-op.
130//
131// As an alternative to calling STLDeleteElements() directly, consider
132// STLElementDeleter (defined below), which ensures that your container's
133// elements are deleted when the STLElementDeleter goes out of scope.
134template <class T>
[email protected]6ee951a2012-06-26 17:24:05135void STLDeleteElements(T* container) {
136 if (!container)
137 return;
[email protected]7286e3fc2011-07-19 22:13:24138 STLDeleteContainerPointers(container->begin(), container->end());
139 container->clear();
140}
141
142// Given an STL container consisting of (key, value) pairs, STLDeleteValues
143// deletes all the "value" components and clears the container. Does nothing
144// in the case it's given a NULL pointer.
[email protected]7286e3fc2011-07-19 22:13:24145template <class T>
[email protected]6ee951a2012-06-26 17:24:05146void STLDeleteValues(T* container) {
147 if (!container)
148 return;
149 for (typename T::iterator i(container->begin()); i != container->end(); ++i)
[email protected]7286e3fc2011-07-19 22:13:24150 delete i->second;
[email protected]6ee951a2012-06-26 17:24:05151 container->clear();
[email protected]7286e3fc2011-07-19 22:13:24152}
153
154
155// The following classes provide a convenient way to delete all elements or
156// values from STL containers when they goes out of scope. This greatly
157// simplifies code that creates temporary objects and has multiple return
158// statements. Example:
159//
160// vector<MyProto *> tmp_proto;
161// STLElementDeleter<vector<MyProto *> > d(&tmp_proto);
162// if (...) return false;
163// ...
164// return success;
165
166// Given a pointer to an STL container this class will delete all the element
167// pointers when it goes out of scope.
[email protected]6ee951a2012-06-26 17:24:05168template<class T>
169class STLElementDeleter {
[email protected]7286e3fc2011-07-19 22:13:24170 public:
[email protected]6ee951a2012-06-26 17:24:05171 STLElementDeleter<T>(T* container) : container_(container) {}
172 ~STLElementDeleter<T>() { STLDeleteElements(container_); }
173
[email protected]7286e3fc2011-07-19 22:13:24174 private:
[email protected]6ee951a2012-06-26 17:24:05175 T* container_;
[email protected]7286e3fc2011-07-19 22:13:24176};
177
178// Given a pointer to an STL container this class will delete all the value
179// pointers when it goes out of scope.
[email protected]6ee951a2012-06-26 17:24:05180template<class T>
181class STLValueDeleter {
[email protected]7286e3fc2011-07-19 22:13:24182 public:
[email protected]6ee951a2012-06-26 17:24:05183 STLValueDeleter<T>(T* container) : container_(container) {}
184 ~STLValueDeleter<T>() { STLDeleteValues(container_); }
185
[email protected]7286e3fc2011-07-19 22:13:24186 private:
[email protected]6ee951a2012-06-26 17:24:05187 T* container_;
[email protected]7286e3fc2011-07-19 22:13:24188};
189
190// Test to see if a set, map, hash_set or hash_map contains a particular key.
191// Returns true if the key is in the collection.
192template <typename Collection, typename Key>
193bool ContainsKey(const Collection& collection, const Key& key) {
194 return collection.find(key) != collection.end();
195}
196
[email protected]1dea7572012-12-05 21:40:27197namespace base {
198
199// Returns true if the container is sorted.
200template <typename Container>
201bool STLIsSorted(const Container& cont) {
202 return std::adjacent_find(cont.begin(), cont.end(),
203 std::greater<typename Container::value_type>())
204 == cont.end();
205}
206
207// Returns a new ResultType containing the difference of two sorted containers.
208template <typename ResultType, typename Arg1, typename Arg2>
209ResultType STLSetDifference(const Arg1& a1, const Arg2& a2) {
210 DCHECK(STLIsSorted(a1));
211 DCHECK(STLIsSorted(a2));
212 ResultType difference;
213 std::set_difference(a1.begin(), a1.end(),
214 a2.begin(), a2.end(),
215 std::inserter(difference, difference.end()));
216 return difference;
217}
218
219} // namespace base
220
[email protected]7286e3fc2011-07-19 22:13:24221#endif // BASE_STL_UTIL_H_