michael@0: // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: // STL utility functions. Usually, these replace built-in, but slow(!), michael@0: // STL functions with more efficient versions. michael@0: michael@0: #ifndef BASE_STL_UTIL_INL_H_ michael@0: #define BASE_STL_UTIL_INL_H_ michael@0: michael@0: #include // for memcpy michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: // Clear internal memory of an STL object. michael@0: // STL clear()/reserve(0) does not always free internal memory allocated michael@0: // This function uses swap/destructor to ensure the internal memory is freed. michael@0: template void STLClearObject(T* obj) { michael@0: T tmp; michael@0: tmp.swap(*obj); michael@0: obj->reserve(0); // this is because sometimes "T tmp" allocates objects with michael@0: // memory (arena implementation?). use reserve() michael@0: // to clear() even if it doesn't always work michael@0: } michael@0: michael@0: // Reduce memory usage on behalf of object if it is using more than michael@0: // "bytes" bytes of space. By default, we clear objects over 1MB. michael@0: template inline void STLClearIfBig(T* obj, size_t limit = 1<<20) { michael@0: if (obj->capacity() >= limit) { michael@0: STLClearObject(obj); michael@0: } else { michael@0: obj->clear(); michael@0: } michael@0: } michael@0: michael@0: // Reserve space for STL object. michael@0: // STL's reserve() will always copy. michael@0: // This function avoid the copy if we already have capacity michael@0: template void STLReserveIfNeeded(T* obj, int new_size) { michael@0: if (obj->capacity() < new_size) // increase capacity michael@0: obj->reserve(new_size); michael@0: else if (obj->size() > new_size) // reduce size michael@0: obj->resize(new_size); michael@0: } michael@0: michael@0: // STLDeleteContainerPointers() michael@0: // For a range within a container of pointers, calls delete michael@0: // (non-array version) on these pointers. michael@0: // NOTE: for these three functions, we could just implement a DeleteObject michael@0: // functor and then call for_each() on the range and functor, but this michael@0: // requires us to pull in all of algorithm.h, which seems expensive. michael@0: // For hash_[multi]set, it is important that this deletes behind the iterator michael@0: // because the hash_set may call the hash function on the iterator when it is michael@0: // advanced, which could result in the hash function trying to deference a michael@0: // stale pointer. michael@0: template michael@0: void STLDeleteContainerPointers(ForwardIterator begin, michael@0: ForwardIterator end) { michael@0: while (begin != end) { michael@0: ForwardIterator temp = begin; michael@0: ++begin; michael@0: delete *temp; michael@0: } michael@0: } michael@0: michael@0: // STLDeleteContainerPairPointers() michael@0: // For a range within a container of pairs, calls delete michael@0: // (non-array version) on BOTH items in the pairs. michael@0: // NOTE: Like STLDeleteContainerPointers, it is important that this deletes michael@0: // behind the iterator because if both the key and value are deleted, the michael@0: // container may call the hash function on the iterator when it is advanced, michael@0: // which could result in the hash function trying to dereference a stale michael@0: // pointer. michael@0: template michael@0: void STLDeleteContainerPairPointers(ForwardIterator begin, michael@0: ForwardIterator end) { michael@0: while (begin != end) { michael@0: ForwardIterator temp = begin; michael@0: ++begin; michael@0: delete temp->first; michael@0: delete temp->second; michael@0: } michael@0: } michael@0: michael@0: // STLDeleteContainerPairFirstPointers() michael@0: // For a range within a container of pairs, calls delete (non-array version) michael@0: // on the FIRST item in the pairs. michael@0: // NOTE: Like STLDeleteContainerPointers, deleting behind the iterator. michael@0: template michael@0: void STLDeleteContainerPairFirstPointers(ForwardIterator begin, michael@0: ForwardIterator end) { michael@0: while (begin != end) { michael@0: ForwardIterator temp = begin; michael@0: ++begin; michael@0: delete temp->first; michael@0: } michael@0: } michael@0: michael@0: // STLDeleteContainerPairSecondPointers() michael@0: // For a range within a container of pairs, calls delete michael@0: // (non-array version) on the SECOND item in the pairs. michael@0: template michael@0: void STLDeleteContainerPairSecondPointers(ForwardIterator begin, michael@0: ForwardIterator end) { michael@0: while (begin != end) { michael@0: delete begin->second; michael@0: ++begin; michael@0: } michael@0: } michael@0: michael@0: template michael@0: inline void STLAssignToVector(std::vector* vec, michael@0: const T* ptr, michael@0: size_t n) { michael@0: vec->resize(n); michael@0: memcpy(&vec->front(), ptr, n*sizeof(T)); michael@0: } michael@0: michael@0: /***** Hack to allow faster assignment to a vector *****/ michael@0: michael@0: // This routine speeds up an assignment of 32 bytes to a vector from michael@0: // about 250 cycles per assignment to about 140 cycles. michael@0: // michael@0: // Usage: michael@0: // STLAssignToVectorChar(&vec, ptr, size); michael@0: // STLAssignToString(&str, ptr, size); michael@0: michael@0: inline void STLAssignToVectorChar(std::vector* vec, michael@0: const char* ptr, michael@0: size_t n) { michael@0: STLAssignToVector(vec, ptr, n); michael@0: } michael@0: michael@0: inline void STLAssignToString(std::string* str, const char* ptr, size_t n) { michael@0: str->resize(n); michael@0: memcpy(&*str->begin(), ptr, n); michael@0: } michael@0: michael@0: // To treat a possibly-empty vector as an array, use these functions. michael@0: // If you know the array will never be empty, you can use &*v.begin() michael@0: // directly, but that is allowed to dump core if v is empty. This michael@0: // function is the most efficient code that will work, taking into michael@0: // account how our STL is actually implemented. THIS IS NON-PORTABLE michael@0: // CODE, so call us instead of repeating the nonportable code michael@0: // everywhere. If our STL implementation changes, we will need to michael@0: // change this as well. michael@0: michael@0: template michael@0: inline T* vector_as_array(std::vector* v) { michael@0: # ifdef NDEBUG michael@0: return &*v->begin(); michael@0: # else michael@0: return v->empty() ? NULL : &*v->begin(); michael@0: # endif michael@0: } michael@0: michael@0: template michael@0: inline const T* vector_as_array(const std::vector* v) { michael@0: # ifdef NDEBUG michael@0: return &*v->begin(); michael@0: # else michael@0: return v->empty() ? NULL : &*v->begin(); michael@0: # endif michael@0: } michael@0: michael@0: // Return a mutable char* pointing to a string's internal buffer, michael@0: // which may not be null-terminated. Writing through this pointer will michael@0: // modify the string. michael@0: // michael@0: // string_as_array(&str)[i] is valid for 0 <= i < str.size() until the michael@0: // next call to a string method that invalidates iterators. michael@0: // michael@0: // As of 2006-04, there is no standard-blessed way of getting a michael@0: // mutable reference to a string's internal buffer. However, issue 530 michael@0: // (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#530) michael@0: // proposes this as the method. According to Matt Austern, this should michael@0: // already work on all current implementations. michael@0: inline char* string_as_array(std::string* str) { michael@0: // DO NOT USE const_cast(str->data())! See the unittest for why. michael@0: return str->empty() ? NULL : &*str->begin(); michael@0: } michael@0: michael@0: // These are methods that test two hash maps/sets for equality. These exist michael@0: // because the == operator in the STL can return false when the maps/sets michael@0: // contain identical elements. This is because it compares the internal hash michael@0: // tables which may be different if the order of insertions and deletions michael@0: // differed. michael@0: michael@0: template michael@0: inline bool michael@0: HashSetEquality(const HashSet& set_a, michael@0: const HashSet& set_b) { michael@0: if (set_a.size() != set_b.size()) return false; michael@0: for (typename HashSet::const_iterator i = set_a.begin(); michael@0: i != set_a.end(); michael@0: ++i) { michael@0: if (set_b.find(*i) == set_b.end()) michael@0: return false; michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: template michael@0: inline bool michael@0: HashMapEquality(const HashMap& map_a, michael@0: const HashMap& map_b) { michael@0: if (map_a.size() != map_b.size()) return false; michael@0: for (typename HashMap::const_iterator i = map_a.begin(); michael@0: i != map_a.end(); ++i) { michael@0: typename HashMap::const_iterator j = map_b.find(i->first); michael@0: if (j == map_b.end()) return false; michael@0: if (i->second != j->second) return false; michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: // The following functions are useful for cleaning up STL containers michael@0: // whose elements point to allocated memory. michael@0: michael@0: // STLDeleteElements() deletes all the elements in an STL container and clears michael@0: // the container. This function is suitable for use with a vector, set, michael@0: // hash_set, or any other STL container which defines sensible begin(), end(), michael@0: // and clear() methods. michael@0: // michael@0: // If container is NULL, this function is a no-op. michael@0: // michael@0: // As an alternative to calling STLDeleteElements() directly, consider michael@0: // STLElementDeleter (defined below), which ensures that your container's michael@0: // elements are deleted when the STLElementDeleter goes out of scope. michael@0: template michael@0: void STLDeleteElements(T *container) { michael@0: if (!container) return; michael@0: STLDeleteContainerPointers(container->begin(), container->end()); michael@0: container->clear(); michael@0: } michael@0: michael@0: // Given an STL container consisting of (key, value) pairs, STLDeleteValues michael@0: // deletes all the "value" components and clears the container. Does nothing michael@0: // in the case it's given a NULL pointer. michael@0: michael@0: template michael@0: void STLDeleteValues(T *v) { michael@0: if (!v) return; michael@0: for (typename T::iterator i = v->begin(); i != v->end(); ++i) { michael@0: delete i->second; michael@0: } michael@0: v->clear(); michael@0: } michael@0: michael@0: michael@0: // The following classes provide a convenient way to delete all elements or michael@0: // values from STL containers when they goes out of scope. This greatly michael@0: // simplifies code that creates temporary objects and has multiple return michael@0: // statements. Example: michael@0: // michael@0: // vector tmp_proto; michael@0: // STLElementDeleter > d(&tmp_proto); michael@0: // if (...) return false; michael@0: // ... michael@0: // return success; michael@0: michael@0: // Given a pointer to an STL container this class will delete all the element michael@0: // pointers when it goes out of scope. michael@0: michael@0: template class STLElementDeleter { michael@0: public: michael@0: STLElementDeleter(STLContainer *ptr) : container_ptr_(ptr) {} michael@0: ~STLElementDeleter() { STLDeleteElements(container_ptr_); } michael@0: private: michael@0: STLContainer *container_ptr_; michael@0: }; michael@0: michael@0: // Given a pointer to an STL container this class will delete all the value michael@0: // pointers when it goes out of scope. michael@0: michael@0: template class STLValueDeleter { michael@0: public: michael@0: STLValueDeleter(STLContainer *ptr) : container_ptr_(ptr) {} michael@0: ~STLValueDeleter() { STLDeleteValues(container_ptr_); } michael@0: private: michael@0: STLContainer *container_ptr_; michael@0: }; michael@0: michael@0: michael@0: // Forward declare some callback classes in callback.h for STLBinaryFunction michael@0: template michael@0: class ResultCallback2; michael@0: michael@0: // STLBinaryFunction is a wrapper for the ResultCallback2 class in callback.h michael@0: // It provides an operator () method instead of a Run method, so it may be michael@0: // passed to STL functions in . michael@0: // michael@0: // The client should create callback with NewPermanentCallback, and should michael@0: // delete callback after it is done using the STLBinaryFunction. michael@0: michael@0: template michael@0: class STLBinaryFunction : public std::binary_function { michael@0: public: michael@0: typedef ResultCallback2 Callback; michael@0: michael@0: STLBinaryFunction(Callback* callback) michael@0: : callback_(callback) { michael@0: assert(callback_); michael@0: } michael@0: michael@0: Result operator() (Arg1 arg1, Arg2 arg2) { michael@0: return callback_->Run(arg1, arg2); michael@0: } michael@0: michael@0: private: michael@0: Callback* callback_; michael@0: }; michael@0: michael@0: // STLBinaryPredicate is a specialized version of STLBinaryFunction, where the michael@0: // return type is bool and both arguments have type Arg. It can be used michael@0: // wherever STL requires a StrictWeakOrdering, such as in sort() or michael@0: // lower_bound(). michael@0: // michael@0: // templated typedefs are not supported, so instead we use inheritance. michael@0: michael@0: template michael@0: class STLBinaryPredicate : public STLBinaryFunction { michael@0: public: michael@0: typedef typename STLBinaryPredicate::Callback Callback; michael@0: STLBinaryPredicate(Callback* callback) michael@0: : STLBinaryFunction(callback) { michael@0: } michael@0: }; michael@0: michael@0: // Functors that compose arbitrary unary and binary functions with a michael@0: // function that "projects" one of the members of a pair. michael@0: // Specifically, if p1 and p2, respectively, are the functions that michael@0: // map a pair to its first and second, respectively, members, the michael@0: // table below summarizes the functions that can be constructed: michael@0: // michael@0: // * UnaryOperate1st(f) returns the function x -> f(p1(x)) michael@0: // * UnaryOperate2nd(f) returns the function x -> f(p2(x)) michael@0: // * BinaryOperate1st(f) returns the function (x,y) -> f(p1(x),p1(y)) michael@0: // * BinaryOperate2nd(f) returns the function (x,y) -> f(p2(x),p2(y)) michael@0: // michael@0: // A typical usage for these functions would be when iterating over michael@0: // the contents of an STL map. For other sample usage, see the unittest. michael@0: michael@0: template michael@0: class UnaryOperateOnFirst michael@0: : public std::unary_function { michael@0: public: michael@0: UnaryOperateOnFirst() { michael@0: } michael@0: michael@0: UnaryOperateOnFirst(const UnaryOp& f) : f_(f) { michael@0: } michael@0: michael@0: typename UnaryOp::result_type operator()(const Pair& p) const { michael@0: return f_(p.first); michael@0: } michael@0: michael@0: private: michael@0: UnaryOp f_; michael@0: }; michael@0: michael@0: template michael@0: UnaryOperateOnFirst UnaryOperate1st(const UnaryOp& f) { michael@0: return UnaryOperateOnFirst(f); michael@0: } michael@0: michael@0: template michael@0: class UnaryOperateOnSecond michael@0: : public std::unary_function { michael@0: public: michael@0: UnaryOperateOnSecond() { michael@0: } michael@0: michael@0: UnaryOperateOnSecond(const UnaryOp& f) : f_(f) { michael@0: } michael@0: michael@0: typename UnaryOp::result_type operator()(const Pair& p) const { michael@0: return f_(p.second); michael@0: } michael@0: michael@0: private: michael@0: UnaryOp f_; michael@0: }; michael@0: michael@0: template michael@0: UnaryOperateOnSecond UnaryOperate2nd(const UnaryOp& f) { michael@0: return UnaryOperateOnSecond(f); michael@0: } michael@0: michael@0: template michael@0: class BinaryOperateOnFirst michael@0: : public std::binary_function { michael@0: public: michael@0: BinaryOperateOnFirst() { michael@0: } michael@0: michael@0: BinaryOperateOnFirst(const BinaryOp& f) : f_(f) { michael@0: } michael@0: michael@0: typename BinaryOp::result_type operator()(const Pair& p1, michael@0: const Pair& p2) const { michael@0: return f_(p1.first, p2.first); michael@0: } michael@0: michael@0: private: michael@0: BinaryOp f_; michael@0: }; michael@0: michael@0: template michael@0: BinaryOperateOnFirst BinaryOperate1st(const BinaryOp& f) { michael@0: return BinaryOperateOnFirst(f); michael@0: } michael@0: michael@0: template michael@0: class BinaryOperateOnSecond michael@0: : public std::binary_function { michael@0: public: michael@0: BinaryOperateOnSecond() { michael@0: } michael@0: michael@0: BinaryOperateOnSecond(const BinaryOp& f) : f_(f) { michael@0: } michael@0: michael@0: typename BinaryOp::result_type operator()(const Pair& p1, michael@0: const Pair& p2) const { michael@0: return f_(p1.second, p2.second); michael@0: } michael@0: michael@0: private: michael@0: BinaryOp f_; michael@0: }; michael@0: michael@0: template michael@0: BinaryOperateOnSecond BinaryOperate2nd(const BinaryOp& f) { michael@0: return BinaryOperateOnSecond(f); michael@0: } michael@0: michael@0: // Translates a set into a vector. michael@0: template michael@0: std::vector SetToVector(const std::set& values) { michael@0: std::vector result; michael@0: result.reserve(values.size()); michael@0: result.insert(result.begin(), values.begin(), values.end()); michael@0: return result; michael@0: } michael@0: michael@0: #endif // BASE_STL_UTIL_INL_H_