00001 #ifndef CACHE_H_ 00002 #define CACHE_H_ 00003 00004 #include <utility/malloc.h> 00005 00006 template<class Tp, bool b> 00007 struct Destroy { 00008 inline Destroy(Tp& tp) {} 00009 }; 00010 00011 template<class Tp> 00012 struct Destroy<Tp, true> { 00013 inline Destroy(Tp& tp) { free(tp); } 00014 }; 00015 00016 template<class CachedTp, unsigned int cacheSize, bool destroy = true> 00017 class Cache { 00018 public: 00019 inline Cache() : _count(0) {} 00020 00021 inline ~Cache() { flush(); } 00022 00023 CachedTp uncache() { 00024 --_count; 00025 return _cache[_count]; 00026 } 00027 00028 void cache(const CachedTp& cached) { 00029 if (size() == capacity()) { 00030 CachedTp element = uncache(); 00031 Destroy<CachedTp, destroy> d(element); 00032 } 00033 _cache[_count++] = cached; 00034 } 00035 00036 void flush() { 00037 for (unsigned int i = 0; i < size(); i++) { 00038 Destroy<CachedTp, destroy> d(_cache[i]); 00039 } 00040 } 00041 00042 inline unsigned int size() { 00043 return _count; 00044 } 00045 00046 inline unsigned int capacity() { 00047 return cacheSize; 00048 } 00049 private: 00050 unsigned int _count; 00051 CachedTp _cache[cacheSize]; 00052 }; 00053 00054 #endif