Qualia  0.2
Allocator.h
Go to the documentation of this file.
1 /*
2  * Allocator.h
3  *
4  * Allows for different implementation of memory allocation methods.
5  *
6  * This file is part of Qualia https://github.com/sofian/qualia
7  *
8  * (c) 2011 Sofian Audry -- info(@)sofianaudry(.)com
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program. If not, see <http://www.gnu.org/licenses/>.
22  */
23 #ifndef ALLOCATOR_H_
24 #define ALLOCATOR_H_
25 
26 #include "common.h"
27 
28 #if is_computer()
29 #include <new>
30 #endif
31 
32 #include <stddef.h>
33 #include <stdlib.h>
34 
40 class Allocator {
41 public:
42  virtual ~Allocator() {}
43 
44  virtual void* malloc(size_t size);
45  virtual void* calloc(size_t num, size_t size);
46  virtual void* realloc(void* ptr, size_t size);
47  virtual void free(void* ptr);
48 };
49 
75 class Alloc {
76  static Allocator* inst;
77 
78 public:
79  static void* malloc(size_t size);
80  static void* calloc(size_t num, size_t size);
81  static void* realloc(void* ptr, size_t size);
82  static void free(void* ptr);
83  static void init(Allocator* alloc);
84  static Allocator* instance() { return inst; }
85 };
86 
88 #define Q_NEW(T) new( Alloc::malloc(sizeof(T)) ) T
89 
90 //void * operator new(size_t size, Allocator* alloc);
91 //#define Q_NEW(T) new( Alloc::instance() ) T
92 //#define _NEW new( Alloc::instance() )
93 
94 //template<class T> T* _Q_ALLOC() { return Alloc::malloc(sizeof(T)); }
95 
96 
98 template<class T>
99 void Q_DELETE(T* obj) {
100  obj->~T(); Alloc::free(obj);
101 }
102 
103 template<class T>
104 T* __Q_ARRAY_NEW(size_t n) {
105  size_t* ptr = (size_t*) Alloc::malloc(2*sizeof(size_t) + n * sizeof(T));
106  *ptr++ = n;
107  *ptr++ = sizeof(T);
108  return new( ptr ) T[n];
109 }
110 
116 #define Q_ARRAY_NEW(T,n) __Q_ARRAY_NEW<T>(n)
117 
122 template<class T>
123 void Q_ARRAY_DELETE(T* array) {
124  size_t* ptr = (size_t*) array;
125  ptr-=2;
126  size_t n = ptr[0];
127  size_t elemSize = ptr[1];
128  unsigned char* iter = (unsigned char*)array;
129  while (n--) {
130  ((T*)iter)->~T();
131  iter += elemSize;
132  }
133  Alloc::free( ptr );
134 }
135 
136 #endif /* ALLOCATOR_H_ */