1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
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
16#ifndef ECMASCRIPT_MEM_HEAP_REGION_ALLOCATOR_H
17#define ECMASCRIPT_MEM_HEAP_REGION_ALLOCATOR_H
18
19#include <atomic>
20
21#include "ecmascript/mem/mem.h"
22
23namespace panda::ecmascript {
24class BaseHeap;
25class Region;
26class Space;
27
28class HeapRegionAllocator {
29public:
30    HeapRegionAllocator() = default;
31    virtual ~HeapRegionAllocator() = default;
32
33    Region *AllocateAlignedRegion(Space *space, size_t capacity, JSThread* thread, BaseHeap *heap,
34                                  bool isFresh = false);
35    void FreeRegion(Region *region, size_t cachedSize);
36
37    void IncreaseAnnoMemoryUsage(size_t bytes)
38    {
39        size_t current = annoMemoryUsage_.fetch_add(bytes, std::memory_order_relaxed) + bytes;
40        size_t max = maxAnnoMemoryUsage_.load(std::memory_order_relaxed);
41        while (current > max && !maxAnnoMemoryUsage_.compare_exchange_weak(max, current, std::memory_order_relaxed)) {
42        }
43    }
44
45    void DecreaseAnnoMemoryUsage(size_t bytes)
46    {
47        annoMemoryUsage_.fetch_sub(bytes, std::memory_order_relaxed);
48    }
49
50    size_t GetAnnoMemoryUsage() const
51    {
52        return annoMemoryUsage_.load(std::memory_order_relaxed);
53    }
54
55    size_t GetMaxAnnoMemoryUsage() const
56    {
57        return maxAnnoMemoryUsage_.load(std::memory_order_relaxed);
58    }
59
60private:
61    NO_COPY_SEMANTIC(HeapRegionAllocator);
62    NO_MOVE_SEMANTIC(HeapRegionAllocator);
63
64    std::atomic<size_t> annoMemoryUsage_ {0};
65    std::atomic<size_t> maxAnnoMemoryUsage_ {0};
66};
67}  // namespace panda::ecmascript
68
69#endif  // ECMASCRIPT_MEM_HEAP_REGION_ALLOCATOR_H
70