Salome HOME
ObjectPool and SMDS_Position
[modules/smesh.git] / src / SMDS / ObjectPool.hxx
1
2 #ifndef _OBJECTPOOL_HXX_
3 #define _OBJECTPOOL_HXX_
4
5 #include <vector>
6 #include <stack>
7 #include <iostream>
8
9 template <class X> class ObjectPool
10 {
11
12 private:
13   std::vector<X*> _chunkList;
14   std::vector<bool> _freeList;
15   int _nextFree;
16   int _maxAvail;
17   int _chunkSize;
18
19   int getNextFree()
20   {
21     for (int i=_nextFree; i< _maxAvail; i++)
22       if (_freeList[i] == true)
23         {
24           return i;
25           break;
26         }
27     return _maxAvail;
28   }
29
30   void checkDelete(int chunkId)
31   {
32     int i0 = _chunkSize*chunkId;
33     int i1 =_chunkSize*(chunkId+1);
34     for (int i=i0; i < i1; i++)
35       if (_freeList[i] == false)
36         return;
37     std::cerr << "a chunk to delete" << std::endl;
38     // compactage des vecteurs un peu lourd, pas necessaire
39     //X* chunk = _chunkList[chunkId];
40     //delete [] chunk;
41   }
42
43 public:
44   ObjectPool(int nblk)
45   {
46     _chunkSize = nblk;
47     _nextFree = 0;
48     _maxAvail = 0;
49     _chunkList.clear();
50     _freeList.clear();
51   }
52
53   virtual ~ObjectPool()
54   {
55     for (int i=0; i<_chunkList.size(); i++)
56       delete [] _chunkList[i];
57   }
58
59   X* getNew()
60   {
61     X *obj = 0;
62     _nextFree = getNextFree();
63     if (_nextFree == _maxAvail)
64       {
65         X* newChunk = new X[_chunkSize];
66         _chunkList.push_back(newChunk);
67         _freeList.insert(_freeList.end(), _chunkSize, true);
68         _maxAvail += _chunkSize;
69         _freeList[_nextFree] = false;
70         obj = newChunk; // &newChunk[0];
71       }
72     else
73       {
74         int chunkId = _nextFree/_chunkSize;
75         int rank = _nextFree - chunkId*_chunkSize;
76         _freeList[_nextFree] = false;
77         obj = _chunkList[chunkId] + rank; // &_chunkList[chunkId][rank];
78       }
79     //obj->init();
80     return obj;
81   }
82
83   void destroy(X* obj)
84   {
85     long adrobj = (long)(obj);
86     for (int i=0; i< _chunkList.size(); i++)
87     {
88       X* chunk = _chunkList[i];
89       long adrmin = (long)(chunk);
90       if (adrobj < adrmin) continue;
91       long adrmax = (long)(chunk + _chunkSize);
92       if (adrobj >= adrmax) continue;
93       int rank = (adrobj -adrmin)/sizeof(X);
94       int toFree = i*_chunkSize + rank;
95       _freeList[toFree] = true;
96       if (toFree < _nextFree) _nextFree = toFree;
97       //obj->clean();
98       //checkDelete(i); compactage non fait
99       break;
100     }
101   }
102
103 };
104
105 #endif