Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2006-2008 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 #ifndef BASE_STACK_CONTAINER_H_
      6 #define BASE_STACK_CONTAINER_H_
      7 
      8 #include <string>
      9 #include <vector>
     10 
     11 #include "base/basictypes.h"
     12 
     13 // This allocator can be used with STL containers to provide a stack buffer
     14 // from which to allocate memory and overflows onto the heap. This stack buffer
     15 // would be allocated on the stack and allows us to avoid heap operations in
     16 // some situations.
     17 //
     18 // STL likes to make copies of allocators, so the allocator itself can't hold
     19 // the data. Instead, we make the creator responsible for creating a
     20 // StackAllocator::Source which contains the data. Copying the allocator
     21 // merely copies the pointer to this shared source, so all allocators created
     22 // based on our allocator will share the same stack buffer.
     23 //
     24 // This stack buffer implementation is very simple. The first allocation that
     25 // fits in the stack buffer will use the stack buffer. Any subsequent
     26 // allocations will not use the stack buffer, even if there is unused room.
     27 // This makes it appropriate for array-like containers, but the caller should
     28 // be sure to reserve() in the container up to the stack buffer size. Otherwise
     29 // the container will allocate a small array which will "use up" the stack
     30 // buffer.
     31 template<typename T, size_t stack_capacity>
     32 class StackAllocator : public std::allocator<T> {
     33  public:
     34   typedef typename std::allocator<T>::pointer pointer;
     35   typedef typename std::allocator<T>::size_type size_type;
     36 
     37   // Backing store for the allocator. The container owner is responsible for
     38   // maintaining this for as long as any containers using this allocator are
     39   // live.
     40   struct Source {
     41     Source() : used_stack_buffer_(false) {
     42     }
     43 
     44     // Casts the buffer in its right type.
     45     T* stack_buffer() { return reinterpret_cast<T*>(stack_buffer_); }
     46     const T* stack_buffer() const {
     47       return reinterpret_cast<const T*>(stack_buffer_);
     48     }
     49 
     50     //
     51     // IMPORTANT: Take care to ensure that stack_buffer_ is aligned
     52     // since it is used to mimic an array of T.
     53     // Be careful while declaring any unaligned types (like bool)
     54     // before stack_buffer_.
     55     //
     56 
     57     // The buffer itself. It is not of type T because we don't want the
     58     // constructors and destructors to be automatically called. Define a POD
     59     // buffer of the right size instead.
     60     char stack_buffer_[sizeof(T[stack_capacity])];
     61 
     62     // Set when the stack buffer is used for an allocation. We do not track
     63     // how much of the buffer is used, only that somebody is using it.
     64     bool used_stack_buffer_;
     65   };
     66 
     67   // Used by containers when they want to refer to an allocator of type U.
     68   template<typename U>
     69   struct rebind {
     70     typedef StackAllocator<U, stack_capacity> other;
     71   };
     72 
     73   // For the straight up copy c-tor, we can share storage.
     74   StackAllocator(const StackAllocator<T, stack_capacity>& rhs)
     75       : source_(rhs.source_) {
     76   }
     77 
     78   // ISO C++ requires the following constructor to be defined,
     79   // and std::vector in VC++2008SP1 Release fails with an error
     80   // in the class _Container_base_aux_alloc_real (from <xutility>)
     81   // if the constructor does not exist.
     82   // For this constructor, we cannot share storage; there's
     83   // no guarantee that the Source buffer of Ts is large enough
     84   // for Us.
     85   // TODO: If we were fancy pants, perhaps we could share storage
     86   // iff sizeof(T) == sizeof(U).
     87   template<typename U, size_t other_capacity>
     88   StackAllocator(const StackAllocator<U, other_capacity>& other)
     89       : source_(NULL) {
     90   }
     91 
     92   explicit StackAllocator(Source* source) : source_(source) {
     93   }
     94 
     95   // Actually do the allocation. Use the stack buffer if nobody has used it yet
     96   // and the size requested fits. Otherwise, fall through to the standard
     97   // allocator.
     98   pointer allocate(size_type n, void* hint = 0) {
     99     if (source_ != NULL && !source_->used_stack_buffer_
    100         && n <= stack_capacity) {
    101       source_->used_stack_buffer_ = true;
    102       return source_->stack_buffer();
    103     } else {
    104       return std::allocator<T>::allocate(n, hint);
    105     }
    106   }
    107 
    108   // Free: when trying to free the stack buffer, just mark it as free. For
    109   // non-stack-buffer pointers, just fall though to the standard allocator.
    110   void deallocate(pointer p, size_type n) {
    111     if (source_ != NULL && p == source_->stack_buffer())
    112       source_->used_stack_buffer_ = false;
    113     else
    114       std::allocator<T>::deallocate(p, n);
    115   }
    116 
    117  private:
    118   Source* source_;
    119 };
    120 
    121 // A wrapper around STL containers that maintains a stack-sized buffer that the
    122 // initial capacity of the vector is based on. Growing the container beyond the
    123 // stack capacity will transparently overflow onto the heap. The container must
    124 // support reserve().
    125 //
    126 // WATCH OUT: the ContainerType MUST use the proper StackAllocator for this
    127 // type. This object is really intended to be used only internally. You'll want
    128 // to use the wrappers below for different types.
    129 template<typename TContainerType, int stack_capacity>
    130 class StackContainer {
    131  public:
    132   typedef TContainerType ContainerType;
    133   typedef typename ContainerType::value_type ContainedType;
    134   typedef StackAllocator<ContainedType, stack_capacity> Allocator;
    135 
    136   // Allocator must be constructed before the container!
    137   StackContainer() : allocator_(&stack_data_), container_(allocator_) {
    138     // Make the container use the stack allocation by reserving our buffer size
    139     // before doing anything else.
    140     container_.reserve(stack_capacity);
    141   }
    142 
    143   // Getters for the actual container.
    144   //
    145   // Danger: any copies of this made using the copy constructor must have
    146   // shorter lifetimes than the source. The copy will share the same allocator
    147   // and therefore the same stack buffer as the original. Use std::copy to
    148   // copy into a "real" container for longer-lived objects.
    149   ContainerType& container() { return container_; }
    150   const ContainerType& container() const { return container_; }
    151 
    152   // Support operator-> to get to the container. This allows nicer syntax like:
    153   //   StackContainer<...> foo;
    154   //   std::sort(foo->begin(), foo->end());
    155   ContainerType* operator->() { return &container_; }
    156   const ContainerType* operator->() const { return &container_; }
    157 
    158 #ifdef UNIT_TEST
    159   // Retrieves the stack source so that that unit tests can verify that the
    160   // buffer is being used properly.
    161   const typename Allocator::Source& stack_data() const {
    162     return stack_data_;
    163   }
    164 #endif
    165 
    166  protected:
    167   typename Allocator::Source stack_data_;
    168   Allocator allocator_;
    169   ContainerType container_;
    170 
    171   DISALLOW_EVIL_CONSTRUCTORS(StackContainer);
    172 };
    173 
    174 // StackString
    175 template<size_t stack_capacity>
    176 class StackString : public StackContainer<
    177     std::basic_string<char,
    178                       std::char_traits<char>,
    179                       StackAllocator<char, stack_capacity> >,
    180     stack_capacity> {
    181  public:
    182   StackString() : StackContainer<
    183       std::basic_string<char,
    184                         std::char_traits<char>,
    185                         StackAllocator<char, stack_capacity> >,
    186       stack_capacity>() {
    187   }
    188 
    189  private:
    190   DISALLOW_EVIL_CONSTRUCTORS(StackString);
    191 };
    192 
    193 // StackWString
    194 template<size_t stack_capacity>
    195 class StackWString : public StackContainer<
    196     std::basic_string<wchar_t,
    197                       std::char_traits<wchar_t>,
    198                       StackAllocator<wchar_t, stack_capacity> >,
    199     stack_capacity> {
    200  public:
    201   StackWString() : StackContainer<
    202       std::basic_string<wchar_t,
    203                         std::char_traits<wchar_t>,
    204                         StackAllocator<wchar_t, stack_capacity> >,
    205       stack_capacity>() {
    206   }
    207 
    208  private:
    209   DISALLOW_EVIL_CONSTRUCTORS(StackWString);
    210 };
    211 
    212 // StackVector
    213 //
    214 // Example:
    215 //   StackVector<int, 16> foo;
    216 //   foo->push_back(22);  // we have overloaded operator->
    217 //   foo[0] = 10;         // as well as operator[]
    218 template<typename T, size_t stack_capacity>
    219 class StackVector : public StackContainer<
    220     std::vector<T, StackAllocator<T, stack_capacity> >,
    221     stack_capacity> {
    222  public:
    223   StackVector() : StackContainer<
    224       std::vector<T, StackAllocator<T, stack_capacity> >,
    225       stack_capacity>() {
    226   }
    227 
    228   // We need to put this in STL containers sometimes, which requires a copy
    229   // constructor. We can't call the regular copy constructor because that will
    230   // take the stack buffer from the original. Here, we create an empty object
    231   // and make a stack buffer of its own.
    232   StackVector(const StackVector<T, stack_capacity>& other)
    233       : StackContainer<
    234             std::vector<T, StackAllocator<T, stack_capacity> >,
    235             stack_capacity>() {
    236     this->container().assign(other->begin(), other->end());
    237   }
    238 
    239   StackVector<T, stack_capacity>& operator=(
    240       const StackVector<T, stack_capacity>& other) {
    241     this->container().assign(other->begin(), other->end());
    242     return *this;
    243   }
    244 
    245   // Vectors are commonly indexed, which isn't very convenient even with
    246   // operator-> (using "->at()" does exception stuff we don't want).
    247   T& operator[](size_t i) { return this->container().operator[](i); }
    248   const T& operator[](size_t i) const {
    249     return this->container().operator[](i);
    250   }
    251 };
    252 
    253 #endif  // BASE_STACK_CONTAINER_H_
    254