| OLD | NEW |
| (Empty) |
| 1 // | |
| 2 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. | |
| 3 // Use of this source code is governed by a BSD-style license that can be | |
| 4 // found in the LICENSE file. | |
| 5 // | |
| 6 // STL utility functions. Usually, these replace built-in, but slow(!), | |
| 7 // STL functions with more efficient versions. | |
| 8 // | |
| 9 | |
| 10 #ifndef CHROME_COMMON_STL_UTIL_INL_H__ | |
| 11 #define CHROME_COMMON_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> void STLClearObject(T* obj) { | |
| 24 T tmp; | |
| 25 tmp.swap(*obj); | |
| 26 obj->reserve(0); // this is because sometimes "T tmp" allocates objects with | |
| 27 // memory (arena implementation?). use reserve() | |
| 28 // to clear() even if it doesn't always work | |
| 29 } | |
| 30 | |
| 31 // Reduce memory usage on behalf of object if it is using more than | |
| 32 // "bytes" bytes of space. By default, we clear objects over 1MB. | |
| 33 template <class T> inline void STLClearIfBig(T* obj, size_t limit = 1<<20) { | |
| 34 if (obj->capacity() >= limit) { | |
| 35 STLClearObject(obj); | |
| 36 } else { | |
| 37 obj->clear(); | |
| 38 } | |
| 39 } | |
| 40 | |
| 41 // Reserve space for STL object. | |
| 42 // STL's reserve() will always copy. | |
| 43 // This function avoid the copy if we already have capacity | |
| 44 template<class T> void STLReserveIfNeeded(T* obj, int new_size) { | |
| 45 if (obj->capacity() < new_size) // increase capacity | |
| 46 obj->reserve(new_size); | |
| 47 else if (obj->size() > new_size) // reduce size | |
| 48 obj->resize(new_size); | |
| 49 } | |
| 50 | |
| 51 // STLDeleteContainerPointers() | |
| 52 // For a range within a container of pointers, calls delete | |
| 53 // (non-array version) on these pointers. | |
| 54 // NOTE: for these three functions, we could just implement a DeleteObject | |
| 55 // functor and then call for_each() on the range and functor, but this | |
| 56 // requires us to pull in all of algorithm.h, which seems expensive. | |
| 57 // For hash_[multi]set, it is important that this deletes behind the iterator | |
| 58 // because the hash_set may call the hash function on the iterator when it is | |
| 59 // advanced, which could result in the hash function trying to deference a | |
| 60 // stale pointer. | |
| 61 template <class ForwardIterator> | |
| 62 void STLDeleteContainerPointers(ForwardIterator begin, | |
| 63 ForwardIterator end) { | |
| 64 while (begin != end) { | |
| 65 ForwardIterator temp = begin; | |
| 66 ++begin; | |
| 67 delete *temp; | |
| 68 } | |
| 69 } | |
| 70 | |
| 71 // STLDeleteContainerPairPointers() | |
| 72 // For a range within a container of pairs, calls delete | |
| 73 // (non-array version) on BOTH items in the pairs. | |
| 74 // NOTE: Like STLDeleteContainerPointers, it is important that this deletes | |
| 75 // behind the iterator because if both the key and value are deleted, the | |
| 76 // container may call the hash function on the iterator when it is advanced, | |
| 77 // which could result in the hash function trying to dereference a stale | |
| 78 // pointer. | |
| 79 template <class ForwardIterator> | |
| 80 void STLDeleteContainerPairPointers(ForwardIterator begin, | |
| 81 ForwardIterator end) { | |
| 82 while (begin != end) { | |
| 83 ForwardIterator temp = begin; | |
| 84 ++begin; | |
| 85 delete temp->first; | |
| 86 delete temp->second; | |
| 87 } | |
| 88 } | |
| 89 | |
| 90 // STLDeleteContainerPairFirstPointers() | |
| 91 // For a range within a container of pairs, calls delete (non-array version) | |
| 92 // on the FIRST item in the pairs. | |
| 93 // NOTE: Like STLDeleteContainerPointers, deleting behind the iterator. | |
| 94 template <class ForwardIterator> | |
| 95 void STLDeleteContainerPairFirstPointers(ForwardIterator begin, | |
| 96 ForwardIterator end) { | |
| 97 while (begin != end) { | |
| 98 ForwardIterator temp = begin; | |
| 99 ++begin; | |
| 100 delete temp->first; | |
| 101 } | |
| 102 } | |
| 103 | |
| 104 // STLDeleteContainerPairSecondPointers() | |
| 105 // For a range within a container of pairs, calls delete | |
| 106 // (non-array version) on the SECOND item in the pairs. | |
| 107 template <class ForwardIterator> | |
| 108 void STLDeleteContainerPairSecondPointers(ForwardIterator begin, | |
| 109 ForwardIterator end) { | |
| 110 while (begin != end) { | |
| 111 delete begin->second; | |
| 112 ++begin; | |
| 113 } | |
| 114 } | |
| 115 | |
| 116 template<typename T> | |
| 117 inline void STLAssignToVector(std::vector<T>* vec, | |
| 118 const T* ptr, | |
| 119 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, | |
| 134 const char* ptr, | |
| 135 size_t n) { | |
| 136 STLAssignToVector(vec, ptr, n); | |
| 137 } | |
| 138 | |
| 139 inline void STLAssignToString(std::string* str, const char* ptr, size_t n) { | |
| 140 str->resize(n); | |
| 141 memcpy(&*str->begin(), ptr, n); | |
| 142 } | |
| 143 | |
| 144 // To treat a possibly-empty vector as an array, use these functions. | |
| 145 // If you know the array will never be empty, you can use &*v.begin() | |
| 146 // directly, but that is allowed to dump core if v is empty. This | |
| 147 // function is the most efficient code that will work, taking into | |
| 148 // account how our STL is actually implemented. THIS IS NON-PORTABLE | |
| 149 // CODE, so call us instead of repeating the nonportable code | |
| 150 // everywhere. If our STL implementation changes, we will need to | |
| 151 // change this as well. | |
| 152 | |
| 153 template<typename T> | |
| 154 inline T* vector_as_array(std::vector<T>* v) { | |
| 155 # ifdef NDEBUG | |
| 156 return &*v->begin(); | |
| 157 # else | |
| 158 return v->empty() ? NULL : &*v->begin(); | |
| 159 # endif | |
| 160 } | |
| 161 | |
| 162 template<typename T> | |
| 163 inline const T* vector_as_array(const std::vector<T>* v) { | |
| 164 # ifdef NDEBUG | |
| 165 return &*v->begin(); | |
| 166 # else | |
| 167 return v->empty() ? NULL : &*v->begin(); | |
| 168 # endif | |
| 169 } | |
| 170 | |
| 171 // Return a mutable char* pointing to a string's internal buffer, | |
| 172 // which may not be null-terminated. Writing through this pointer will | |
| 173 // modify the string. | |
| 174 // | |
| 175 // string_as_array(&str)[i] is valid for 0 <= i < str.size() until the | |
| 176 // next call to a string method that invalidates iterators. | |
| 177 // | |
| 178 // As of 2006-04, there is no standard-blessed way of getting a | |
| 179 // mutable reference to a string's internal buffer. However, issue 530 | |
| 180 // (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#530) | |
| 181 // proposes this as the method. According to Matt Austern, this should | |
| 182 // already work on all current implementations. | |
| 183 inline char* string_as_array(std::string* str) { | |
| 184 // DO NOT USE const_cast<char*>(str->data())! See the unittest for why. | |
| 185 return str->empty() ? NULL : &*str->begin(); | |
| 186 } | |
| 187 | |
| 188 // These are methods that test two hash maps/sets for equality. These exist | |
| 189 // because the == operator in the STL can return false when the maps/sets | |
| 190 // contain identical elements. This is because it compares the internal hash | |
| 191 // tables which may be different if the order of insertions and deletions | |
| 192 // differed. | |
| 193 | |
| 194 template <class HashSet> | |
| 195 inline bool | |
| 196 HashSetEquality(const HashSet& set_a, | |
| 197 const HashSet& set_b) { | |
| 198 if (set_a.size() != set_b.size()) return false; | |
| 199 for (typename HashSet::const_iterator i = set_a.begin(); | |
| 200 i != set_a.end(); | |
| 201 ++i) { | |
| 202 if (set_b.find(*i) == set_b.end()) | |
| 203 return false; | |
| 204 } | |
| 205 return true; | |
| 206 } | |
| 207 | |
| 208 template <class HashMap> | |
| 209 inline bool | |
| 210 HashMapEquality(const HashMap& map_a, | |
| 211 const HashMap& map_b) { | |
| 212 if (map_a.size() != map_b.size()) return false; | |
| 213 for (typename HashMap::const_iterator i = map_a.begin(); | |
| 214 i != map_a.end(); ++i) { | |
| 215 typename HashMap::const_iterator j = map_b.find(i->first); | |
| 216 if (j == map_b.end()) return false; | |
| 217 if (i->second != j->second) return false; | |
| 218 } | |
| 219 return true; | |
| 220 } | |
| 221 | |
| 222 // The following functions are useful for cleaning up STL containers | |
| 223 // whose elements point to allocated memory. | |
| 224 | |
| 225 // STLDeleteElements() deletes all the elements in an STL container and clears | |
| 226 // the container. This function is suitable for use with a vector, set, | |
| 227 // hash_set, or any other STL container which defines sensible begin(), end(), | |
| 228 // and clear() methods. | |
| 229 // | |
| 230 // If container is NULL, this function is a no-op. | |
| 231 // | |
| 232 // As an alternative to calling STLDeleteElements() directly, consider | |
| 233 // STLElementDeleter (defined below), which ensures that your container's | |
| 234 // elements are deleted when the STLElementDeleter goes out of scope. | |
| 235 template <class T> | |
| 236 void STLDeleteElements(T *container) { | |
| 237 if (!container) return; | |
| 238 STLDeleteContainerPointers(container->begin(), container->end()); | |
| 239 container->clear(); | |
| 240 } | |
| 241 | |
| 242 // Given an STL container consisting of (key, value) pairs, STLDeleteValues | |
| 243 // deletes all the "value" components and clears the container. Does nothing | |
| 244 // in the case it's given a NULL pointer. | |
| 245 | |
| 246 template <class T> | |
| 247 void STLDeleteValues(T *v) { | |
| 248 if (!v) return; | |
| 249 for (typename T::iterator i = v->begin(); i != v->end(); ++i) { | |
| 250 delete i->second; | |
| 251 } | |
| 252 v->clear(); | |
| 253 } | |
| 254 | |
| 255 | |
| 256 // The following classes provide a convenient way to delete all elements or | |
| 257 // values from STL containers when they goes out of scope. This greatly | |
| 258 // simplifies code that creates temporary objects and has multiple return | |
| 259 // statements. Example: | |
| 260 // | |
| 261 // vector<MyProto *> tmp_proto; | |
| 262 // STLElementDeleter<vector<MyProto *> > d(&tmp_proto); | |
| 263 // if (...) return false; | |
| 264 // ... | |
| 265 // return success; | |
| 266 | |
| 267 // Given a pointer to an STL container this class will delete all the element | |
| 268 // pointers when it goes out of scope. | |
| 269 | |
| 270 template<class STLContainer> class STLElementDeleter { | |
| 271 public: | |
| 272 STLElementDeleter<STLContainer>(STLContainer *ptr) : container_ptr_(ptr) {} | |
| 273 ~STLElementDeleter<STLContainer>() { STLDeleteElements(container_ptr_); } | |
| 274 private: | |
| 275 STLContainer *container_ptr_; | |
| 276 }; | |
| 277 | |
| 278 // Given a pointer to an STL container this class will delete all the value | |
| 279 // pointers when it goes out of scope. | |
| 280 | |
| 281 template<class STLContainer> class STLValueDeleter { | |
| 282 public: | |
| 283 STLValueDeleter<STLContainer>(STLContainer *ptr) : container_ptr_(ptr) {} | |
| 284 ~STLValueDeleter<STLContainer>() { STLDeleteValues(container_ptr_); } | |
| 285 private: | |
| 286 STLContainer *container_ptr_; | |
| 287 }; | |
| 288 | |
| 289 | |
| 290 // Forward declare some callback classes in callback.h for STLBinaryFunction | |
| 291 template <class R, class T1, class T2> | |
| 292 class ResultCallback2; | |
| 293 | |
| 294 // STLBinaryFunction is a wrapper for the ResultCallback2 class in callback.h | |
| 295 // It provides an operator () method instead of a Run method, so it may be | |
| 296 // passed to STL functions in <algorithm>. | |
| 297 // | |
| 298 // The client should create callback with NewPermanentCallback, and should | |
| 299 // delete callback after it is done using the STLBinaryFunction. | |
| 300 | |
| 301 template <class Result, class Arg1, class Arg2> | |
| 302 class STLBinaryFunction : public std::binary_function<Arg1, Arg2, Result> { | |
| 303 public: | |
| 304 typedef ResultCallback2<Result, Arg1, Arg2> Callback; | |
| 305 | |
| 306 STLBinaryFunction(Callback* callback) | |
| 307 : callback_(callback) { | |
| 308 assert(callback_); | |
| 309 } | |
| 310 | |
| 311 Result operator() (Arg1 arg1, Arg2 arg2) { | |
| 312 return callback_->Run(arg1, arg2); | |
| 313 } | |
| 314 | |
| 315 private: | |
| 316 Callback* callback_; | |
| 317 }; | |
| 318 | |
| 319 // STLBinaryPredicate is a specialized version of STLBinaryFunction, where the | |
| 320 // return type is bool and both arguments have type Arg. It can be used | |
| 321 // wherever STL requires a StrictWeakOrdering, such as in sort() or | |
| 322 // lower_bound(). | |
| 323 // | |
| 324 // templated typedefs are not supported, so instead we use inheritance. | |
| 325 | |
| 326 template <class Arg> | |
| 327 class STLBinaryPredicate : public STLBinaryFunction<bool, Arg, Arg> { | |
| 328 public: | |
| 329 typedef typename STLBinaryPredicate<Arg>::Callback Callback; | |
| 330 STLBinaryPredicate(Callback* callback) | |
| 331 : STLBinaryFunction<bool, Arg, Arg>(callback) { | |
| 332 } | |
| 333 }; | |
| 334 | |
| 335 // Functors that compose arbitrary unary and binary functions with a | |
| 336 // function that "projects" one of the members of a pair. | |
| 337 // Specifically, if p1 and p2, respectively, are the functions that | |
| 338 // map a pair to its first and second, respectively, members, the | |
| 339 // table below summarizes the functions that can be constructed: | |
| 340 // | |
| 341 // * UnaryOperate1st<pair>(f) returns the function x -> f(p1(x)) | |
| 342 // * UnaryOperate2nd<pair>(f) returns the function x -> f(p2(x)) | |
| 343 // * BinaryOperate1st<pair>(f) returns the function (x,y) -> f(p1(x),p1(y)) | |
| 344 // * BinaryOperate2nd<pair>(f) returns the function (x,y) -> f(p2(x),p2(y)) | |
| 345 // | |
| 346 // A typical usage for these functions would be when iterating over | |
| 347 // the contents of an STL map. For other sample usage, see the unittest. | |
| 348 | |
| 349 template<typename Pair, typename UnaryOp> | |
| 350 class UnaryOperateOnFirst | |
| 351 : public std::unary_function<Pair, typename UnaryOp::result_type> { | |
| 352 public: | |
| 353 UnaryOperateOnFirst() { | |
| 354 } | |
| 355 | |
| 356 UnaryOperateOnFirst(const UnaryOp& f) : f_(f) { | |
| 357 } | |
| 358 | |
| 359 typename UnaryOp::result_type operator()(const Pair& p) const { | |
| 360 return f_(p.first); | |
| 361 } | |
| 362 | |
| 363 private: | |
| 364 UnaryOp f_; | |
| 365 }; | |
| 366 | |
| 367 template<typename Pair, typename UnaryOp> | |
| 368 UnaryOperateOnFirst<Pair, UnaryOp> UnaryOperate1st(const UnaryOp& f) { | |
| 369 return UnaryOperateOnFirst<Pair, UnaryOp>(f); | |
| 370 } | |
| 371 | |
| 372 template<typename Pair, typename UnaryOp> | |
| 373 class UnaryOperateOnSecond | |
| 374 : public std::unary_function<Pair, typename UnaryOp::result_type> { | |
| 375 public: | |
| 376 UnaryOperateOnSecond() { | |
| 377 } | |
| 378 | |
| 379 UnaryOperateOnSecond(const UnaryOp& f) : f_(f) { | |
| 380 } | |
| 381 | |
| 382 typename UnaryOp::result_type operator()(const Pair& p) const { | |
| 383 return f_(p.second); | |
| 384 } | |
| 385 | |
| 386 private: | |
| 387 UnaryOp f_; | |
| 388 }; | |
| 389 | |
| 390 template<typename Pair, typename UnaryOp> | |
| 391 UnaryOperateOnSecond<Pair, UnaryOp> UnaryOperate2nd(const UnaryOp& f) { | |
| 392 return UnaryOperateOnSecond<Pair, UnaryOp>(f); | |
| 393 } | |
| 394 | |
| 395 template<typename Pair, typename BinaryOp> | |
| 396 class BinaryOperateOnFirst | |
| 397 : public std::binary_function<Pair, Pair, typename BinaryOp::result_type> { | |
| 398 public: | |
| 399 BinaryOperateOnFirst() { | |
| 400 } | |
| 401 | |
| 402 BinaryOperateOnFirst(const BinaryOp& f) : f_(f) { | |
| 403 } | |
| 404 | |
| 405 typename BinaryOp::result_type operator()(const Pair& p1, | |
| 406 const Pair& p2) const { | |
| 407 return f_(p1.first, p2.first); | |
| 408 } | |
| 409 | |
| 410 private: | |
| 411 BinaryOp f_; | |
| 412 }; | |
| 413 | |
| 414 template<typename Pair, typename BinaryOp> | |
| 415 BinaryOperateOnFirst<Pair, BinaryOp> BinaryOperate1st(const BinaryOp& f) { | |
| 416 return BinaryOperateOnFirst<Pair, BinaryOp>(f); | |
| 417 } | |
| 418 | |
| 419 template<typename Pair, typename BinaryOp> | |
| 420 class BinaryOperateOnSecond | |
| 421 : public std::binary_function<Pair, Pair, typename BinaryOp::result_type> { | |
| 422 public: | |
| 423 BinaryOperateOnSecond() { | |
| 424 } | |
| 425 | |
| 426 BinaryOperateOnSecond(const BinaryOp& f) : f_(f) { | |
| 427 } | |
| 428 | |
| 429 typename BinaryOp::result_type operator()(const Pair& p1, | |
| 430 const Pair& p2) const { | |
| 431 return f_(p1.second, p2.second); | |
| 432 } | |
| 433 | |
| 434 private: | |
| 435 BinaryOp f_; | |
| 436 }; | |
| 437 | |
| 438 template<typename Pair, typename BinaryOp> | |
| 439 BinaryOperateOnSecond<Pair, BinaryOp> BinaryOperate2nd(const BinaryOp& f) { | |
| 440 return BinaryOperateOnSecond<Pair, BinaryOp>(f); | |
| 441 } | |
| 442 | |
| 443 // Translates a set into a vector. | |
| 444 template<typename T> | |
| 445 std::vector<T> SetToVector(const std::set<T>& values) { | |
| 446 std::vector<T> result; | |
| 447 result.reserve(values.size()); | |
| 448 result.insert(result.begin(), values.begin(), values.end()); | |
| 449 return result; | |
| 450 } | |
| 451 | |
| 452 #endif // CHROME_COMMON_STL_UTIL_INL_H__ | |
| OLD | NEW |