dataChunker.h 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _DATACHUNKER_H_
  23. #define _DATACHUNKER_H_
  24. #ifndef _PLATFORM_H_
  25. # include "platform/platform.h"
  26. #endif
  27. //----------------------------------------------------------------------------
  28. /// Implements a chunked data allocator.
  29. ///
  30. /// Calling new/malloc all the time is a time consuming operation. Therefore,
  31. /// we provide the DataChunker, which allocates memory in blocks of
  32. /// chunkSize (by default 16k, see ChunkSize, though it can be set in
  33. /// the constructor), then doles it out as requested, in chunks of up to
  34. /// chunkSize in size.
  35. ///
  36. /// It will assert if you try to get more than ChunkSize bytes at a time,
  37. /// and it deals with the logic of allocating new blocks and giving out
  38. /// word-aligned chunks.
  39. ///
  40. /// Note that new/free/realloc WILL NOT WORK on memory gotten from the
  41. /// DataChunker. This also only grows (you can call freeBlocks to deallocate
  42. /// and reset things).
  43. class DataChunker
  44. {
  45. public:
  46. enum {
  47. ChunkSize = 16376 ///< Default size of each DataBlock page in the DataChunker
  48. };
  49. /// Return a pointer to a chunk of memory from a pre-allocated block.
  50. ///
  51. /// This memory goes away when you call freeBlocks.
  52. ///
  53. /// This memory is word-aligned.
  54. /// @param size Size of chunk to return. This must be less than chunkSize or else
  55. /// an assertion will occur.
  56. void *alloc(S32 size);
  57. /// Free all allocated memory blocks.
  58. ///
  59. /// This invalidates all pointers returned from alloc().
  60. void freeBlocks(bool keepOne = false);
  61. /// Initialize using blocks of a given size.
  62. ///
  63. /// One new block is allocated at constructor-time.
  64. ///
  65. /// @param size Size in bytes of the space to allocate for each block.
  66. DataChunker(S32 size=ChunkSize);
  67. ~DataChunker();
  68. /// Swaps the memory allocated in one data chunker for another. This can be used to implement
  69. /// packing of memory stored in a DataChunker.
  70. void swap(DataChunker &d)
  71. {
  72. DataBlock *temp = d.mCurBlock;
  73. d.mCurBlock = mCurBlock;
  74. mCurBlock = temp;
  75. }
  76. private:
  77. /// Block of allocated memory.
  78. ///
  79. /// <b>This has nothing to do with datablocks as used in the rest of Torque.</b>
  80. struct DataBlock
  81. {
  82. DataBlock* prev;
  83. DataBlock* next; ///< linked list pointer to the next DataBlock for this chunker
  84. U8 *data; ///< allocated pointer for the base of this page
  85. S32 curIndex; ///< current allocation point within this DataBlock
  86. DataBlock(S32 size);
  87. ~DataBlock();
  88. };
  89. DataBlock* mFirstBlock;
  90. DataBlock *mCurBlock; ///< current page we're allocating data from. If the
  91. ///< data size request is greater than the memory space currently
  92. ///< available in the current page, a new page will be allocated.
  93. S32 mChunkSize; ///< The size allocated for each page in the DataChunker
  94. };
  95. //----------------------------------------------------------------------------
  96. template<class T>
  97. class Chunker: private DataChunker
  98. {
  99. public:
  100. Chunker(S32 size = DataChunker::ChunkSize) : DataChunker(size) {};
  101. T* alloc() { return reinterpret_cast<T*>(DataChunker::alloc(S32(sizeof(T)))); }
  102. void clear() { freeBlocks(); }
  103. };
  104. //----------------------------------------------------------------------------
  105. /// This class is similar to the Chunker<> class above. But it allows for multiple
  106. /// types of structs to be stored.
  107. /// CodeReview: This could potentially go into DataChunker directly, but I wasn't sure if
  108. /// CodeReview: That would be polluting it. BTR
  109. class MultiTypedChunker : private DataChunker
  110. {
  111. public:
  112. MultiTypedChunker(S32 size = DataChunker::ChunkSize) : DataChunker(size) {};
  113. /// Use like so: MyType* t = chunker.alloc<MyType>();
  114. template<typename T>
  115. T* alloc() { return reinterpret_cast<T*>(DataChunker::alloc(S32(sizeof(T)))); }
  116. void clear() { freeBlocks(true); }
  117. };
  118. //----------------------------------------------------------------------------
  119. /// Templatized data chunker class with proper construction and destruction of its elements.
  120. ///
  121. /// DataChunker just allocates space. This subclass actually constructs/destructs the
  122. /// elements. This class is appropriate for more complex classes.
  123. template<class T>
  124. class ClassChunker: private DataChunker
  125. {
  126. public:
  127. ClassChunker(S32 size = DataChunker::ChunkSize) : DataChunker(size)
  128. {
  129. mElementSize = getMax(U32(sizeof(T)), U32(sizeof(T *)));
  130. mFreeListHead = NULL;
  131. }
  132. /// Allocates and properly constructs in place a new element.
  133. T *alloc()
  134. {
  135. if(mFreeListHead == NULL)
  136. return constructInPlace(reinterpret_cast<T*>(DataChunker::alloc(mElementSize)));
  137. T* ret = mFreeListHead;
  138. mFreeListHead = *(reinterpret_cast<T**>(mFreeListHead));
  139. return constructInPlace(ret);
  140. }
  141. /// Properly destructs and frees an element allocated with the alloc method.
  142. void free(T* elem)
  143. {
  144. destructInPlace(elem);
  145. *(reinterpret_cast<T**>(elem)) = mFreeListHead;
  146. mFreeListHead = elem;
  147. }
  148. void freeBlocks( bool keepOne = false )
  149. {
  150. DataChunker::freeBlocks( keepOne );
  151. mFreeListHead = NULL;
  152. }
  153. private:
  154. S32 mElementSize; ///< the size of each element, or the size of a pointer, whichever is greater
  155. T *mFreeListHead; ///< a pointer to a linked list of freed elements for reuse
  156. };
  157. //----------------------------------------------------------------------------
  158. template<class T>
  159. class FreeListChunker
  160. {
  161. public:
  162. FreeListChunker(DataChunker *inChunker)
  163. : mChunker( inChunker ),
  164. mOwnChunker( false ),
  165. mFreeListHead( NULL )
  166. {
  167. mElementSize = getMax(U32(sizeof(T)), U32(sizeof(T *)));
  168. }
  169. FreeListChunker(S32 size = DataChunker::ChunkSize)
  170. : mFreeListHead( NULL )
  171. {
  172. mChunker = new DataChunker( size );
  173. mOwnChunker = true;
  174. mElementSize = getMax(U32(sizeof(T)), U32(sizeof(T *)));
  175. }
  176. ~FreeListChunker()
  177. {
  178. if ( mOwnChunker )
  179. delete mChunker;
  180. }
  181. T *alloc()
  182. {
  183. if(mFreeListHead == NULL)
  184. return reinterpret_cast<T*>(mChunker->alloc(mElementSize));
  185. T* ret = mFreeListHead;
  186. mFreeListHead = *(reinterpret_cast<T**>(mFreeListHead));
  187. return ret;
  188. }
  189. void free(T* elem)
  190. {
  191. *(reinterpret_cast<T**>(elem)) = mFreeListHead;
  192. mFreeListHead = elem;
  193. }
  194. /// Allow people to free all their memory if they want.
  195. void freeBlocks( bool keepOne = false )
  196. {
  197. mChunker->freeBlocks( keepOne );
  198. mFreeListHead = NULL;
  199. }
  200. private:
  201. DataChunker *mChunker;
  202. bool mOwnChunker;
  203. S32 mElementSize;
  204. T *mFreeListHead;
  205. };
  206. class FreeListChunkerUntyped
  207. {
  208. public:
  209. FreeListChunkerUntyped(U32 inElementSize, DataChunker *inChunker)
  210. : mChunker( inChunker ),
  211. mOwnChunker( false ),
  212. mElementSize( inElementSize ),
  213. mFreeListHead( NULL )
  214. {
  215. }
  216. FreeListChunkerUntyped(U32 inElementSize, S32 size = DataChunker::ChunkSize)
  217. : mElementSize( inElementSize ),
  218. mFreeListHead( NULL )
  219. {
  220. mChunker = new DataChunker( size );
  221. mOwnChunker = true;
  222. }
  223. ~FreeListChunkerUntyped()
  224. {
  225. if ( mOwnChunker )
  226. delete mChunker;
  227. }
  228. void *alloc()
  229. {
  230. if(mFreeListHead == NULL)
  231. return mChunker->alloc(mElementSize);
  232. void *ret = mFreeListHead;
  233. mFreeListHead = *(reinterpret_cast<void**>(mFreeListHead));
  234. return ret;
  235. }
  236. void free(void* elem)
  237. {
  238. *(reinterpret_cast<void**>(elem)) = mFreeListHead;
  239. mFreeListHead = elem;
  240. }
  241. // Allow people to free all their memory if they want.
  242. void freeBlocks()
  243. {
  244. mChunker->freeBlocks();
  245. // We have to terminate the freelist as well or else we'll run
  246. // into crazy unused memory.
  247. mFreeListHead = NULL;
  248. }
  249. U32 getElementSize() const { return mElementSize; }
  250. private:
  251. DataChunker *mChunker;
  252. bool mOwnChunker;
  253. const U32 mElementSize;
  254. void *mFreeListHead;
  255. };
  256. #endif