blob: 14a39f8a661c1ab4c4198e3ca8b8e807383ea6eb [file] [log] [blame]
Lingfeng Yangea978ce2019-12-13 13:42:23 -08001// Copyright 2018 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14#pragma once
15
Yilong Lif35ede42021-04-30 13:05:50 -070016#include "android/base/Allocator.h"
17
Lingfeng Yangea978ce2019-12-13 13:42:23 -080018#include <unordered_set>
19
20#include <inttypes.h>
21#include <stddef.h>
22#include <string.h>
23
24namespace android {
25namespace base {
26
27// Class to make it easier to set up memory regions where it is fast
28// to allocate/deallocate buffers that have size within
29// the specified range.
Yilong Lif35ede42021-04-30 13:05:50 -070030class Pool : public Allocator {
Lingfeng Yangea978ce2019-12-13 13:42:23 -080031public:
32 // minSize/maxSize: the target range of sizes for which we want to
33 // make allocations fast. the greater the range, the more space
34 // traded off.
35 // chunksPerSize: the target maximum number of live objects of
36 // each size that are expected. the higher it is, the more space
37 // traded off.
38 //
39 // Rough space cost formula:
40 // O(chunksPerSize * log2(maxSize / minSize) * maxSize)
Lingfeng Yangfc62bd52020-11-03 09:04:39 -080041 Pool(size_t minSize = 4,
Lingfeng Yangea978ce2019-12-13 13:42:23 -080042 size_t maxSize = 4096,
Lingfeng Yangfc62bd52020-11-03 09:04:39 -080043 size_t chunksPerSize = 1024);
44
Lingfeng Yangea978ce2019-12-13 13:42:23 -080045 // All memory allocated by this pool
46 // is automatically deleted when the pool
47 // is deconstructed.
48 ~Pool();
49
Yilong Lif35ede42021-04-30 13:05:50 -070050 void* alloc(size_t wantedSize) override;
Lingfeng Yangea978ce2019-12-13 13:42:23 -080051 void free(void* ptr);
52
53 // Convenience function to free everything currently allocated.
54 void freeAll();
55
Lingfeng Yangea978ce2019-12-13 13:42:23 -080056private:
57 class Impl;
58 Impl* mImpl = nullptr;
59
60 std::unordered_set<void*> mFallbackPtrs;
61};
62
63} // namespace base
64} // namespace android