|
|
1.1 parser 1: /** @file
2: Parser: CGI: pool storage class decl.
3:
4: Copyright (c) 2001 ArtLebedev Group (http://www.artlebedev.com)
5: Author: Alexander Petrosyan <paf@design.ru> (http://design.ru/paf)
6:
1.2 ! parser 7: $Id: pool_storage.h,v 1.1 2001/10/22 17:16:14 parser Exp $
1.1 parser 8: */
9:
10: #ifndef PA_POOL_STORAGE_H
11: #define PA_POOL_STORAGE_H
12:
13: #include "pa_config_includes.h"
14:
15: /**
16: Dumb pool allocations accounter
17:
18: @todo implement at least simple suballocations
19: */
20:
1.2 ! parser 21: class Pool_storage;
! 22:
! 23: template<class T> class List {
1.1 parser 24: friend Pool_storage;
25: public:
26: List(int preallocate) :
27: items((T *)::malloc(preallocate*sizeof(T))),
28: allocated(0),
29: used(0) {
30: if(items) // successfully preallocated?
31: allocated=preallocate;
32: }
33:
34: ~List() {
35: ::free(items);
36: }
37:
38: bool add(T item) {
39: if(full())
40: if(!expand())
41: return false;
42:
43: items[used++]=item;
44: return true;
45: }
46:
47: private:
48:
49: bool full() { return used==allocated; }
50: bool expand() {
51: size_t new_allocated=allocated*3/2;
52: T *new_items=(T *)::realloc(items, new_allocated*sizeof(T));
53: if(new_items) {
54: items=new_items;
55: allocated=new_allocated;
56: return true;
57: } else
58: return false;
59: }
60:
61: private:
62:
63: T *items;
64: size_t allocated;
65: size_t used;
66:
67: };
68:
1.2 ! parser 69: class Pool_storage {
1.1 parser 70: struct Cleanup_struct {
71: void (*cleanup) (void *);
72: void *data;
73: };
74:
75:
76: public:
77:
78: Pool_storage() :
79: cleanups(100) {
80: }
81:
82: bool register_cleanup(void (*cleanup) (void *), void *data) {
83: Cleanup_struct item={cleanup, data};
84: return cleanups.add(item)!=0;
85: }
86:
87: ~Pool_storage() {
88: size_t top;
89:
90: // cleanups first, because they use some object's memory pointers
91: // Cleanup_structs
92: for(top=cleanups.used; top; ) {
93: Cleanup_struct& item=cleanups.items[--top];
94: item.cleanup(item.data);
95: }
96: }
97:
98: private:
99:
100: List<Cleanup_struct> cleanups;
101:
102: };
103:
104:
105: #endif