allocators.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. /*! \def RAPIDJSON_ALLOCATOR_DEFUALT_CHUNK_CAPACITY
  44. \ingroup RAPIDJSON_CONFIG
  45. \brief User-defined kDefaultChunkCapacity definition.
  46. User can define this as any \c size that is a power of 2.
  47. */
  48. #ifndef RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY
  49. #define RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY (64 * 1024)
  50. #endif
  51. ///////////////////////////////////////////////////////////////////////////////
  52. // CrtAllocator
  53. //! C-runtime library allocator.
  54. /*! This class is just wrapper for standard C library memory routines.
  55. \note implements Allocator concept
  56. */
  57. class CrtAllocator {
  58. public:
  59. static const bool kNeedFree = true;
  60. void* Malloc(size_t size) {
  61. if (size) // behavior of malloc(0) is implementation defined.
  62. return std::malloc(size);
  63. else
  64. return NULL; // standardize to returning NULL.
  65. }
  66. void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) {
  67. (void)originalSize;
  68. if (newSize == 0) {
  69. std::free(originalPtr);
  70. return NULL;
  71. }
  72. return std::realloc(originalPtr, newSize);
  73. }
  74. static void Free(void *ptr) { std::free(ptr); }
  75. };
  76. ///////////////////////////////////////////////////////////////////////////////
  77. // MemoryPoolAllocator
  78. //! Default memory allocator used by the parser and DOM.
  79. /*! This allocator allocate memory blocks from pre-allocated memory chunks.
  80. It does not free memory blocks. And Realloc() only allocate new memory.
  81. The memory chunks are allocated by BaseAllocator, which is CrtAllocator by default.
  82. User may also supply a buffer as the first chunk.
  83. If the user-buffer is full then additional chunks are allocated by BaseAllocator.
  84. The user-buffer is not deallocated by this allocator.
  85. \tparam BaseAllocator the allocator type for allocating memory chunks. Default is CrtAllocator.
  86. \note implements Allocator concept
  87. */
  88. template <typename BaseAllocator = CrtAllocator>
  89. class MemoryPoolAllocator {
  90. public:
  91. static const bool kNeedFree = false; //!< Tell users that no need to call Free() with this allocator. (concept Allocator)
  92. //! Constructor with chunkSize.
  93. /*! \param chunkSize The size of memory chunk. The default is kDefaultChunkSize.
  94. \param baseAllocator The allocator for allocating memory chunks.
  95. */
  96. MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
  97. chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
  98. {
  99. }
  100. //! Constructor with user-supplied buffer.
  101. /*! The user buffer will be used firstly. When it is full, memory pool allocates new chunk with chunk size.
  102. The user buffer will not be deallocated when this allocator is destructed.
  103. \param buffer User supplied buffer.
  104. \param size Size of the buffer in bytes. It must at least larger than sizeof(ChunkHeader).
  105. \param chunkSize The size of memory chunk. The default is kDefaultChunkSize.
  106. \param baseAllocator The allocator for allocating memory chunks.
  107. */
  108. MemoryPoolAllocator(void *buffer, size_t size, size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
  109. chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(buffer), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
  110. {
  111. RAPIDJSON_ASSERT(buffer != 0);
  112. RAPIDJSON_ASSERT(size > sizeof(ChunkHeader));
  113. chunkHead_ = reinterpret_cast<ChunkHeader*>(buffer);
  114. chunkHead_->capacity = size - sizeof(ChunkHeader);
  115. chunkHead_->size = 0;
  116. chunkHead_->next = 0;
  117. }
  118. //! Destructor.
  119. /*! This deallocates all memory chunks, excluding the user-supplied buffer.
  120. */
  121. ~MemoryPoolAllocator() {
  122. Clear();
  123. RAPIDJSON_DELETE(ownBaseAllocator_);
  124. }
  125. //! Deallocates all memory chunks, excluding the user-supplied buffer.
  126. void Clear() {
  127. while (chunkHead_ && chunkHead_ != userBuffer_) {
  128. ChunkHeader* next = chunkHead_->next;
  129. baseAllocator_->Free(chunkHead_);
  130. chunkHead_ = next;
  131. }
  132. if (chunkHead_ && chunkHead_ == userBuffer_)
  133. chunkHead_->size = 0; // Clear user buffer
  134. }
  135. //! Computes the total capacity of allocated memory chunks.
  136. /*! \return total capacity in bytes.
  137. */
  138. size_t Capacity() const {
  139. size_t capacity = 0;
  140. for (ChunkHeader* c = chunkHead_; c != 0; c = c->next)
  141. capacity += c->capacity;
  142. return capacity;
  143. }
  144. //! Computes the memory blocks allocated.
  145. /*! \return total used bytes.
  146. */
  147. size_t Size() const {
  148. size_t size = 0;
  149. for (ChunkHeader* c = chunkHead_; c != 0; c = c->next)
  150. size += c->size;
  151. return size;
  152. }
  153. //! Allocates a memory block. (concept Allocator)
  154. void* Malloc(size_t size) {
  155. if (!size)
  156. return NULL;
  157. size = RAPIDJSON_ALIGN(size);
  158. if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity)
  159. if (!AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size))
  160. return NULL;
  161. void *buffer = reinterpret_cast<char *>(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size;
  162. chunkHead_->size += size;
  163. return buffer;
  164. }
  165. //! Resizes a memory block (concept Allocator)
  166. void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) {
  167. if (originalPtr == 0)
  168. return Malloc(newSize);
  169. if (newSize == 0)
  170. return NULL;
  171. originalSize = RAPIDJSON_ALIGN(originalSize);
  172. newSize = RAPIDJSON_ALIGN(newSize);
  173. // Do not shrink if new size is smaller than original
  174. if (originalSize >= newSize)
  175. return originalPtr;
  176. // Simply expand it if it is the last allocation and there is sufficient space
  177. if (originalPtr == reinterpret_cast<char *>(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size - originalSize) {
  178. size_t increment = static_cast<size_t>(newSize - originalSize);
  179. if (chunkHead_->size + increment <= chunkHead_->capacity) {
  180. chunkHead_->size += increment;
  181. return originalPtr;
  182. }
  183. }
  184. // Realloc process: allocate and copy memory, do not free original buffer.
  185. if (void* newBuffer = Malloc(newSize)) {
  186. if (originalSize)
  187. std::memcpy(newBuffer, originalPtr, originalSize);
  188. return newBuffer;
  189. }
  190. else
  191. return NULL;
  192. }
  193. //! Frees a memory block (concept Allocator)
  194. static void Free(void *ptr) { (void)ptr; } // Do nothing
  195. private:
  196. //! Copy constructor is not permitted.
  197. MemoryPoolAllocator(const MemoryPoolAllocator& rhs) /* = delete */;
  198. //! Copy assignment operator is not permitted.
  199. MemoryPoolAllocator& operator=(const MemoryPoolAllocator& rhs) /* = delete */;
  200. //! Creates a new chunk.
  201. /*! \param capacity Capacity of the chunk in bytes.
  202. \return true if success.
  203. */
  204. bool AddChunk(size_t capacity) {
  205. if (!baseAllocator_)
  206. ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator)();
  207. if (ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(baseAllocator_->Malloc(RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity))) {
  208. chunk->capacity = capacity;
  209. chunk->size = 0;
  210. chunk->next = chunkHead_;
  211. chunkHead_ = chunk;
  212. return true;
  213. }
  214. else
  215. return false;
  216. }
  217. static const int kDefaultChunkCapacity = RAPIDJSON_ALLOCATOR_DEFAULT_CHUNK_CAPACITY; //!< Default chunk capacity.
  218. //! Chunk header for perpending to each chunk.
  219. /*! Chunks are stored as a singly linked list.
  220. */
  221. struct ChunkHeader {
  222. size_t capacity; //!< Capacity of the chunk in bytes (excluding the header itself).
  223. size_t size; //!< Current size of allocated memory in bytes.
  224. ChunkHeader *next; //!< Next chunk in the linked list.
  225. };
  226. ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head chunk serves allocation.
  227. size_t chunk_capacity_; //!< The minimum capacity of chunk when they are allocated.
  228. void *userBuffer_; //!< User supplied buffer.
  229. BaseAllocator* baseAllocator_; //!< base allocator for allocating memory chunks.
  230. BaseAllocator* ownBaseAllocator_; //!< base allocator created by this object.
  231. };
  232. RAPIDJSON_NAMESPACE_END
  233. #endif // RAPIDJSON_ENCODINGS_H_