stack_container.h 9.5 KB

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