memory_pool_impl.h revision a51ef01822ac68061a1d6e686389cfbcb0e1f8da
1/* 2 * Copyright (C) 2016 The Android Open Source Project 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 CHRE_UTIL_MEMORY_POOL_IMPL_H_ 18#define CHRE_UTIL_MEMORY_POOL_IMPL_H_ 19 20#include "chre/util/memory_pool.h" 21 22#include <utility> 23 24namespace chre { 25template<typename ElementType, size_t kSize> 26MemoryPool<ElementType, kSize>::MemoryPool() { 27 // Initialize the free block list. The initial condition is such that each 28 // block points to the next as being empty. The mFreeBlockCount is used to 29 // ensure that we never allocate out of bounds so we don't need to worry about 30 // the last block referring to one that is non-existent. 31 for (size_t i = 0; i < kSize; i++) { 32 blocks()[i].mNextFreeBlockIndex = i + 1; 33 } 34} 35 36template<typename ElementType, size_t kSize> 37template<typename... Args> 38ElementType *MemoryPool<ElementType, kSize>::allocate(Args&&... args) { 39 if (mFreeBlockCount == 0) { 40 return nullptr; 41 } 42 43 size_t blockIndex = mNextFreeBlockIndex; 44 mNextFreeBlockIndex = blocks()[blockIndex].mNextFreeBlockIndex; 45 mFreeBlockCount--; 46 47 return new (&blocks()[blockIndex].mElement) 48 ElementType(std::forward<Args>(args)...); 49} 50 51template<typename ElementType, size_t kSize> 52void MemoryPool<ElementType, kSize>::deallocate(ElementType *element) { 53 uintptr_t elementAddress = reinterpret_cast<uintptr_t>(element); 54 uintptr_t baseAddress = reinterpret_cast<uintptr_t>(&blocks()[0].mElement); 55 size_t blockIndex = (elementAddress - baseAddress) / sizeof(MemoryPoolBlock); 56 57 blocks()[blockIndex].mElement.~ElementType(); 58 blocks()[blockIndex].mNextFreeBlockIndex = mNextFreeBlockIndex; 59 mNextFreeBlockIndex = blockIndex; 60 mFreeBlockCount++; 61} 62 63template<typename ElementType, size_t kSize> 64typename MemoryPool<ElementType, kSize>::MemoryPoolBlock 65 *MemoryPool<ElementType, kSize>::blocks() { 66 return reinterpret_cast<MemoryPoolBlock *>(mBlocks); 67} 68 69} // namespace chre 70 71#endif // CHRE_UTIL_MEMORY_POOL_IMPL_H_ 72