stack_container.h 9.5 KB

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