stack_container.h 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 <string>
  7. #include <vector>
  8. #include "base/basictypes.h"
  9. #include "base/memory/aligned_memory.h"
  10. #include "base/strings/string16.h"
  11. #include "base/build_config.h"
  12. namespace base {
  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. // Backing store for the allocator. The container owner is responsible for
  37. // maintaining this for as long as any containers using this allocator are
  38. // live.
  39. struct Source {
  40. Source() : used_stack_buffer_(false) {
  41. }
  42. // Casts the buffer in its right type.
  43. T* stack_buffer() { return stack_buffer_.template data_as<T>(); }
  44. const T* stack_buffer() const {
  45. return stack_buffer_.template data_as<T>();
  46. }
  47. // The buffer itself. It is not of type T because we don't want the
  48. // constructors and destructors to be automatically called. Define a POD
  49. // buffer of the right size instead.
  50. base::AlignedMemory<sizeof(T[stack_capacity]), ALIGNOF(T)> stack_buffer_;
  51. #if defined(__GNUC__) && !defined(ARCH_CPU_X86_FAMILY)
  52. COMPILE_ASSERT(ALIGNOF(T) <= 16, crbug_115612);
  53. #endif
  54. // Set when the stack buffer is used for an allocation. We do not track
  55. // how much of the buffer is used, only that somebody is using it.
  56. bool used_stack_buffer_;
  57. };
  58. // Used by containers when they want to refer to an allocator of type U.
  59. template<typename U>
  60. struct rebind {
  61. typedef StackAllocator<U, stack_capacity> other;
  62. };
  63. // For the straight up copy c-tor, we can share storage.
  64. StackAllocator(const StackAllocator<T, stack_capacity>& rhs)
  65. : std::allocator<T>(), source_(rhs.source_) {
  66. }
  67. // ISO C++ requires the following constructor to be defined,
  68. // and std::vector in VC++2008SP1 Release fails with an error
  69. // in the class _Container_base_aux_alloc_real (from <xutility>)
  70. // if the constructor does not exist.
  71. // For this constructor, we cannot share storage; there's
  72. // no guarantee that the Source buffer of Ts is large enough
  73. // for Us.
  74. // TODO: If we were fancy pants, perhaps we could share storage
  75. // iff sizeof(T) == sizeof(U).
  76. template<typename U, size_t other_capacity>
  77. StackAllocator(const StackAllocator<U, other_capacity>& other)
  78. : source_(NULL) {
  79. }
  80. // This constructor must exist. It creates a default allocator that doesn't
  81. // actually have a stack buffer. glibc's std::string() will compare the
  82. // current allocator against the default-constructed allocator, so this
  83. // should be fast.
  84. StackAllocator() : source_(NULL) {
  85. }
  86. explicit StackAllocator(Source* source) : source_(source) {
  87. }
  88. // Actually do the allocation. Use the stack buffer if nobody has used it yet
  89. // and the size requested fits. Otherwise, fall through to the standard
  90. // allocator.
  91. pointer allocate(size_type n, void* hint = 0) {
  92. if (source_ != NULL && !source_->used_stack_buffer_
  93. && n <= stack_capacity) {
  94. source_->used_stack_buffer_ = true;
  95. return source_->stack_buffer();
  96. } else {
  97. return std::allocator<T>::allocate(n, hint);
  98. }
  99. }
  100. // Free: when trying to free the stack buffer, just mark it as free. For
  101. // non-stack-buffer pointers, just fall though to the standard allocator.
  102. void deallocate(pointer p, size_type n) {
  103. if (source_ != NULL && p == source_->stack_buffer())
  104. source_->used_stack_buffer_ = false;
  105. else
  106. std::allocator<T>::deallocate(p, n);
  107. }
  108. private:
  109. Source* source_;
  110. };
  111. // A wrapper around STL containers that maintains a stack-sized buffer that the
  112. // initial capacity of the vector is based on. Growing the container beyond the
  113. // stack capacity will transparently overflow onto the heap. The container must
  114. // support reserve().
  115. //
  116. // WATCH OUT: the ContainerType MUST use the proper StackAllocator for this
  117. // type. This object is really intended to be used only internally. You'll want
  118. // to use the wrappers below for different types.
  119. template<typename TContainerType, int stack_capacity>
  120. class StackContainer {
  121. public:
  122. typedef TContainerType ContainerType;
  123. typedef typename ContainerType::value_type ContainedType;
  124. typedef StackAllocator<ContainedType, stack_capacity> Allocator;
  125. // Allocator must be constructed before the container!
  126. StackContainer() : allocator_(&stack_data_), container_(allocator_) {
  127. // Make the container use the stack allocation by reserving our buffer size
  128. // before doing anything else.
  129. container_.reserve(stack_capacity);
  130. }
  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. DISALLOW_COPY_AND_ASSIGN(StackContainer);
  156. };
  157. // StackString -----------------------------------------------------------------
  158. template<size_t stack_capacity>
  159. class StackString : public StackContainer<
  160. std::basic_string<char,
  161. std::char_traits<char>,
  162. StackAllocator<char, stack_capacity> >,
  163. stack_capacity> {
  164. public:
  165. StackString() : StackContainer<
  166. std::basic_string<char,
  167. std::char_traits<char>,
  168. StackAllocator<char, stack_capacity> >,
  169. stack_capacity>() {
  170. }
  171. private:
  172. DISALLOW_COPY_AND_ASSIGN(StackString);
  173. };
  174. // StackStrin16 ----------------------------------------------------------------
  175. template<size_t stack_capacity>
  176. class StackString16 : public StackContainer<
  177. std::basic_string<char16,
  178. base::string16_char_traits,
  179. StackAllocator<char16, stack_capacity> >,
  180. stack_capacity> {
  181. public:
  182. StackString16() : StackContainer<
  183. std::basic_string<char16,
  184. base::string16_char_traits,
  185. StackAllocator<char16, stack_capacity> >,
  186. stack_capacity>() {
  187. }
  188. private:
  189. DISALLOW_COPY_AND_ASSIGN(StackString16);
  190. };
  191. // StackVector -----------------------------------------------------------------
  192. // Example:
  193. // StackVector<int, 16> foo;
  194. // foo->push_back(22); // we have overloaded operator->
  195. // foo[0] = 10; // as well as operator[]
  196. template<typename T, size_t stack_capacity>
  197. class StackVector : public StackContainer<
  198. std::vector<T, StackAllocator<T, stack_capacity> >,
  199. stack_capacity> {
  200. public:
  201. StackVector() : StackContainer<
  202. std::vector<T, StackAllocator<T, stack_capacity> >,
  203. stack_capacity>() {
  204. }
  205. // We need to put this in STL containers sometimes, which requires a copy
  206. // constructor. We can't call the regular copy constructor because that will
  207. // take the stack buffer from the original. Here, we create an empty object
  208. // and make a stack buffer of its own.
  209. StackVector(const StackVector<T, stack_capacity>& other)
  210. : StackContainer<
  211. std::vector<T, StackAllocator<T, stack_capacity> >,
  212. stack_capacity>() {
  213. this->container().assign(other->begin(), other->end());
  214. }
  215. StackVector<T, stack_capacity>& operator=(
  216. const StackVector<T, stack_capacity>& other) {
  217. this->container().assign(other->begin(), other->end());
  218. return *this;
  219. }
  220. // Vectors are commonly indexed, which isn't very convenient even with
  221. // operator-> (using "->at()" does exception stuff we don't want).
  222. T& operator[](size_t i) { return this->container().operator[](i); }
  223. const T& operator[](size_t i) const {
  224. return this->container().operator[](i);
  225. }
  226. };
  227. } // namespace base
  228. #endif // BASE_CONTAINERS_STACK_CONTAINER_H_