1 // 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 
15 #pragma once
16 
17 #include "aemu/base/Compiler.h"
18 
19 #include <functional>
20 
21 #include <inttypes.h>
22 
23 // Convenience class ContiguousRangeMapper which makes it easier to collect
24 // contiguous ranges and run some function over the coalesced range.
25 
26 namespace android {
27 namespace base {
28 
29 class ContiguousRangeMapper {
30 public:
31     using Func = std::function<void(uintptr_t, uintptr_t)>;
32 
33     ContiguousRangeMapper(Func&& mapFunc, uintptr_t batchSize = 0) :
mMapFunc(std::move (mapFunc))34         mMapFunc(std::move(mapFunc)), mBatchSize(batchSize) { }
35 
36     // add(): adds [start, start + size) to the internally tracked range.
37     // mMapFunc on the previous range runs if the new piece is not contiguous.
38 
39     void add(uintptr_t start, uintptr_t size);
40 
41     // Signals end of collection of pieces, running mMapFunc over any
42     // outstanding range.
43     void finish();
44 
45     // Destructor all runs mMapFunc if there is an outstanding range.
46     ~ContiguousRangeMapper();
47 
48 private:
49     Func mMapFunc = {};
50     uintptr_t mBatchSize = 0;
51     bool mHasRange = false;
52     uintptr_t mStart = 0;
53     uintptr_t mEnd = 0;
54     DISALLOW_COPY_ASSIGN_AND_MOVE(ContiguousRangeMapper);
55 };
56 
57 }  // namespace base
58 }  // namespace android
59