00001
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036 #ifndef eman__emcache__h__
00037 #define eman__emcache__h__ 1
00038
00039 #include <cstdlib>
00040 #include <string>
00041 #include <map>
00042
00043 using std::string;
00044 using std::map;
00045
00046 namespace EMAN
00047 {
00053 template < class T > class EMCache
00054 {
00055 public:
00056 explicit EMCache(int cache_size)
00057 {
00058 item_cache = new T *[cache_size];
00059 name_cache = new string[cache_size];
00060
00061 size = cache_size;
00062 nitems = 0;
00063 }
00064
00065 ~EMCache()
00066 {
00067 for (int i = 0; i < nitems; i++) {
00068 if( item_cache[i] )
00069 {
00070 delete item_cache[i];
00071 item_cache[i] = 0;
00072 }
00073 }
00074
00075 if( item_cache )
00076 {
00077 delete[]item_cache;
00078 item_cache = 0;
00079 }
00080
00081 if( name_cache )
00082 {
00083 delete[]name_cache;
00084 name_cache = 0;
00085 }
00086 }
00087
00088
00089 T *get(const string & itemname) const
00090 {
00091 T *result = 0;
00092
00093 for (int i = 0; i < nitems; i++)
00094 {
00095 if (name_cache[i] == itemname) {
00096 result = item_cache[i];
00097 break;
00098 }
00099 }
00100
00101 return result;
00102 }
00103
00104 void add(const string & itemname, T * item)
00105 {
00106 if (!item) {
00107 return;
00108 }
00109
00110 if (nitems < size) {
00111 item_cache[nitems] = item;
00112 name_cache[nitems] = itemname;
00113 nitems++;
00114 }
00115 else {
00116 int r = (int) (1.0 * size * rand() / (RAND_MAX + 1.0));
00117 if( item_cache[r] )
00118 {
00119 delete item_cache[r];
00120 item_cache[r] = 0;
00121 }
00122
00123 item_cache[r] = item;
00124 name_cache[r] = itemname;
00125 }
00126 }
00127
00128 void remove(const string & itemname)
00129 {
00130 int r = -1;
00131 for (int i = 0; i < nitems; i++) {
00132 if (name_cache[i] == itemname) {
00133 r = i;
00134 break;
00135 }
00136 }
00137 if (r >= 0) {
00138 if( item_cache[r] )
00139 {
00140 delete item_cache[r];
00141 item_cache[r] = 0;
00142 }
00143 name_cache[r] = "";
00144 }
00145 }
00146
00147 int get_size() const
00148 {
00149 return size;
00150 }
00151
00152 private:
00153 T ** item_cache;
00154 string *name_cache;
00155
00156 int size;
00157 int nitems;
00158 };
00159
00160 class ImageIO;
00161
00165 class GlobalCache
00166 {
00167 public:
00168 static GlobalCache *instance();
00169
00170 ImageIO *get_imageio(const string & filename, int rw_mode);
00171 void add_imageio(const string & filename, int rw_mode, ImageIO * io);
00172
00173 private:
00174 EMCache < ImageIO > *imageio_cache;
00175 static GlobalCache *global_cache;
00176 map < string, int >file_rw_dict;
00177
00178
00179 GlobalCache();
00180 GlobalCache(const GlobalCache & gc);
00181 ~GlobalCache();
00182
00183 };
00184
00185 }
00186
00187 #endif