1 /* 2 * Copyright 2014 Google Inc. All rights reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef FRUIT_MEMORY_POOL_H 18 #define FRUIT_MEMORY_POOL_H 19 20 #include <vector> 21 22 namespace fruit { 23 namespace impl { 24 25 /** 26 * A pool of memory that never shrinks and is only deallocated on destruction. 27 * See also ArenaAllocator, an Allocator backed by a MemoryPool object. 28 */ 29 class MemoryPool { 30 private: 31 // 4KB - 64B. 32 // We don't use the full 4KB because malloc also needs to store some metadata for each block, and we want 33 // malloc to request <=4KB from the OS. 34 constexpr static const std::size_t CHUNK_SIZE = 4 * 1024 - 64; 35 36 std::vector<void*> allocated_chunks; 37 // The memory block [first_free, first_free + capacity) is available for allocation 38 char* first_free; 39 std::size_t capacity; 40 41 void destroy(); 42 43 public: 44 MemoryPool(); 45 46 MemoryPool(const MemoryPool&) = delete; 47 MemoryPool(MemoryPool&&); 48 MemoryPool& operator=(const MemoryPool&) = delete; 49 MemoryPool& operator=(MemoryPool&&); 50 ~MemoryPool(); 51 52 /** 53 * Returns a chunk of memory that can hold n T objects. 54 * Note that this does *not* construct any T objects at that location. 55 */ 56 template <typename T> 57 T* allocate(std::size_t n); 58 }; 59 60 } // namespace impl 61 } // namespace fruit 62 63 #include <fruit/impl/data_structures/memory_pool.defn.h> 64 65 #endif // FRUIT_MEMORY_POOL_H 66