blob: 2ee768eef1aa797dd363cd1a59cc5dce11b2326f [file] [log] [blame]
Jeff Brown46b9ac02010-04-22 18:58:52 -07001/*
2 * Copyright (C) 2010 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 UTILS_POOL_H
18#define UTILS_POOL_H
19
20#include <utils/TypeHelpers.h>
21
22namespace android {
23
24class PoolImpl {
25public:
26 PoolImpl(size_t objSize);
27 ~PoolImpl();
28
29 void* allocImpl();
30 void freeImpl(void* obj);
31
32private:
33 size_t mObjSize;
34};
35
36/*
37 * A homogeneous typed memory pool for fixed size objects.
38 * Not intended to be thread-safe.
39 */
40template<typename T>
41class Pool : private PoolImpl {
42public:
43 /* Creates an initially empty pool. */
44 Pool() : PoolImpl(sizeof(T)) { }
45
46 /* Destroys the pool.
47 * Assumes that the pool is empty. */
48 ~Pool() { }
49
50 /* Allocates an object from the pool, growing the pool if needed. */
51 inline T* alloc() {
52 void* mem = allocImpl();
53 if (! traits<T>::has_trivial_ctor) {
54 return new (mem) T();
55 } else {
56 return static_cast<T*>(mem);
57 }
58 }
59
60 /* Frees an object from the pool. */
61 inline void free(T* obj) {
62 if (! traits<T>::has_trivial_dtor) {
63 obj->~T();
64 }
65 freeImpl(obj);
66 }
67};
68
69} // namespace android
70
71#endif // UTILS_POOL_H