allocator.hpp 1.15 KB
Newer Older
PanZezhong's avatar
PanZezhong committed
1
2
3
4
#ifndef ALLOCATOR_HPP
#define ALLOCATOR_HPP

#include "infinicore_infer.h"
thatPepe's avatar
thatPepe committed
5
6
7
8
9
#include <map>
#include <memory>
#include <set>
#include <unordered_map>
#include <vector>
PanZezhong's avatar
PanZezhong committed
10
11
12
13
14

class AllocatorBase {
public:
    virtual void *alloc(size_t size) = 0;
    virtual void release(void *ptr) = 0;
thatPepe's avatar
thatPepe committed
15
    virtual ~AllocatorBase() = default;
PanZezhong's avatar
PanZezhong committed
16
17
};

thatPepe's avatar
thatPepe committed
18
class MemoryPool : public AllocatorBase {
PanZezhong's avatar
PanZezhong committed
19
public:
thatPepe's avatar
thatPepe committed
20
21
    MemoryPool(size_t initialSize = 0);
    ~MemoryPool();
PanZezhong's avatar
PanZezhong committed
22
23
    void *alloc(size_t size) override;
    void release(void *ptr) override;
thatPepe's avatar
thatPepe committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

private:
    struct Block {
        void *base;
        void *ptr;
        size_t size;
        bool is_free;
        Block(void *b, void *p, size_t s, bool f)
            : base(b), ptr(p), size(s), is_free(f) {}
        bool operator<(const Block &other) const {
            return ptr < other.ptr;
        }
    };

    void *allocateNewRegion(size_t size);
    void insertFreeBlock(Block &&block);
    void tryCoalesce(const Block &block);

    std::vector<void *> _base_regions;
    std::set<Block> _all_blocks;
    std::multimap<size_t, std::set<Block>::iterator> _free_blocks;
    std::unordered_map<void *, std::set<Block>::iterator> _ptr_to_block;
PanZezhong's avatar
PanZezhong committed
46
47
48
};

#endif