1 /*
2 * Copyright (C) 1998-2002 Tom Holroyd <tomh@kurage.nimh.nih.gov>
3 * Copyright (C) 2006-2009 Stephan Kulow <coolo@kde.org>
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 2 of
8 * the License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #ifndef MEMORY_H
20 #define MEMORY_H
21
22 // Std
23 #include <cstdlib>
24 #include <sys/types.h>
25
26 struct TREE;
27
28 /* Memory. */
29
30 struct BLOCK;
31 struct BLOCK {
32 unsigned char *block;
33 unsigned char *ptr;
34 size_t remain;
35 BLOCK *next;
36 };
37
38 struct TREELIST;
39 struct TREELIST {
40 TREE *tree;
41 unsigned int cluster;
42 TREELIST *next;
43 };
44
45 /* Position information. We store a compact representation of the position;
46 Temp cells are stored separately since they don't have to be compared.
47 We also store the move that led to this position from the parent, as well
48 as a pointers back to the parent, and the btree of all positions examined so
49 far. */
50 struct TREE {
51 TREE *left;
52 TREE *right;
53 short depth;
54 };
55
56 #ifdef ERR
57 #undef ERR
58 #endif
59
60 class MemoryManager
61 {
62 public:
63 enum inscode { NEW, FOUND, ERR };
64
65 unsigned char *new_from_block(size_t s);
66 void init_clusters(void);
67 void free_blocks(void);
68 void free_clusters(void);
69 TREELIST *cluster_tree(unsigned int cluster);
70 inscode insert_node(TREE *n, int d, TREE **tree, TREE **node);
71 void give_back_block(unsigned char *p);
72
73 BLOCK *new_block(void);
74
75 template<class T>
free_ptr(T * ptr)76 static void free_ptr(T *ptr) {
77 free(ptr); Mem_remain += sizeof(T);
78 }
79
80 template<class T>
free_array(T * ptr,size_t size)81 static void free_array(T *ptr, size_t size) {
82 free(ptr);
83 Mem_remain += size * sizeof(T);
84 }
85
86 static void *allocate_memory(size_t s);
87
88 // ugly hack
89 int Pilebytes;
90 static size_t Mem_remain;
91 private:
92 BLOCK *Block;
93
94 };
95
96 template<typename T>
mm_new_array(const size_t size)97 T* mm_new_array(const size_t size) {
98 return static_cast<T*>(MemoryManager::allocate_memory(size * sizeof(T)));
99 }
100
101 template<typename T>
mm_allocate()102 T* mm_allocate() {return static_cast<T*>(MemoryManager::allocate_memory(sizeof(T)));}
103
104 #endif // MEMORY_H
105