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