extensionPool.h revision 12855:588919e0e4aa
1/*****************************************************************************
2
3  Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
4  more contributor license agreements.  See the NOTICE file distributed
5  with this work for additional information regarding copyright ownership.
6  Accellera licenses this file to you under the Apache License, Version 2.0
7  (the "License"); you may not use this file except in compliance with the
8  License.  You may obtain a copy of the License at
9
10    http://www.apache.org/licenses/LICENSE-2.0
11
12  Unless required by applicable law or agreed to in writing, software
13  distributed under the License is distributed on an "AS IS" BASIS,
14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15  implied.  See the License for the specific language governing
16  permissions and limitations under the License.
17
18 *****************************************************************************/
19
20#ifndef __EXTENSION_POOL_H__
21#define __EXTENSION_POOL_H__
22
23template <class T>
24class ExtensionPool{
25  struct entry{
26    public:
27    entry(T* content){
28      that=content;
29      next=NULL;
30    }
31    T* that;
32    entry* next;
33  };
34
35public:
36  ExtensionPool(int size): used(NULL){
37    unused=new entry(new T());  //create first one
38    mine.push_back(unused->that);
39    for (int i=0; i<size-1; i++){
40      entry* e=new entry(new T());
41      e->next=unused;
42      unused=e;
43      mine.push_back(unused->that);
44    }
45  }
46
47  ~ExtensionPool(){
48    //delete all T* that belong to this pool
49    for (unsigned int i=0; i<mine.size(); i++){
50      delete mine[i];
51    }
52
53    //delete all unused elements
54    while (unused){
55      entry* e=unused;
56      unused=unused->next;
57      delete e;
58    }
59
60    //delete all used elements
61    while (used){
62      entry* e=used;
63      used=used->next;
64      delete e;
65    }
66  }
67
68  bool is_from(T* cont){ //slow!!!
69    for (int i=0; i<mine.size(); i++){
70      if (mine[i]==cont) return true;
71    }
72    return false;
73  }
74
75  T* construct(){
76    entry* e;
77    if (unused==NULL){
78      e=new entry(new T());
79      mine.push_back(e->that);
80    }
81    else{
82      e=unused;
83      unused=unused->next;
84    }
85    e->next=used;
86    used=e;
87    return used->that; //if all elements of pool are used, just create a new one and go on
88  }
89
90  void free (T* cont){
91    sc_assert(used);
92    entry* e=used;
93    used=e->next;
94    e->that=cont;
95    e->next=unused;
96    unused=e;
97  }
98
99private:
100  entry* unused;
101  entry* used;
102  std::vector<T*> mine; //just for clean up and is_from
103};
104
105#endif
106
107