00001
00002
00003
00004
00005
00006
00007
00008
00009 #ifndef __PEEKABOT_ID_ALLOCATOR_HH
00010 #define __PEEKABOT_ID_ALLOCATOR_HH
00011
00012
00013 #include <stack>
00014
00015
00016 namespace peekabot
00017 {
00018
00026 template<class IDType>
00027 class IDAllocator
00028 {
00029 public:
00030 virtual ~IDAllocator() {}
00031
00036 virtual IDType allocate() = 0;
00037
00042 virtual void release(IDType id) = 0;
00043 };
00044
00045
00046
00047 template<typename IDType>
00048 class DefaultIDAllocator : public IDAllocator<IDType>
00049 {
00050 IDType m_next_id;
00051 const size_t m_reuse_limit;
00052 std::stack<IDType> m_reuse_stack;
00053
00054 public:
00055 DefaultIDAllocator(size_t reuse_limit = 100) throw()
00056 : m_next_id(1),
00057 m_reuse_limit(reuse_limit) {}
00058
00059 DefaultIDAllocator(IDType first, IDType last, size_t reuse_limit = 100) throw()
00060 : m_next_id(last+1),
00061 m_reuse_limit(reuse_limit) {}
00062
00063 virtual IDType allocate()
00064 {
00065 if( !m_reuse_stack.empty() )
00066 {
00067 IDType id = m_reuse_stack.top();
00068 m_reuse_stack.pop();
00069 return id;
00070 }
00071 else
00072 {
00073 return m_next_id++;
00074 }
00075 }
00076
00077 virtual void release(IDType id)
00078 {
00079 if( m_reuse_stack.size() < m_reuse_limit )
00080 m_reuse_stack.push(id);
00081 }
00082 };
00083
00084
00085 }
00086
00087
00088 #endif // __PEEKABOT_ID_ALLOCATOR_HH