1/*
2 * Copyright (c) 2021 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_FREE_OBJECT_SET_H
17#define ECMASCRIPT_MEM_FREE_OBJECT_SET_H
18
19#include <cstdint>
20
21#include "libpandabase/macros.h"
22#include "ecmascript/mem/jit_fort_memdesc.h"
23
24namespace panda::ecmascript {
25using SetType = int32_t;
26
27class FreeObject;
28
29template <typename T>
30class FreeObjectList;
31
32template <typename T>
33class FreeObjectSet {
34public:
35    explicit FreeObjectSet(SetType type) : setType_(type)
36    {
37        Rebuild();
38    }
39    explicit FreeObjectSet(SetType type, MemDescPool *pool) : setType_(type), memDescPool_(pool)
40    {
41        Rebuild();
42    }
43    ~FreeObjectSet() = default;
44
45    inline bool Empty() const
46    {
47        return available_ == 0;
48    }
49
50    inline size_t Available() const
51    {
52        return available_;
53    }
54
55    void Free(uintptr_t begin, size_t size);
56
57    void Rebuild();
58
59    T *LookupSmallFreeObject(size_t size);
60    T *LookupLargeFreeObject(size_t size);
61    T *ObtainSmallFreeObject(size_t size);
62    T *ObtainLargeFreeObject(size_t size);
63
64    NO_COPY_SEMANTIC(FreeObjectSet);
65    NO_MOVE_SEMANTIC(FreeObjectSet);
66
67    static constexpr SetType INVALID_SET_TYPE = -1;
68
69private:
70    FreeObjectSet *next_ = nullptr;
71    FreeObjectSet *prev_ = nullptr;
72    SetType setType_ = INVALID_SET_TYPE;
73    size_t available_ = 0;
74    uint64_t isAdded_ = 0; // 0: not added, 1: is added
75    T *freeObject_ = nullptr;
76    MemDescPool *memDescPool_ {nullptr};
77    friend class FreeObjectList<T>;
78};
79}  // namespace panda::ecmascript
80#endif  // ECMASCRIPT_MEM_FREE_OBJECT_SET_H
81