WebKit roll 98705:98715
[chromium-blink-merge.git] / base / stl_util.h
blobaf77150f6b3a83d6d8081b7182492c0a7c021ac4
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.
5 // Derived from google3/util/gtl/stl_util.h
7 #ifndef BASE_STL_UTIL_H_
8 #define BASE_STL_UTIL_H_
9 #pragma once
11 #include <string>
12 #include <vector>
14 // Clear internal memory of an STL object.
15 // STL clear()/reserve(0) does not always free internal memory allocated
16 // This function uses swap/destructor to ensure the internal memory is freed.
17 template<class T> void STLClearObject(T* obj) {
18 T tmp;
19 tmp.swap(*obj);
20 // Sometimes "T tmp" allocates objects with memory (arena implementation?).
21 // Hence using additional reserve(0) even if it doesn't always work.
22 obj->reserve(0);
25 // STLDeleteContainerPointers()
26 // For a range within a container of pointers, calls delete
27 // (non-array version) on these pointers.
28 // NOTE: for these three functions, we could just implement a DeleteObject
29 // functor and then call for_each() on the range and functor, but this
30 // requires us to pull in all of algorithm.h, which seems expensive.
31 // For hash_[multi]set, it is important that this deletes behind the iterator
32 // because the hash_set may call the hash function on the iterator when it is
33 // advanced, which could result in the hash function trying to deference a
34 // stale pointer.
35 template <class ForwardIterator>
36 void STLDeleteContainerPointers(ForwardIterator begin, ForwardIterator end) {
37 while (begin != end) {
38 ForwardIterator temp = begin;
39 ++begin;
40 delete *temp;
44 // STLDeleteContainerPairPointers()
45 // For a range within a container of pairs, calls delete
46 // (non-array version) on BOTH items in the pairs.
47 // NOTE: Like STLDeleteContainerPointers, it is important that this deletes
48 // behind the iterator because if both the key and value are deleted, the
49 // container may call the hash function on the iterator when it is advanced,
50 // which could result in the hash function trying to dereference a stale
51 // pointer.
52 template <class ForwardIterator>
53 void STLDeleteContainerPairPointers(ForwardIterator begin,
54 ForwardIterator end) {
55 while (begin != end) {
56 ForwardIterator temp = begin;
57 ++begin;
58 delete temp->first;
59 delete temp->second;
63 // STLDeleteContainerPairFirstPointers()
64 // For a range within a container of pairs, calls delete (non-array version)
65 // on the FIRST item in the pairs.
66 // NOTE: Like STLDeleteContainerPointers, deleting behind the iterator.
67 template <class ForwardIterator>
68 void STLDeleteContainerPairFirstPointers(ForwardIterator begin,
69 ForwardIterator end) {
70 while (begin != end) {
71 ForwardIterator temp = begin;
72 ++begin;
73 delete temp->first;
77 // STLDeleteContainerPairSecondPointers()
78 // For a range within a container of pairs, calls delete
79 // NOTE: Like STLDeleteContainerPointers, deleting behind the iterator.
80 // Deleting the value does not always invalidate the iterator, but it may
81 // do so if the key is a pointer into the value object.
82 // (non-array version) on the SECOND item in the pairs.
83 template <class ForwardIterator>
84 void STLDeleteContainerPairSecondPointers(ForwardIterator begin,
85 ForwardIterator end) {
86 while (begin != end) {
87 ForwardIterator temp = begin;
88 ++begin;
89 delete temp->second;
93 // To treat a possibly-empty vector as an array, use these functions.
94 // If you know the array will never be empty, you can use &*v.begin()
95 // directly, but that is undefined behaviour if v is empty.
97 template<typename T>
98 inline T* vector_as_array(std::vector<T>* v) {
99 return v->empty() ? NULL : &*v->begin();
102 template<typename T>
103 inline const T* vector_as_array(const std::vector<T>* v) {
104 return v->empty() ? NULL : &*v->begin();
107 // Return a mutable char* pointing to a string's internal buffer,
108 // which may not be null-terminated. Writing through this pointer will
109 // modify the string.
111 // string_as_array(&str)[i] is valid for 0 <= i < str.size() until the
112 // next call to a string method that invalidates iterators.
114 // As of 2006-04, there is no standard-blessed way of getting a
115 // mutable reference to a string's internal buffer. However, issue 530
116 // (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#530)
117 // proposes this as the method. According to Matt Austern, this should
118 // already work on all current implementations.
119 inline char* string_as_array(std::string* str) {
120 // DO NOT USE const_cast<char*>(str->data())
121 return str->empty() ? NULL : &*str->begin();
124 // The following functions are useful for cleaning up STL containers
125 // whose elements point to allocated memory.
127 // STLDeleteElements() deletes all the elements in an STL container and clears
128 // the container. This function is suitable for use with a vector, set,
129 // hash_set, or any other STL container which defines sensible begin(), end(),
130 // and clear() methods.
132 // If container is NULL, this function is a no-op.
134 // As an alternative to calling STLDeleteElements() directly, consider
135 // STLElementDeleter (defined below), which ensures that your container's
136 // elements are deleted when the STLElementDeleter goes out of scope.
137 template <class T>
138 void STLDeleteElements(T *container) {
139 if (!container) return;
140 STLDeleteContainerPointers(container->begin(), container->end());
141 container->clear();
144 // Given an STL container consisting of (key, value) pairs, STLDeleteValues
145 // deletes all the "value" components and clears the container. Does nothing
146 // in the case it's given a NULL pointer.
148 template <class T>
149 void STLDeleteValues(T *v) {
150 if (!v) return;
151 for (typename T::iterator i = v->begin(); i != v->end(); ++i) {
152 delete i->second;
154 v->clear();
158 // The following classes provide a convenient way to delete all elements or
159 // values from STL containers when they goes out of scope. This greatly
160 // simplifies code that creates temporary objects and has multiple return
161 // statements. Example:
163 // vector<MyProto *> tmp_proto;
164 // STLElementDeleter<vector<MyProto *> > d(&tmp_proto);
165 // if (...) return false;
166 // ...
167 // return success;
169 // Given a pointer to an STL container this class will delete all the element
170 // pointers when it goes out of scope.
172 template<class STLContainer> class STLElementDeleter {
173 public:
174 STLElementDeleter<STLContainer>(STLContainer *ptr) : container_ptr_(ptr) {}
175 ~STLElementDeleter<STLContainer>() { STLDeleteElements(container_ptr_); }
176 private:
177 STLContainer *container_ptr_;
180 // Given a pointer to an STL container this class will delete all the value
181 // pointers when it goes out of scope.
183 template<class STLContainer> class STLValueDeleter {
184 public:
185 STLValueDeleter<STLContainer>(STLContainer *ptr) : container_ptr_(ptr) {}
186 ~STLValueDeleter<STLContainer>() { STLDeleteValues(container_ptr_); }
187 private:
188 STLContainer *container_ptr_;
191 // Test to see if a set, map, hash_set or hash_map contains a particular key.
192 // Returns true if the key is in the collection.
193 template <typename Collection, typename Key>
194 bool ContainsKey(const Collection& collection, const Key& key) {
195 return collection.find(key) != collection.end();
198 #endif // BASE_STL_UTIL_H_