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 <cinttypes>
23 #include <utility>
24
25 namespace chre {
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 blocks()[i].mNextFreeBlockIndex = 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 = blocks()[blockIndex].mNextFreeBlockIndex;
46 mFreeBlockCount--;
47
48 return new (&blocks()[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>(&blocks()[0].mElement);
56 size_t blockIndex = (elementAddress - baseAddress) / sizeof(MemoryPoolBlock);
57
58 blocks()[blockIndex].mElement.~ElementType();
59 blocks()[blockIndex].mNextFreeBlockIndex = mNextFreeBlockIndex;
60 mNextFreeBlockIndex = blockIndex;
61 mFreeBlockCount++;
62 }
63
64 template <typename ElementType, size_t kSize>
getFreeBlockCount()65 size_t MemoryPool<ElementType, kSize>::getFreeBlockCount() const {
66 return mFreeBlockCount;
67 }
68
69 template <typename ElementType, size_t kSize>
70 typename MemoryPool<ElementType, kSize>::MemoryPoolBlock *
blocks()71 MemoryPool<ElementType, kSize>::blocks() {
72 return reinterpret_cast<MemoryPoolBlock *>(mBlocks);
73 }
74
75 } // namespace chre
76
77 #endif // CHRE_UTIL_MEMORY_POOL_IMPL_H_
78