pluskid / pyppm

PPM (Predict by Partial Matching) compression algorithm implementation for Python

This URL has Read+Write access

pyppm / slab_allocator.h
100644 94 lines (79 sloc) 2.513 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#ifndef _SLAB_ALLOCATOR_H_
#define _SLAB_ALLOCATOR_H_
 
#include <new>
#include <algorithm>
 
////////////////////////////////////////////////////////////
// A slab allocator allocate memory for many objects of the
// same time.
//
// When memory is needed for an object, it first see whether
// there are free objects in the freelist. If not, it then
// look at the current block. It will request a new block if
// necessary. The new allocated block is not split into the
// freelist immediately. Only deallocated objects will be put
// into the freelist.
//
// When the slab allocator is destroyed, all the blocks are
// freed. The allocator will NOT call either constructor
// or destructor.
////////////////////////////////////////////////////////////
template<typename T, size_t Block_size=4096>
class SlabAllocator
{
private:
    struct Node
    {
        Node *next;
    };
 
    Node *m_blocks; // Allocated blocks chained together
 
    char *m_block; // Current block used for allocating
    size_t m_block_remain; // How many bytes remained for current block
 
    Node *m_freelist; // Released objects are chained here
 
    void get_new_block() {
        Node *block = (Node *)operator new(Block_size);
 
        // Link blocks for later release
        block->next = m_blocks;
        m_blocks = block;
 
        char *mem = (char *)block;
 
        // Skip the header used to link the blocks together
        size_t skip = std::max(sizeof(Node), sizeof(T));
        mem += skip;
 
        m_block = mem;
        m_block_remain = Block_size-skip;
    }
    
public:
    SlabAllocator()
        :m_blocks(NULL), m_block(NULL), m_block_remain(0), m_freelist(NULL) {
    }
    ~SlabAllocator() {
        Node *next;
        while (m_blocks != NULL) {
            next = m_blocks->next;
            delete m_blocks;
            m_blocks = next;
        }
    }
 
    // Allocate
    T *allocate() {
        if (m_freelist == NULL) {
            if (m_block_remain < sizeof(T)) {
                get_new_block();
            }
            T *res = (T *)m_block;
            m_block += sizeof(T);
            m_block_remain -= sizeof(T);
            return res;
        } else {
            Node *res = m_freelist;
            m_freelist = m_freelist->next;
            return (T *)res;
        }
    }
 
    // Release
    void release(T *t) {
        Node *obj = (Node *)t;
        obj->next = m_freelist;
        m_freelist = obj;
    }
};
 
#endif /* _SLAB_ALLOCATOR_H_ */