stl_util-inl.h (14740B)
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. 6 7 // STL utility functions. Usually, these replace built-in, but slow(!), 8 // STL functions with more efficient versions. 9 10 #ifndef BASE_STL_UTIL_INL_H_ 11 #define BASE_STL_UTIL_INL_H_ 12 13 #include <string.h> // for memcpy 14 #include <functional> 15 #include <set> 16 #include <string> 17 #include <vector> 18 #include <cassert> 19 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. 23 template <class T> 24 void STLClearObject(T* obj) { 25 T tmp; 26 tmp.swap(*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 30 } 31 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. 34 template <class T> 35 inline void STLClearIfBig(T* obj, size_t limit = 1 << 20) { 36 if (obj->capacity() >= limit) { 37 STLClearObject(obj); 38 } else { 39 obj->clear(); 40 } 41 } 42 43 // Reserve space for STL object. 44 // STL's reserve() will always copy. 45 // This function avoid the copy if we already have capacity 46 template <class T> 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); 52 } 53 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 63 // stale pointer. 64 template <class ForwardIterator> 65 void STLDeleteContainerPointers(ForwardIterator begin, ForwardIterator end) { 66 while (begin != end) { 67 ForwardIterator temp = begin; 68 ++begin; 69 delete *temp; 70 } 71 } 72 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 80 // pointer. 81 template <class ForwardIterator> 82 void STLDeleteContainerPairPointers(ForwardIterator begin, 83 ForwardIterator end) { 84 while (begin != end) { 85 ForwardIterator temp = begin; 86 ++begin; 87 delete temp->first; 88 delete temp->second; 89 } 90 } 91 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; 101 ++begin; 102 delete temp->first; 103 } 104 } 105 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; 114 ++begin; 115 } 116 } 117 118 template <typename T> 119 inline void STLAssignToVector(std::vector<T>* vec, const T* ptr, size_t n) { 120 vec->resize(n); 121 memcpy(&vec->front(), ptr, n * sizeof(T)); 122 } 123 124 /***** Hack to allow faster assignment to a vector *****/ 125 126 // This routine speeds up an assignment of 32 bytes to a vector from 127 // about 250 cycles per assignment to about 140 cycles. 128 // 129 // Usage: 130 // STLAssignToVectorChar(&vec, ptr, size); 131 // STLAssignToString(&str, ptr, size); 132 133 inline void STLAssignToVectorChar(std::vector<char>* vec, const char* ptr, 134 size_t n) { 135 STLAssignToVector(vec, ptr, n); 136 } 137 138 inline void STLAssignToString(std::string* str, const char* ptr, size_t n) { 139 str->resize(n); 140 memcpy(&*str->begin(), ptr, n); 141 } 142 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. 151 152 template <typename T> 153 inline T* vector_as_array(std::vector<T>* v) { 154 #ifdef NDEBUG 155 return &*v->begin(); 156 #else 157 return v->empty() ? NULL : &*v->begin(); 158 #endif 159 } 160 161 template <typename T> 162 inline const T* vector_as_array(const std::vector<T>* v) { 163 #ifdef NDEBUG 164 return &*v->begin(); 165 #else 166 return v->empty() ? NULL : &*v->begin(); 167 #endif 168 } 169 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. 173 // 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. 176 // 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(); 185 } 186 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 191 // differed. 192 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(); 197 ++i) { 198 if (set_b.find(*i) == set_b.end()) return false; 199 } 200 return true; 201 } 202 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(); 207 ++i) { 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; 211 } 212 return true; 213 } 214 215 // The following functions are useful for cleaning up STL containers 216 // whose elements point to allocated memory. 217 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. 222 // 223 // If container is NULL, this function is a no-op. 224 // 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. 228 template <class T> 229 void STLDeleteElements(T* container) { 230 if (!container) return; 231 STLDeleteContainerPointers(container->begin(), container->end()); 232 container->clear(); 233 } 234 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. 238 239 template <class T> 240 void STLDeleteValues(T* v) { 241 if (!v) return; 242 for (typename T::iterator i = v->begin(); i != v->end(); ++i) { 243 delete i->second; 244 } 245 v->clear(); 246 } 247 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: 252 // 253 // vector<MyProto *> tmp_proto; 254 // STLElementDeleter<vector<MyProto *> > d(&tmp_proto); 255 // if (...) return false; 256 // ... 257 // return success; 258 259 // Given a pointer to an STL container this class will delete all the element 260 // pointers when it goes out of scope. 261 262 template <class STLContainer> 263 class STLElementDeleter { 264 public: 265 explicit STLElementDeleter(STLContainer* ptr) : container_ptr_(ptr) {} 266 ~STLElementDeleter() { STLDeleteElements(container_ptr_); } 267 268 private: 269 STLContainer* container_ptr_; 270 }; 271 272 // Given a pointer to an STL container this class will delete all the value 273 // pointers when it goes out of scope. 274 275 template <class STLContainer> 276 class STLValueDeleter { 277 public: 278 explicit STLValueDeleter(STLContainer* ptr) : container_ptr_(ptr) {} 279 ~STLValueDeleter() { STLDeleteValues(container_ptr_); } 280 281 private: 282 STLContainer* container_ptr_; 283 }; 284 285 // Forward declare some callback classes in callback.h for STLBinaryFunction 286 template <class R, class T1, class T2> 287 class ResultCallback2; 288 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>. 292 // 293 // The client should create callback with NewPermanentCallback, and should 294 // delete callback after it is done using the STLBinaryFunction. 295 296 template <class Result, class Arg1, class Arg2> 297 class STLBinaryFunction : public std::binary_function<Arg1, Arg2, Result> { 298 public: 299 typedef ResultCallback2<Result, Arg1, Arg2> Callback; 300 301 explicit STLBinaryFunction(Callback* callback) : callback_(callback) { 302 assert(callback_); 303 } 304 305 Result operator()(Arg1 arg1, Arg2 arg2) { return callback_->Run(arg1, arg2); } 306 307 private: 308 Callback* callback_; 309 }; 310 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 314 // lower_bound(). 315 // 316 // templated typedefs are not supported, so instead we use inheritance. 317 318 template <class Arg> 319 class STLBinaryPredicate : public STLBinaryFunction<bool, Arg, Arg> { 320 public: 321 typedef typename STLBinaryPredicate<Arg>::Callback Callback; 322 explicit STLBinaryPredicate(Callback* callback) 323 : STLBinaryFunction<bool, Arg, Arg>(callback) {} 324 }; 325 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: 331 // 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)) 336 // 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. 339 340 template <typename Pair, typename UnaryOp> 341 class UnaryOperateOnFirst 342 : public std::unary_function<Pair, typename UnaryOp::result_type> { 343 public: 344 UnaryOperateOnFirst() {} 345 346 explicit UnaryOperateOnFirst(const UnaryOp& f) : f_(f) {} 347 348 typename UnaryOp::result_type operator()(const Pair& p) const { 349 return f_(p.first); 350 } 351 352 private: 353 UnaryOp f_; 354 }; 355 356 template <typename Pair, typename UnaryOp> 357 UnaryOperateOnFirst<Pair, UnaryOp> UnaryOperate1st(const UnaryOp& f) { 358 return UnaryOperateOnFirst<Pair, UnaryOp>(f); 359 } 360 361 template <typename Pair, typename UnaryOp> 362 class UnaryOperateOnSecond 363 : public std::unary_function<Pair, typename UnaryOp::result_type> { 364 public: 365 UnaryOperateOnSecond() {} 366 367 explicit UnaryOperateOnSecond(const UnaryOp& f) : f_(f) {} 368 369 typename UnaryOp::result_type operator()(const Pair& p) const { 370 return f_(p.second); 371 } 372 373 private: 374 UnaryOp f_; 375 }; 376 377 template <typename Pair, typename UnaryOp> 378 UnaryOperateOnSecond<Pair, UnaryOp> UnaryOperate2nd(const UnaryOp& f) { 379 return UnaryOperateOnSecond<Pair, UnaryOp>(f); 380 } 381 382 template <typename Pair, typename BinaryOp> 383 class BinaryOperateOnFirst 384 : public std::binary_function<Pair, Pair, typename BinaryOp::result_type> { 385 public: 386 BinaryOperateOnFirst() {} 387 388 explicit BinaryOperateOnFirst(const BinaryOp& f) : f_(f) {} 389 390 typename BinaryOp::result_type operator()(const Pair& p1, 391 const Pair& p2) const { 392 return f_(p1.first, p2.first); 393 } 394 395 private: 396 BinaryOp f_; 397 }; 398 399 template <typename Pair, typename BinaryOp> 400 BinaryOperateOnFirst<Pair, BinaryOp> BinaryOperate1st(const BinaryOp& f) { 401 return BinaryOperateOnFirst<Pair, BinaryOp>(f); 402 } 403 404 template <typename Pair, typename BinaryOp> 405 class BinaryOperateOnSecond 406 : public std::binary_function<Pair, Pair, typename BinaryOp::result_type> { 407 public: 408 BinaryOperateOnSecond() {} 409 410 explicit BinaryOperateOnSecond(const BinaryOp& f) : f_(f) {} 411 412 typename BinaryOp::result_type operator()(const Pair& p1, 413 const Pair& p2) const { 414 return f_(p1.second, p2.second); 415 } 416 417 private: 418 BinaryOp f_; 419 }; 420 421 template <typename Pair, typename BinaryOp> 422 BinaryOperateOnSecond<Pair, BinaryOp> BinaryOperate2nd(const BinaryOp& f) { 423 return BinaryOperateOnSecond<Pair, BinaryOp>(f); 424 } 425 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()); 432 return result; 433 } 434 435 #endif // BASE_STL_UTIL_INL_H_