6 #ifndef JSONCPP_BATCHALLOCATOR_H_INCLUDED
7 #define JSONCPP_BATCHALLOCATOR_H_INCLUDED
12 #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
28 template <
typename AllocatedType, const
unsigned int objectPerAllocation>
29 class BatchAllocator {
31 BatchAllocator(
unsigned int objectsPerPage = 255)
32 : freeHead_(0), objectsPerPage_(objectsPerPage) {
35 assert(
sizeof(AllocatedType) * objectPerAllocation >=
36 sizeof(AllocatedType *));
38 assert(objectsPerPage >= 16);
39 batches_ = allocateBatch(0);
40 currentBatch_ = batches_;
44 for (BatchInfo *batch = batches_; batch;) {
45 BatchInfo *nextBatch = batch->next_;
54 AllocatedType *allocate() {
57 AllocatedType *
object = freeHead_;
58 freeHead_ = *(AllocatedType **)
object;
61 if (currentBatch_->used_ == currentBatch_->end_) {
62 currentBatch_ = currentBatch_->next_;
63 while (currentBatch_ && currentBatch_->used_ == currentBatch_->end_)
64 currentBatch_ = currentBatch_->next_;
68 currentBatch_ = allocateBatch(objectsPerPage_);
69 currentBatch_->next_ = batches_;
70 batches_ = currentBatch_;
73 AllocatedType *allocated = currentBatch_->used_;
74 currentBatch_->used_ += objectPerAllocation;
81 void release(AllocatedType *
object) {
83 *(AllocatedType **)
object = freeHead_;
92 AllocatedType buffer_[objectPerAllocation];
96 BatchAllocator(
const BatchAllocator &);
97 void operator=(
const BatchAllocator &);
99 static BatchInfo *allocateBatch(
unsigned int objectsPerPage) {
100 const unsigned int mallocSize =
101 sizeof(BatchInfo) -
sizeof(AllocatedType) * objectPerAllocation +
102 sizeof(AllocatedType) * objectPerAllocation * objectsPerPage;
103 BatchInfo *batch = static_cast<BatchInfo *>(malloc(mallocSize));
105 batch->used_ = batch->buffer_;
106 batch->end_ = batch->buffer_ + objectsPerPage;
111 BatchInfo *currentBatch_;
113 AllocatedType *freeHead_;
114 unsigned int objectsPerPage_;
119 #endif // ifndef JSONCPP_DOC_INCLUDE_IMPLEMENTATION
121 #endif // JSONCPP_BATCHALLOCATOR_H_INCLUDED