00001 /* 00002 * Copyright (C) Sergey P. Derevyago, 2008-2009. 00003 * 00004 * Permission to copy, use, modify, sell and distribute this software is granted 00005 * provided this copyright notice appears in all copies. 00006 * This software is provided "as is" without express or implied warranty, and 00007 * with no claim as to its suitability for any purpose. 00008 * 00009 */ 00010 00016 #ifndef __DERS__BUF_CACHE_HPP__ 00017 #define __DERS__BUF_CACHE_HPP__ 00018 00019 #include <ders/config.hpp> 00020 #include <vector> 00021 00022 namespace ders { // ::ders 00023 00027 class mem_buf { 00028 void* buf; 00029 00030 mem_buf(const mem_buf&); 00031 mem_buf& operator=(const mem_buf&); 00032 00033 public: 00034 mem_buf(void* bf) : buf(bf) {} 00035 ~mem_buf() { operator delete(buf); } 00036 00037 void* get() const { return buf; } 00038 void release() { buf=0; } 00039 }; 00040 00045 class buf_cache { 00046 std::vector<void*> bufs; 00047 int bsz; 00048 00049 buf_cache(const buf_cache&); 00050 buf_cache& operator=(const buf_cache&); 00051 00052 public: 00053 buf_cache(int bsize) : bsz(bsize) {} 00054 ~buf_cache(); 00055 00056 void* take_buf(); 00057 void return_buf(mem_buf& mb); 00058 int buf_size() const { return bsz; } 00059 }; 00060 00061 inline buf_cache::~buf_cache() 00062 { 00063 for (int i=0, end=bufs.size(); i<end; i++) operator delete(bufs[i]); 00064 } 00065 00066 inline void* buf_cache::take_buf() 00067 { 00068 if (!bufs.size()) return operator new(bsz); 00069 00070 void* ret=bufs.back(); 00071 bufs.pop_back(); 00072 return ret; 00073 } 00074 00075 inline void buf_cache::return_buf(mem_buf& mb) 00076 { 00077 bufs.push_back(mb.get()); 00078 mb.release(); 00079 } 00080 00081 } // namespace ::ders 00082 00083 #endif // __DERS__BUF_CACHE_HPP__ 00084