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