source: icGREP/icgrep-devel/icgrep/slab_allocator.h @ 4388

Last change on this file since 4388 was 4272, checked in by nmedfort, 5 years ago

Implemented slab allocator based on the original Parabix StringPool?; intergrated it with RE and Pablo AST nodes.

File size: 2.2 KB
Line 
1#ifndef SLAB_ALLOCATOR_H
2#define SLAB_ALLOCATOR_H
3
4#include <cstddef>
5#include <cstdint>
6#include <new>
7#include <algorithm>
8#include <iostream>
9
10template <unsigned BasePoolSize>
11class SlabAllocator {
12public:
13
14    typedef std::size_t size_type;
15    typedef void* pointer;
16    typedef const void* const_pointer;
17
18    inline pointer allocate(size_type n) noexcept {
19        if (n > mSpaceAvail && !extend(n)) {
20            exit(-1);
21        }
22        pointer ptr = static_cast<pointer>(mAllocationPtr);
23        mAllocationPtr += n;
24        mSpaceAvail -= n;
25        return ptr;
26    }
27
28    inline void deallocate(pointer p) noexcept {
29        /* do nothing */
30    }
31
32    void release_memory();
33
34    SlabAllocator();
35    ~SlabAllocator();
36
37protected:
38    bool extend(const size_type n) noexcept;
39private:
40    struct Chunk {
41        Chunk *     prev;
42        uint8_t     space[BasePoolSize];
43    };
44    size_type       mSpaceAvail;
45    uint8_t *       mAllocationPtr;
46    Chunk *         mCurrentChunk;
47    size_type       mTotalSize;
48    Chunk           mInitialChunk;
49};
50
51template <unsigned BasePoolSize>
52SlabAllocator<BasePoolSize>::SlabAllocator()
53: mSpaceAvail(BasePoolSize)
54, mAllocationPtr(mInitialChunk.space)
55, mCurrentChunk(&mInitialChunk)
56, mTotalSize(BasePoolSize)
57{
58    mInitialChunk.prev = nullptr;
59}
60
61template <unsigned BasePoolSize>
62SlabAllocator<BasePoolSize>::~SlabAllocator() {
63    release_memory();
64}
65
66template <unsigned BasePoolSize>
67void SlabAllocator<BasePoolSize>::release_memory() {
68    while (mCurrentChunk != &mInitialChunk) {
69        Chunk * n = mCurrentChunk;
70        mCurrentChunk = n->prev;
71        free(n);
72    }
73    mSpaceAvail = BasePoolSize;
74    mAllocationPtr = mInitialChunk.space;
75}
76
77template <unsigned BasePoolSize>
78bool SlabAllocator<BasePoolSize>::extend(const size_type n) noexcept {
79    const size_type size = std::max<size_type>(n, mTotalSize) * 2;
80    Chunk * newChunk = (Chunk *)malloc(sizeof(Chunk) + size - BasePoolSize);
81    if (newChunk == nullptr) {
82        return false;
83    }
84    newChunk->prev = mCurrentChunk;
85    mTotalSize += size;
86    mCurrentChunk = newChunk;
87    mAllocationPtr = newChunk->space;
88    mSpaceAvail = size;
89    return true;
90}
91
92#endif // SLAB_ALLOCATOR_H
Note: See TracBrowser for help on using the repository browser.