summaryrefslogtreecommitdiff
path: root/os/pool.h
blob: 1cb0a717b7992b12015c3d18253408d9323b8297 (plain)
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#ifndef POOL_H
#define POOL_H

#include "stdint.h"

template<class T>
class BasePool {
	public:
		struct Element {
			unsigned int use_count;
			BasePool* pool;
			
			char data[sizeof(T)];
		};
		
		virtual void free(Element* e) = 0;
};

template<class T>
class P {
	private:
		typedef typename BasePool<T>::Element Element;
		
		Element* e;
		
		void inc() {
			e->use_count++;
		}
		
		void dec() {
			e->use_count--;
			if(!e->use_count) {
				T* p = (T*)e->data;
				p->~T();
				e->pool->free(e);
			}
		}
	
	public:
		P() : e(0) {}
		
		explicit P(Element* ep) : e(ep) {
			inc();
		}
		
		P(const P& p) : e(p.e) {
			inc();
		}
		
		~P() {
			if(e) {
				dec();
			}
		}
		
		void operator=(const P& p) {
			if(e) {
				dec();
			}
			
			e = p.e;
			
			if(e) {
				inc();
			}
		}
		
		void reset() {
			if(e) {
				dec();
			}
			
			e = 0;
		}
		
		T* operator->() {
			return (T*)e->data;
		}
		
		T* operator*() {
			return (T*)e->data;
		}
		
		operator bool() {
			return bool(e);
		}
};

template<class T, unsigned int size>
class Pool : public BasePool<T> {
	private:
		typedef typename BasePool<T>::Element Element;
		
		union Node {
			Element e;
			Node* next;
		};
		
		Node elements[size];
		
		Node* next_free;
		
		void free(Element* e) {
			Node* n = (Node*)e;
			
			n->next = next_free;
			next_free = n;
		}
		
		Element* alloc() {
			if(!next_free) {
				return 0;
			}
			
			Element* e = &next_free->e;
			next_free = next_free->next;
			
			e->use_count = 0;
			e->pool = this;
			
			return e;
		}
	
	public:
		Pool() : next_free(0) {
			for(unsigned int i = 0; i < size; i++) {
				free(&elements[i].e);
			}
		}
		
		P<T> create() {
			Element* e = alloc();
			
			if(!e) {
				return P<T>();
			}
			
			new (e->data) T;
			
			return P<T>(e);
		}
};

void* operator new(unsigned int, char* buf);

#endif