1
#ifndef _RHEO_HEAP_ALLOCATOR_H
2
#define _RHEO_HEAP_ALLOCATOR_H
4
/// This file is part of Rheolef.
6
/// Copyright (C) 2000-2009 Pierre Saramito <Pierre.Saramito@imag.fr>
8
/// Rheolef is free software; you can redistribute it and/or modify
9
/// it under the terms of the GNU General Public License as published by
10
/// the Free Software Foundation; either version 2 of the License, or
11
/// (at your option) any later version.
13
/// Rheolef is distributed in the hope that it will be useful,
14
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
15
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
/// GNU General Public License for more details.
18
/// You should have received a copy of the GNU General Public License
19
/// along with Rheolef; if not, write to the Free Software
20
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22
/// =========================================================================
24
#include "rheolef/compiler.h"
27
class heap_allocator {
29
typedef size_t size_type;
30
heap_allocator(size_type sizeof_bucket = sizeof(T));
33
void reinitialize (size_type sizeof_bucket = sizeof(T));
36
std::list<std::vector<char> > _heap;
37
size_type _heap_block_size;
38
size_type _heap_block_last_free;
39
size_type _sizeof_bucket;
41
static const size_type _heap_block_size_init = 10;
45
heap_allocator<T>::heap_allocator(size_type sz)
47
_heap_block_size(_heap_block_size_init),
48
_heap_block_last_free(0),
52
_heap.push_front(std::vector<char>(_heap_block_size*_sizeof_bucket));
57
heap_allocator<T>::reinitialize (size_type sz)
60
_heap_block_size = heap_allocator<T>::_heap_block_size_init;
61
_heap_block_last_free = 0;
64
_heap.push_front(std::vector<char>(_heap_block_size*_sizeof_bucket));
69
heap_allocator<T>::new_bucket()
71
if (_heap_block_last_free == _heap_block_size) {
72
_heap_block_size *= 2;
73
_heap.push_front(std::vector<char>(_heap_block_size*_sizeof_bucket));
74
_heap_block_last_free = 0;
76
std::vector<char>& block = *(_heap.begin());
77
char* p = &block [_heap_block_last_free*_sizeof_bucket];
78
_heap_block_last_free++;
79
new ((void*) p) T(); // call default T constructor at p
85
heap_allocator<T>::~heap_allocator()
91
heap_allocator<T>::clear()
93
size_type n = _heap_block_size_init;
94
for (std::list<std::vector<char> >::reverse_iterator i = _heap.rbegin();
95
_counter != 0 && i != _heap.rend(); i++, n *= 2) {
96
std::vector<char>& block = *i;
97
char* p = &(block[0]);
98
for (size_type c = 0; _counter != 0 && c < n; c++, p += _sizeof_bucket) {
103
_heap.erase(_heap.begin(), _heap.end());
105
#endif // _RHEO_HEAP_ALLOCATOR_H