allocators.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // Tencent is pleased to support the open source community by making RapidJSON available.
  2. //
  3. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
  4. //
  5. // Licensed under the MIT License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://opensource.org/licenses/MIT
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #ifndef RAPIDJSON_ALLOCATORS_H_
  15. #define RAPIDJSON_ALLOCATORS_H_
  16. #include "rapidjson.h"
  17. RAPIDJSON_NAMESPACE_BEGIN
  18. ///////////////////////////////////////////////////////////////////////////////
  19. // Allocator
  20. /*! \class rapidjson::Allocator
  21. \brief Concept for allocating, resizing and freeing memory block.
  22. Note that Malloc() and Realloc() are non-static but Free() is static.
  23. So if an allocator need to support Free(), it needs to put its pointer in
  24. the header of memory block.
  25. \code
  26. concept Allocator {
  27. static const bool kNeedFree; //!< Whether this allocator needs to call Free().
  28. // Allocate a memory block.
  29. // \param size of the memory block in bytes.
  30. // \returns pointer to the memory block.
  31. void* Malloc(size_t size);
  32. // Resize a memory block.
  33. // \param originalPtr The pointer to current memory block. Null pointer is permitted.
  34. // \param originalSize The current size in bytes. (Design issue: since some allocator may not book-keep this, explicitly pass to it can save memory.)
  35. // \param newSize the new size in bytes.
  36. void* Realloc(void* originalPtr, size_t originalSize, size_t newSize);
  37. // Free a memory block.
  38. // \param pointer to the memory block. Null pointer is permitted.
  39. static void Free(void *ptr);
  40. };
  41. \endcode
  42. */
  43. ///////////////////////////////////////////////////////////////////////////////
  44. // CrtAllocator
  45. //! C-runtime library allocator.
  46. /*! This class is just wrapper for standard C library memory routines.
  47. \note implements Allocator concept
  48. */
  49. class CrtAllocator {
  50. public:
  51. static const bool kNeedFree = true;
  52. void* Malloc(size_t size) {
  53. if (size) // behavior of malloc(0) is implementation defined.
  54. return std::malloc(size);
  55. else
  56. return NULL; // standardize to returning NULL.
  57. }
  58. void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) {
  59. (void)originalSize;
  60. if (newSize == 0) {
  61. std::free(originalPtr);
  62. return NULL;
  63. }
  64. return std::realloc(originalPtr, newSize);
  65. }
  66. static void Free(void *ptr) { std::free(ptr); }
  67. };
  68. ///////////////////////////////////////////////////////////////////////////////
  69. // MemoryPoolAllocator
  70. //! Default memory allocator used by the parser and DOM.
  71. /*! This allocator allocate memory blocks from pre-allocated memory chunks.
  72. It does not free memory blocks. And Realloc() only allocate new memory.
  73. The memory chunks are allocated by BaseAllocator, which is CrtAllocator by default.
  74. User may also supply a buffer as the first chunk.
  75. If the user-buffer is full then additional chunks are allocated by BaseAllocator.
  76. The user-buffer is not deallocated by this allocator.
  77. \tparam BaseAllocator the allocator type for allocating memory chunks. Default is CrtAllocator.
  78. \note implements Allocator concept
  79. */
  80. template <typename BaseAllocator = CrtAllocator>
  81. class MemoryPoolAllocator {
  82. public:
  83. static const bool kNeedFree = false; //!< Tell users that no need to call Free() with this allocator. (concept Allocator)
  84. //! Constructor with chunkSize.
  85. /*! \param chunkSize The size of memory chunk. The default is kDefaultChunkSize.
  86. \param baseAllocator The allocator for allocating memory chunks.
  87. */
  88. MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
  89. chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
  90. {
  91. }
  92. //! Constructor with user-supplied buffer.
  93. /*! The user buffer will be used firstly. When it is full, memory pool allocates new chunk with chunk size.
  94. The user buffer will not be deallocated when this allocator is destructed.
  95. \param buffer User supplied buffer.
  96. \param size Size of the buffer in bytes. It must at least larger than sizeof(ChunkHeader).
  97. \param chunkSize The size of memory chunk. The default is kDefaultChunkSize.
  98. \param baseAllocator The allocator for allocating memory chunks.
  99. */
  100. MemoryPoolAllocator(void *buffer, size_t size, size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
  101. chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(buffer), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
  102. {
  103. RAPIDJSON_ASSERT(buffer != 0);
  104. RAPIDJSON_ASSERT(size > sizeof(ChunkHeader));
  105. chunkHead_ = reinterpret_cast<ChunkHeader*>(buffer);
  106. chunkHead_->capacity = size - sizeof(ChunkHeader);
  107. chunkHead_->size = 0;
  108. chunkHead_->next = 0;
  109. }
  110. //! Destructor.
  111. /*! This deallocates all memory chunks, excluding the user-supplied buffer.
  112. */
  113. ~MemoryPoolAllocator() {
  114. Clear();
  115. RAPIDJSON_DELETE(ownBaseAllocator_);
  116. }
  117. //! Deallocates all memory chunks, excluding the user-supplied buffer.
  118. void Clear() {
  119. while (chunkHead_ && chunkHead_ != userBuffer_) {
  120. ChunkHeader* next = chunkHead_->next;
  121. baseAllocator_->Free(chunkHead_);
  122. chunkHead_ = next;
  123. }
  124. if (chunkHead_ && chunkHead_ == userBuffer_)
  125. chunkHead_->size = 0; // Clear user buffer
  126. }
  127. //! Computes the total capacity of allocated memory chunks.
  128. /*! \return total capacity in bytes.
  129. */
  130. size_t Capacity() const {
  131. size_t capacity = 0;
  132. for (ChunkHeader* c = chunkHead_; c != 0; c = c->next)
  133. capacity += c->capacity;
  134. return capacity;
  135. }
  136. //! Computes the memory blocks allocated.
  137. /*! \return total used bytes.
  138. */
  139. size_t Size() const {
  140. size_t size = 0;
  141. for (ChunkHeader* c = chunkHead_; c != 0; c = c->next)
  142. size += c->size;
  143. return size;
  144. }
  145. //! Allocates a memory block. (concept Allocator)
  146. void* Malloc(size_t size) {
  147. if (!size)
  148. return NULL;
  149. size = RAPIDJSON_ALIGN(size);
  150. if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity)
  151. AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size);
  152. void *buffer = reinterpret_cast<char *>(chunkHead_ + 1) + chunkHead_->size;
  153. chunkHead_->size += size;
  154. return buffer;
  155. }
  156. //! Resizes a memory block (concept Allocator)
  157. void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) {
  158. if (originalPtr == 0)
  159. return Malloc(newSize);
  160. if (newSize == 0)
  161. return NULL;
  162. // Do not shrink if new size is smaller than original
  163. if (originalSize >= newSize)
  164. return originalPtr;
  165. // Simply expand it if it is the last allocation and there is sufficient space
  166. if (originalPtr == (char *)(chunkHead_ + 1) + chunkHead_->size - originalSize) {
  167. size_t increment = static_cast<size_t>(newSize - originalSize);
  168. increment = RAPIDJSON_ALIGN(increment);
  169. if (chunkHead_->size + increment <= chunkHead_->capacity) {
  170. chunkHead_->size += increment;
  171. return originalPtr;
  172. }
  173. }
  174. // Realloc process: allocate and copy memory, do not free original buffer.
  175. void* newBuffer = Malloc(newSize);
  176. RAPIDJSON_ASSERT(newBuffer != 0); // Do not handle out-of-memory explicitly.
  177. if (originalSize)
  178. std::memcpy(newBuffer, originalPtr, originalSize);
  179. return newBuffer;
  180. }
  181. //! Frees a memory block (concept Allocator)
  182. static void Free(void *ptr) { (void)ptr; } // Do nothing
  183. private:
  184. //! Copy constructor is not permitted.
  185. MemoryPoolAllocator(const MemoryPoolAllocator& rhs) /* = delete */;
  186. //! Copy assignment operator is not permitted.
  187. MemoryPoolAllocator& operator=(const MemoryPoolAllocator& rhs) /* = delete */;
  188. //! Creates a new chunk.
  189. /*! \param capacity Capacity of the chunk in bytes.
  190. */
  191. void AddChunk(size_t capacity) {
  192. if (!baseAllocator_)
  193. ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator());
  194. ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(baseAllocator_->Malloc(sizeof(ChunkHeader) + capacity));
  195. chunk->capacity = capacity;
  196. chunk->size = 0;
  197. chunk->next = chunkHead_;
  198. chunkHead_ = chunk;
  199. }
  200. static const int kDefaultChunkCapacity = 64 * 1024; //!< Default chunk capacity.
  201. //! Chunk header for perpending to each chunk.
  202. /*! Chunks are stored as a singly linked list.
  203. */
  204. struct ChunkHeader {
  205. size_t capacity; //!< Capacity of the chunk in bytes (excluding the header itself).
  206. size_t size; //!< Current size of allocated memory in bytes.
  207. ChunkHeader *next; //!< Next chunk in the linked list.
  208. };
  209. ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head chunk serves allocation.
  210. size_t chunk_capacity_; //!< The minimum capacity of chunk when they are allocated.
  211. void *userBuffer_; //!< User supplied buffer.
  212. BaseAllocator* baseAllocator_; //!< base allocator for allocating memory chunks.
  213. BaseAllocator* ownBaseAllocator_; //!< base allocator created by this object.
  214. };
  215. RAPIDJSON_NAMESPACE_END
  216. #endif // RAPIDJSON_ENCODINGS_H_